You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@aries.apache.org by gn...@apache.org on 2018/02/21 09:04:42 UTC
svn commit: r1824942 [3/4] - in /aries/trunk/jndi:
jndi-api/src/main/java/org/apache/aries/jndi/api/
jndi-api/src/main/java/org/apache/aries/jndi/spi/
jndi-api/src/main/java/org/apache/aries/jndi/urls/
jndi-bundle/src/main/java/org/apache/aries/jndi/pr...
Modified: aries/trunk/jndi/jndi-url-itest/src/test/java/org/apache/aries/jndi/itests/JndiUrlIntegrationTest.java
URL: http://svn.apache.org/viewvc/aries/trunk/jndi/jndi-url-itest/src/test/java/org/apache/aries/jndi/itests/JndiUrlIntegrationTest.java?rev=1824942&r1=1824941&r2=1824942&view=diff
==============================================================================
--- aries/trunk/jndi/jndi-url-itest/src/test/java/org/apache/aries/jndi/itests/JndiUrlIntegrationTest.java (original)
+++ aries/trunk/jndi/jndi-url-itest/src/test/java/org/apache/aries/jndi/itests/JndiUrlIntegrationTest.java Wed Feb 21 09:04:41 2018
@@ -19,21 +19,6 @@
package org.apache.aries.jndi.itests;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.ops4j.pax.exam.CoreOptions.composite;
-import static org.ops4j.pax.exam.CoreOptions.junitBundles;
-import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
-import static org.ops4j.pax.exam.CoreOptions.systemProperty;
-import static org.ops4j.pax.exam.CoreOptions.vmOption;
-import static org.ops4j.pax.exam.CoreOptions.when;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.HttpURLConnection;
-import java.net.URL;
-
import org.apache.aries.itest.AbstractIntegrationTest;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -45,141 +30,148 @@ import org.ops4j.pax.exam.spi.reactors.E
import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.osgi.framework.Bundle;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.ops4j.pax.exam.CoreOptions.*;
+
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
public class JndiUrlIntegrationTest extends AbstractIntegrationTest {
- private static final int CONNECTION_TIMEOUT = 10000;
-
+ private static final int CONNECTION_TIMEOUT = 10000;
+
+ private static HttpURLConnection makeConnection(String contextPath) throws IOException {
+ URL url = new URL(contextPath);
+ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-
- /**
- * This test exercises the blueprint:comp/ jndi namespace by driving
- * a Servlet which then looks up some blueprint components from its own
- * bundle, including a reference which it uses to call a service from a
- * second bundle.
- * @throws Exception
- */
- @Test
- public void testBlueprintCompNamespaceWorks() throws Exception {
-
- Bundle bBiz = context().getBundleByName("org.apache.aries.jndi.url.itest.biz");
- assertNotNull(bBiz);
-
- Bundle bweb = context().getBundleByName("org.apache.aries.jndi.url.itest.web");
- assertNotNull(bweb);
- context().getBundleByName("org.ops4j.pax.web.pax-web-extender-war").start();
- printBundleStatus ("Before making web request");
- try {
- Thread.sleep(5000);
- } catch (InterruptedException ix) {}
-
- System.out.println("In test and trying to get connection....");
- String response = getTestServletResponse();
- System.out.println("Got response `" + response + "`");
- assertEquals("ITest servlet response wrong", "Mark.2.0.three", response);
- }
-
- private void printBundleStatus (String msg) {
- System.out.println("-----\nprintBundleStatus: " + msg + "\n-----");
- for (Bundle b : bundleContext.getBundles()) {
- System.out.println (b.getSymbolicName() + " " + "state=" + formatState(b.getState()));
- }
- System.out.println();
- }
-
- private String formatState (int state) {
- String result = Integer.toString(state);
- switch (state) {
- case Bundle.ACTIVE:
- result = "Active";
- break;
- case Bundle.INSTALLED:
- result = "Installed";
- break;
- case Bundle.RESOLVED:
- result = "Resolved";
- break;
- }
- return result;
- }
-
- private String getTestServletResponse() throws IOException {
- HttpURLConnection conn = makeConnection("http://localhost:8080/jndiUrlItest/ITestServlet");
- String response = getHTTPResponse(conn).trim();
- return response;
- }
-
- private static HttpURLConnection makeConnection(String contextPath) throws IOException
- {
- URL url = new URL(contextPath);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-
- conn.setConnectTimeout(CONNECTION_TIMEOUT);
- conn.connect();
-
- return conn;
- }
-
- private static String getHTTPResponse(HttpURLConnection conn) throws IOException
- {
- StringBuilder response = new StringBuilder();
- BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-1"));
- try {
- for (String s = reader.readLine(); s != null; s = reader.readLine()) {
- response.append(s).append("\r\n");
- }
- } finally {
- reader.close();
- }
-
- return response.toString();
- }
-
- public Option baseOptions() {
- String localRepo = System.getProperty("maven.repo.local");
- if (localRepo == null) {
- localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository");
- }
- return composite(
- junitBundles(),
- // this is how you set the default log level when using pax
- // logging (logProfile)
- systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),
- when(localRepo != null).useOptions(vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo))
- );
- }
-
- @Configuration
- public Option[] configuration()
- {
- return CoreOptions.options(
- baseOptions(),
-
- // Bundles
- mavenBundle("org.eclipse.equinox", "cm").versionAsInProject(),
- mavenBundle("org.eclipse.osgi", "services").versionAsInProject(),
- mavenBundle("org.apache.geronimo.specs", "geronimo-servlet_2.5_spec").versionAsInProject(),
-
- mavenBundle("org.ops4j.pax.web", "pax-web-extender-war").versionAsInProject(),
- mavenBundle("org.ops4j.pax.web", "pax-web-jetty-bundle").versionAsInProject(),
-
- mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.api").versionAsInProject(),
- mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.core").versionAsInProject(),
- mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy").versionAsInProject(),
- mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(),
- mavenBundle("org.apache.aries.jndi", "org.apache.aries.jndi").versionAsInProject(),
-
- mavenBundle("org.apache.aries.jndi", "org.apache.aries.jndi.url.itest.web").versionAsInProject(),
- mavenBundle("org.apache.aries.jndi", "org.apache.aries.jndi.url.itest.biz").versionAsInProject(),
- mavenBundle("org.ow2.asm", "asm-debug-all").versionAsInProject(),
- mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(),
+ conn.setConnectTimeout(CONNECTION_TIMEOUT);
+ conn.connect();
- mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(),
- mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject()
+ return conn;
+ }
+
+ private static String getHTTPResponse(HttpURLConnection conn) throws IOException {
+ StringBuilder response = new StringBuilder();
+ BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-1"));
+ try {
+ for (String s = reader.readLine(); s != null; s = reader.readLine()) {
+ response.append(s).append("\r\n");
+ }
+ } finally {
+ reader.close();
+ }
+
+ return response.toString();
+ }
+
+ /**
+ * This test exercises the blueprint:comp/ jndi namespace by driving
+ * a Servlet which then looks up some blueprint components from its own
+ * bundle, including a reference which it uses to call a service from a
+ * second bundle.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testBlueprintCompNamespaceWorks() throws Exception {
+
+ Bundle bBiz = context().getBundleByName("org.apache.aries.jndi.url.itest.biz");
+ assertNotNull(bBiz);
+
+ Bundle bweb = context().getBundleByName("org.apache.aries.jndi.url.itest.web");
+ assertNotNull(bweb);
+ context().getBundleByName("org.ops4j.pax.web.pax-web-extender-war").start();
+ printBundleStatus("Before making web request");
+ try {
+ Thread.sleep(5000);
+ } catch (InterruptedException ix) {
+ }
+
+ System.out.println("In test and trying to get connection....");
+ String response = getTestServletResponse();
+ System.out.println("Got response `" + response + "`");
+ assertEquals("ITest servlet response wrong", "Mark.2.0.three", response);
+ }
+
+ private void printBundleStatus(String msg) {
+ System.out.println("-----\nprintBundleStatus: " + msg + "\n-----");
+ for (Bundle b : bundleContext.getBundles()) {
+ System.out.println(b.getSymbolicName() + " " + "state=" + formatState(b.getState()));
+ }
+ System.out.println();
+ }
+
+ private String formatState(int state) {
+ String result = Integer.toString(state);
+ switch (state) {
+ case Bundle.ACTIVE:
+ result = "Active";
+ break;
+ case Bundle.INSTALLED:
+ result = "Installed";
+ break;
+ case Bundle.RESOLVED:
+ result = "Resolved";
+ break;
+ }
+ return result;
+ }
+
+ private String getTestServletResponse() throws IOException {
+ HttpURLConnection conn = makeConnection("http://localhost:8080/jndiUrlItest/ITestServlet");
+ String response = getHTTPResponse(conn).trim();
+ return response;
+ }
+
+ public Option baseOptions() {
+ String localRepo = System.getProperty("maven.repo.local");
+ if (localRepo == null) {
+ localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository");
+ }
+ return composite(
+ junitBundles(),
+ // this is how you set the default log level when using pax
+ // logging (logProfile)
+ systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),
+ when(localRepo != null).useOptions(vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo))
+ );
+ }
+
+ @Configuration
+ public Option[] configuration() {
+ return CoreOptions.options(
+ baseOptions(),
+
+ // Bundles
+ mavenBundle("org.eclipse.equinox", "cm").versionAsInProject(),
+ mavenBundle("org.eclipse.osgi", "services").versionAsInProject(),
+ mavenBundle("org.apache.geronimo.specs", "geronimo-servlet_2.5_spec").versionAsInProject(),
+
+ mavenBundle("org.ops4j.pax.web", "pax-web-extender-war").versionAsInProject(),
+ mavenBundle("org.ops4j.pax.web", "pax-web-jetty-bundle").versionAsInProject(),
+
+ mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.api").versionAsInProject(),
+ mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.core").versionAsInProject(),
+ mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy").versionAsInProject(),
+ mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(),
+ mavenBundle("org.apache.aries.jndi", "org.apache.aries.jndi").versionAsInProject(),
+
+ mavenBundle("org.apache.aries.jndi", "org.apache.aries.jndi.url.itest.web").versionAsInProject(),
+ mavenBundle("org.apache.aries.jndi", "org.apache.aries.jndi.url.itest.biz").versionAsInProject(),
+ mavenBundle("org.ow2.asm", "asm-debug-all").versionAsInProject(),
+ mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(),
+
+ mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(),
+ mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject()
);
// org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=7777"),
// org.ops4j.pax.exam.CoreOptions.waitForFrameworkStartup(),
- }
+ }
}
Modified: aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/services/ServiceHelper.java
URL: http://svn.apache.org/viewvc/aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/services/ServiceHelper.java?rev=1824942&r1=1824941&r2=1824942&view=diff
==============================================================================
--- aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/services/ServiceHelper.java (original)
+++ aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/services/ServiceHelper.java Wed Feb 21 09:04:41 2018
@@ -18,41 +18,23 @@
*/
package org.apache.aries.jndi.services;
-import java.lang.ref.WeakReference;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import javax.naming.NamingException;
-
import org.apache.aries.jndi.url.Activator;
import org.apache.aries.jndi.url.OsgiName;
import org.apache.aries.proxy.ProxyManager;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.util.nls.MessageUtil;
-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.InvalidSyntaxException;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceException;
-import org.osgi.framework.ServiceListener;
-import org.osgi.framework.ServiceReference;
+import org.osgi.framework.*;
import org.osgi.service.jndi.JNDIConstants;
+import javax.naming.NamingException;
+import java.lang.ref.WeakReference;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.*;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
/**
* This helper provides access to services registered in the OSGi service registry.
* If a matching service cannot be located null may be returned. A caller should not
@@ -61,423 +43,403 @@ import org.osgi.service.jndi.JNDIConstan
* A caller should avoid caching the returned service. OSGi is a dynamic environment and
* the service may become unavailable while a reference to it is held. To minimize this
* risk the caller should hold onto the service for the minimum length of time.
- *
+ * <p>
* <p>This API should not be used from within an OSGi bundle. When in an OSGi environment
- * the BundleContext for the bundle should be used to obtain the service.
+ * the BundleContext for the bundle should be used to obtain the service.
* </p>
*/
-public final class ServiceHelper
-{
- public static final class CacheClearoutListener implements BundleListener, ServiceListener
- {
- /** The cache to purge */
- private final ConcurrentMap<ServiceKey, WeakReference<Object>> cache;
-
-
- public CacheClearoutListener(ConcurrentMap<ServiceKey, WeakReference<Object>> pc)
- {
- cache = pc;
- }
-
- public void bundleChanged(BundleEvent event)
- {
- if (event.getType() == BundleEvent.STOPPED) {
- Bundle b = event.getBundle();
- Iterator<ServiceKey> keys = cache.keySet().iterator();
- while (keys.hasNext()) {
- ServiceKey key = keys.next();
- if (key.requesting == b) keys.remove();
- }
- }
- }
-
- public void serviceChanged(ServiceEvent event)
- {
- if (event.getType() == ServiceEvent.UNREGISTERING) {
- ServiceReference ref = event.getServiceReference();
- Long serviceId = (Long) ref.getProperty(Constants.SERVICE_ID);
- Bundle registeringBundle = ref.getBundle();
- Iterator<ServiceKey> keys = cache.keySet().iterator();
- while (keys.hasNext()) {
- ServiceKey key = keys.next();
- if (key.registering == registeringBundle && serviceId.equals(key.serviceId)) {
- keys.remove();
- break;
- }
- }
- }
- }
-
- public void add(final BundleContext ctx, ServiceKey k)
- {
- // try to use the system bundle for our listener, if that fails we fall back to the calling context
- BundleContext systemBundle = AccessController.doPrivileged(new PrivilegedAction<BundleContext>() {
- public BundleContext run()
- {
- Bundle system = ctx.getBundle(0);
- return system == null ? null : system.getBundleContext();
- }
- });
- if (systemBundle == null) systemBundle = ctx;
- systemBundle.addBundleListener(cacheClearoutListener);
- systemBundle.addServiceListener(cacheClearoutListener);
- }
- }
-
- private static final class ServiceKey
- {
- private final Bundle requesting;
- private final Bundle registering;
- private final Long serviceId;
- private final int hash;
-
- public ServiceKey(Bundle owningBundle, Bundle registeringBundle, Long property)
- {
- requesting = owningBundle;
- registering = registeringBundle;
- serviceId = property;
- hash = serviceId.intValue() * 100003 + System.identityHashCode(requesting);
- }
-
- public int hashCode()
- {
- return hash;
- }
-
- public boolean equals(Object other)
- {
- if (other == this) return true;
- if (other == null) return false;
-
- if (other instanceof ServiceKey) {
- ServiceKey otherKey = (ServiceKey) other;
- return (otherKey.requesting == requesting && otherKey.serviceId.equals(serviceId));
- }
-
- return false;
- }
- }
-
- private static class JNDIServiceDamper implements Callable<Object>
- {
- private BundleContext ctx;
- private ServicePair pair;
- private String interfaceName;
- private String filter;
- private boolean dynamic;
- private int rebindTimeout;
-
- public JNDIServiceDamper(BundleContext context, String i, String f, ServicePair service,
- boolean d, int timeout)
- {
- ctx = context;
- pair = service;
- interfaceName = i;
- filter = f;
- dynamic = d;
- rebindTimeout = timeout;
- }
-
- public Object call() throws NamingException {
- if (pair == null || pair.ref.getBundle() == null) {
- if (dynamic) {
- pair = findService(ctx, interfaceName, filter);
- if (pair == null && rebindTimeout > 0) {
- long startTime = System.currentTimeMillis();
- try {
- while (pair == null && System.currentTimeMillis() - startTime < rebindTimeout) {
- Thread.sleep(100);
- pair = findService(ctx, interfaceName, filter);
- }
- } catch (InterruptedException e) {
+public final class ServiceHelper {
+ /**
+ * A cache of proxies returned to the client
+ */
+ private static final ConcurrentMap<ServiceKey, WeakReference<Object>> proxyCache = new ConcurrentHashMap<ServiceKey, WeakReference<Object>>();
+ private static final CacheClearoutListener cacheClearoutListener = new CacheClearoutListener(proxyCache);
+ private static final MessageUtil MESSAGES = MessageUtil.createMessageUtil(ServiceHelper.class, "org.apache.aries.jndi.nls.jndiUrlMessages");
+
+ public static Object getService(BundleContext ctx, OsgiName lookupName, String id,
+ boolean dynamicRebind, Map<String, Object> env, boolean requireProxy) throws NamingException {
+ String interfaceName = lookupName.getInterface();
+ String filter = lookupName.getFilter();
+ String serviceName = lookupName.getServiceName();
+
+ if (id != null) {
+ if (filter == null) {
+ filter = '(' + Constants.SERVICE_ID + '=' + id + ')';
+ } else {
+ filter = "(&(" + Constants.SERVICE_ID + '=' + id + ')' + filter + ')';
+ }
+ }
+
+ ServicePair pair = null;
+
+ if (!!!lookupName.isServiceNameBased()) {
+ pair = findService(ctx, interfaceName, filter);
+ }
+
+ if (pair == null) {
+ interfaceName = null;
+ if (id == null) {
+ filter = "(" + JNDIConstants.JNDI_SERVICENAME + "=" + serviceName + ')';
+ } else {
+ filter = "(&(" + Constants.SERVICE_ID + '=' + id + ")(" + JNDIConstants.JNDI_SERVICENAME
+ + "=" + serviceName + "))";
+ }
+ pair = findService(ctx, interfaceName, filter);
+ }
+
+ Object result = null;
+
+ if (pair != null) {
+ if (requireProxy) {
+ Object obj = env.get(org.apache.aries.jndi.api.JNDIConstants.REBIND_TIMEOUT);
+ int timeout = 0;
+ if (obj instanceof String) {
+ timeout = Integer.parseInt((String) obj);
+ } else if (obj instanceof Integer) {
+ timeout = (Integer) obj;
+ }
+
+ result = proxy(interfaceName, filter, dynamicRebind, ctx, pair, timeout);
+ } else {
+ result = pair.service;
}
- }
+ }
+
+ return result;
+ }
+
+ private static Object proxy(final String interface1, final String filter, final boolean rebind,
+ final BundleContext ctx, final ServicePair pair, final int timeout) {
+ Object result = null;
+ Bundle owningBundle = ctx.getBundle();
+ ServiceKey k = new ServiceKey(owningBundle, pair.ref.getBundle(), (Long) pair.ref.getProperty(Constants.SERVICE_ID));
+
+ WeakReference<Object> proxyRef = proxyCache.get(k);
+
+ if (proxyRef != null) {
+ result = proxyRef.get();
+ if (result == null) {
+ proxyCache.remove(k, proxyRef);
+ }
+ }
+
+ if (result == null) {
+ result = AccessController.doPrivileged(new PrivilegedAction<Object>() {
+ public Object run() {
+ return proxyPrivileged(interface1, filter, rebind, ctx, pair, timeout);
+ }
+ });
+
+ proxyRef = new WeakReference<Object>(result);
+ // if we have two threads doing a put and then clashing we ignore it. The code to ensure only
+ // one wins is quite complex to save a few bytes of memory and millis of execution time.
+ proxyCache.putIfAbsent(k, proxyRef);
+ cacheClearoutListener.add(ctx, k);
+ }
+
+ return result;
+ }
+
+ private static Object proxyPrivileged(String interface1, String filter, boolean dynamicRebind, BundleContext ctx, ServicePair pair, int timeout) {
+ String[] interfaces = null;
+ if (interface1 != null) {
+ interfaces = new String[]{interface1};
} else {
- pair = null;
+ interfaces = (String[]) pair.ref.getProperty(Constants.OBJECTCLASS);
+ }
+
+ List<Class<?>> clazz = new ArrayList<Class<?>>(interfaces.length);
+
+ // We load the interface classes the service is registered under using the defining bundle.
+ // This is ok because the service must be able to see the classes to be registered using them.
+ // We then check to see if isAssignableTo on the reference works for the owning bundle and
+ // the interface name and only use the interface if true is returned there.
+
+ // This might seem odd, but equinox and felix return true for isAssignableTo if the
+ // Bundle provided does not import the package. This is under the assumption the
+ // caller will then use reflection. The upshot of doing it this way is that a utility
+ // bundle can be created which centralizes JNDI lookups, but the service will be used
+ // by another bundle. It is true that class space consistency is less safe, but we
+ // are enabling a slightly odd use case anyway.
+
+ // August 13th 2013: We've found valid use cases in which a Bundle is exporting
+ // services that the Bundle itself cannot load. We deal with this rare case by
+ // noting the classes that we failed to load. If as a result we have no classes
+ // to proxy, we try those classes again but instead pull the Class objects off
+ // the service rather than from the bundle exporting that service.
+
+ Bundle serviceProviderBundle = pair.ref.getBundle();
+ Bundle owningBundle = ctx.getBundle();
+ ProxyManager proxyManager = Activator.getProxyManager();
+
+ Collection<String> classesNotFound = new ArrayList<String>();
+ for (String interfaceName : interfaces) {
+ try {
+ Class<?> potentialClass = serviceProviderBundle.loadClass(interfaceName);
+ if (pair.ref.isAssignableTo(owningBundle, interfaceName)) {
+ clazz.add(potentialClass);
+ }
+ } catch (ClassNotFoundException e) {
+ classesNotFound.add(interfaceName);
+ }
+ }
+
+ if (clazz.isEmpty() && !classesNotFound.isEmpty()) {
+ Class<?> ifacesOnService[] = ctx.getService(pair.ref).getClass().getInterfaces();
+ for (String interfaceName : classesNotFound) {
+ Class<?> thisClass = null;
+ for (Class<?> c : getAllInterfaces(ifacesOnService)) {
+ if (c.getName().equals(interfaceName)) {
+ thisClass = c;
+ break;
+ }
+ }
+ if (thisClass != null) {
+ if (pair.ref.isAssignableTo(owningBundle, interfaceName)) {
+ clazz.add(thisClass);
+ }
+ }
+ }
+ }
+
+ if (clazz.isEmpty()) {
+ throw new IllegalArgumentException(Arrays.asList(interfaces).toString());
+ }
+
+ Callable<Object> ih = new JNDIServiceDamper(ctx, interface1, filter, pair, dynamicRebind, timeout);
+
+ // The ClassLoader needs to be able to load the service interface
+ // classes so it needs to be
+ // wrapping the service provider bundle. The class is actually defined
+ // on this adapter.
+
+ try {
+ return proxyManager.createDelegatingProxy(serviceProviderBundle, clazz, ih, null);
+ } catch (UnableToProxyException e) {
+ throw new IllegalArgumentException(e);
+ } catch (RuntimeException e) {
+ throw new IllegalArgumentException(MESSAGES.getMessage("unable.to.create.proxy", pair.ref), e);
+ }
+ }
+
+ private static ServicePair findService(BundleContext ctx, String interface1, String filter)
+ throws NamingException {
+ ServicePair p = null;
+
+ try {
+ ServiceReference[] refs = ctx.getServiceReferences(interface1, filter);
+
+ if (refs != null) {
+ // natural order is the exact opposite of the order we desire.
+ Arrays.sort(refs, new Comparator<ServiceReference>() {
+ public int compare(ServiceReference o1, ServiceReference o2) {
+ return o2.compareTo(o1);
+ }
+ });
+
+ for (ServiceReference ref : refs) {
+ Object service = ctx.getService(ref);
+
+ if (service != null) {
+ p = new ServicePair();
+ p.ref = ref;
+ p.service = service;
+ break;
+ }
+ }
+ }
+
+ } catch (InvalidSyntaxException e) {
+ // If we get an invalid syntax exception we just ignore it. Null
+ // will be returned which
+ // is valid and that may result in a NameNotFoundException if that
+ // is the right thing to do
+ }
+
+ return p;
+ }
+
+ public static ServiceReference[] getServiceReferences(BundleContext ctx, String interface1,
+ String filter, String serviceName, Map<String, Object> env) throws NamingException {
+ ServiceReference[] refs = null;
+
+ try {
+ refs = ctx.getServiceReferences(interface1, filter);
+
+ if (refs == null || refs.length == 0) {
+ refs = ctx.getServiceReferences((String) null, "(" + JNDIConstants.JNDI_SERVICENAME + "="
+ + serviceName + ')');
+ }
+ } catch (InvalidSyntaxException e) {
+ throw (NamingException) new NamingException(e.getFilter()).initCause(e);
+ }
+
+ if (refs != null) {
+ // natural order is the exact opposite of the order we desire.
+ Arrays.sort(refs, new Comparator<ServiceReference>() {
+ public int compare(ServiceReference o1, ServiceReference o2) {
+ return o2.compareTo(o1);
+ }
+ });
+ }
+
+ return refs;
+ }
+
+ public static Object getService(BundleContext ctx, ServiceReference ref) {
+ Object service = ctx.getService(ref);
+ if (service == null) {
+ return null;
+ }
+
+ ServicePair pair = new ServicePair();
+ pair.ref = ref;
+ pair.service = service;
+ return proxy(null, null, false, ctx, pair, 0);
+ }
+
+ static Collection<Class<?>> getAllInterfaces(Class<?>[] baseInterfaces) {
+ Set<Class<?>> result = new HashSet<Class<?>>();
+ for (Class<?> c : baseInterfaces) {
+ if (!c.equals(Object.class)) {
+ result.add(c);
+ Class<?> ifaces[] = c.getInterfaces();
+ if (ifaces.length != 0) {
+ result.addAll(getAllInterfaces(ifaces));
+ }
+ }
+ }
+ return result;
+ }
+
+ public static final class CacheClearoutListener implements BundleListener, ServiceListener {
+ /**
+ * The cache to purge
+ */
+ private final ConcurrentMap<ServiceKey, WeakReference<Object>> cache;
+
+
+ public CacheClearoutListener(ConcurrentMap<ServiceKey, WeakReference<Object>> pc) {
+ cache = pc;
}
- }
- if (pair == null) {
- throw new ServiceException(interfaceName, ServiceException.UNREGISTERED);
- }
- return pair.service;
- }
- }
-
- private static class ServicePair
- {
- private ServiceReference ref;
- private Object service;
- }
-
- /** A cache of proxies returned to the client */
- private static final ConcurrentMap<ServiceKey, WeakReference<Object>> proxyCache = new ConcurrentHashMap<ServiceKey, WeakReference<Object>>();
- private static final CacheClearoutListener cacheClearoutListener = new CacheClearoutListener(proxyCache);
- private static final MessageUtil MESSAGES = MessageUtil.createMessageUtil(ServiceHelper.class, "org.apache.aries.jndi.nls.jndiUrlMessages");
-
- public static Object getService(BundleContext ctx, OsgiName lookupName, String id,
- boolean dynamicRebind, Map<String, Object> env, boolean requireProxy) throws NamingException
- {
- String interfaceName = lookupName.getInterface();
- String filter = lookupName.getFilter();
- String serviceName = lookupName.getServiceName();
-
- if (id != null) {
- if (filter == null) {
- filter = '(' + Constants.SERVICE_ID + '=' + id + ')';
- } else {
- filter = "(&(" + Constants.SERVICE_ID + '=' + id + ')' + filter + ')';
- }
- }
-
- ServicePair pair = null;
-
- if (!!!lookupName.isServiceNameBased()) {
- pair = findService(ctx, interfaceName, filter);
- }
-
- if (pair == null) {
- interfaceName = null;
- if (id == null) {
- filter = "(" + JNDIConstants.JNDI_SERVICENAME + "=" + serviceName + ')';
- } else {
- filter = "(&(" + Constants.SERVICE_ID + '=' + id + ")(" + JNDIConstants.JNDI_SERVICENAME
- + "=" + serviceName + "))";
- }
- pair = findService(ctx, interfaceName, filter);
- }
-
- Object result = null;
-
- if (pair != null) {
- if (requireProxy) {
- Object obj = env.get(org.apache.aries.jndi.api.JNDIConstants.REBIND_TIMEOUT);
- int timeout = 0;
- if (obj instanceof String) {
- timeout = Integer.parseInt((String)obj);
- } else if (obj instanceof Integer) {
- timeout = (Integer)obj;
- }
-
- result = proxy(interfaceName, filter, dynamicRebind, ctx, pair, timeout);
- } else {
- result = pair.service;
- }
- }
-
- return result;
- }
-
- private static Object proxy(final String interface1, final String filter, final boolean rebind,
- final BundleContext ctx, final ServicePair pair, final int timeout)
- {
- Object result = null;
- Bundle owningBundle = ctx.getBundle();
- ServiceKey k = new ServiceKey(owningBundle, pair.ref.getBundle(), (Long) pair.ref.getProperty(Constants.SERVICE_ID));
-
- WeakReference<Object> proxyRef = proxyCache.get(k);
-
- if (proxyRef != null) {
- result = proxyRef.get();
- if (result == null) {
- proxyCache.remove(k, proxyRef);
- }
- }
-
- if (result == null) {
- result = AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run()
- {
- return proxyPrivileged(interface1, filter, rebind, ctx, pair, timeout);
- }
- });
-
- proxyRef = new WeakReference<Object>(result);
- // if we have two threads doing a put and then clashing we ignore it. The code to ensure only
- // one wins is quite complex to save a few bytes of memory and millis of execution time.
- proxyCache.putIfAbsent(k, proxyRef);
- cacheClearoutListener.add(ctx, k);
- }
-
- return result;
- }
-
- private static Object proxyPrivileged(String interface1, String filter, boolean dynamicRebind, BundleContext ctx, ServicePair pair, int timeout)
- {
- String[] interfaces = null;
- if (interface1 != null) {
- interfaces = new String[] { interface1 };
- } else {
- interfaces = (String[]) pair.ref.getProperty(Constants.OBJECTCLASS);
- }
-
- List<Class<?>> clazz = new ArrayList<Class<?>>(interfaces.length);
-
- // We load the interface classes the service is registered under using the defining bundle.
- // This is ok because the service must be able to see the classes to be registered using them.
- // We then check to see if isAssignableTo on the reference works for the owning bundle and
- // the interface name and only use the interface if true is returned there.
-
- // This might seem odd, but equinox and felix return true for isAssignableTo if the
- // Bundle provided does not import the package. This is under the assumption the
- // caller will then use reflection. The upshot of doing it this way is that a utility
- // bundle can be created which centralizes JNDI lookups, but the service will be used
- // by another bundle. It is true that class space consistency is less safe, but we
- // are enabling a slightly odd use case anyway.
-
- // August 13th 2013: We've found valid use cases in which a Bundle is exporting
- // services that the Bundle itself cannot load. We deal with this rare case by
- // noting the classes that we failed to load. If as a result we have no classes
- // to proxy, we try those classes again but instead pull the Class objects off
- // the service rather than from the bundle exporting that service.
-
- Bundle serviceProviderBundle = pair.ref.getBundle();
- Bundle owningBundle = ctx.getBundle();
- ProxyManager proxyManager = Activator.getProxyManager();
-
- Collection<String> classesNotFound = new ArrayList<String>();
- for (String interfaceName : interfaces) {
- try {
- Class<?> potentialClass = serviceProviderBundle.loadClass(interfaceName);
- if (pair.ref.isAssignableTo(owningBundle, interfaceName)) {
- clazz.add(potentialClass);
- }
- } catch (ClassNotFoundException e) {
- classesNotFound.add(interfaceName);
- }
- }
-
- if (clazz.isEmpty() && !classesNotFound.isEmpty()) {
- Class<?> ifacesOnService[] = ctx.getService(pair.ref).getClass().getInterfaces();
- for (String interfaceName : classesNotFound) {
- Class<?> thisClass = null;
- for (Class<?> c : getAllInterfaces(ifacesOnService)) {
- if (c.getName().equals(interfaceName)) {
- thisClass = c;
- break;
- }
- }
- if (thisClass != null) {
- if (pair.ref.isAssignableTo(owningBundle, interfaceName)) {
- clazz.add(thisClass);
- }
- }
- }
- }
-
- if (clazz.isEmpty()) {
- throw new IllegalArgumentException(Arrays.asList(interfaces).toString());
- }
-
- Callable<Object> ih = new JNDIServiceDamper(ctx, interface1, filter, pair, dynamicRebind, timeout);
-
- // The ClassLoader needs to be able to load the service interface
- // classes so it needs to be
- // wrapping the service provider bundle. The class is actually defined
- // on this adapter.
-
- try {
- return proxyManager.createDelegatingProxy(serviceProviderBundle, clazz, ih, null);
- } catch (UnableToProxyException e) {
- throw new IllegalArgumentException(e);
- } catch (RuntimeException e) {
- throw new IllegalArgumentException(MESSAGES.getMessage("unable.to.create.proxy", pair.ref), e);
- }
- }
-
- private static ServicePair findService(BundleContext ctx, String interface1, String filter)
- throws NamingException
- {
- ServicePair p = null;
-
- try {
- ServiceReference[] refs = ctx.getServiceReferences(interface1, filter);
-
- if (refs != null) {
- // natural order is the exact opposite of the order we desire.
- Arrays.sort(refs, new Comparator<ServiceReference>() {
- public int compare(ServiceReference o1, ServiceReference o2)
- {
- return o2.compareTo(o1);
- }
- });
-
- for (ServiceReference ref : refs) {
- Object service = ctx.getService(ref);
-
- if (service != null) {
- p = new ServicePair();
- p.ref = ref;
- p.service = service;
- break;
- }
- }
- }
-
- } catch (InvalidSyntaxException e) {
- // If we get an invalid syntax exception we just ignore it. Null
- // will be returned which
- // is valid and that may result in a NameNotFoundException if that
- // is the right thing to do
- }
-
- return p;
- }
-
- public static ServiceReference[] getServiceReferences(BundleContext ctx, String interface1,
- String filter, String serviceName, Map<String, Object> env) throws NamingException
- {
- ServiceReference[] refs = null;
-
- try {
- refs = ctx.getServiceReferences(interface1, filter);
-
- if (refs == null || refs.length == 0) {
- refs = ctx.getServiceReferences((String) null, "(" + JNDIConstants.JNDI_SERVICENAME + "="
- + serviceName + ')');
- }
- } catch (InvalidSyntaxException e) {
- throw (NamingException) new NamingException(e.getFilter()).initCause(e);
- }
-
- if (refs != null) {
- // natural order is the exact opposite of the order we desire.
- Arrays.sort(refs, new Comparator<ServiceReference>() {
- public int compare(ServiceReference o1, ServiceReference o2)
- {
- return o2.compareTo(o1);
- }
- });
- }
-
- return refs;
- }
-
- public static Object getService(BundleContext ctx, ServiceReference ref)
- {
- Object service = ctx.getService(ref);
- if (service == null) {
- return null;
- }
-
- ServicePair pair = new ServicePair();
- pair.ref = ref;
- pair.service = service;
- return proxy(null, null, false, ctx, pair, 0);
- }
-
- static Collection<Class<?>> getAllInterfaces (Class<?>[] baseInterfaces)
- {
- Set<Class<?>> result = new HashSet<Class<?>>();
- for (Class<?> c : baseInterfaces) {
- if (!c.equals(Object.class)) {
- result.add (c);
- Class<?> ifaces[] = c.getInterfaces();
- if (ifaces.length != 0) {
- result.addAll(getAllInterfaces(ifaces));
- }
- }
- }
- return result;
- }
+ public void bundleChanged(BundleEvent event) {
+ if (event.getType() == BundleEvent.STOPPED) {
+ Bundle b = event.getBundle();
+ Iterator<ServiceKey> keys = cache.keySet().iterator();
+ while (keys.hasNext()) {
+ ServiceKey key = keys.next();
+ if (key.requesting == b) keys.remove();
+ }
+ }
+ }
+
+ public void serviceChanged(ServiceEvent event) {
+ if (event.getType() == ServiceEvent.UNREGISTERING) {
+ ServiceReference ref = event.getServiceReference();
+ Long serviceId = (Long) ref.getProperty(Constants.SERVICE_ID);
+ Bundle registeringBundle = ref.getBundle();
+ Iterator<ServiceKey> keys = cache.keySet().iterator();
+ while (keys.hasNext()) {
+ ServiceKey key = keys.next();
+ if (key.registering == registeringBundle && serviceId.equals(key.serviceId)) {
+ keys.remove();
+ break;
+ }
+ }
+ }
+ }
+
+ public void add(final BundleContext ctx, ServiceKey k) {
+ // try to use the system bundle for our listener, if that fails we fall back to the calling context
+ BundleContext systemBundle = AccessController.doPrivileged(new PrivilegedAction<BundleContext>() {
+ public BundleContext run() {
+ Bundle system = ctx.getBundle(0);
+ return system == null ? null : system.getBundleContext();
+ }
+ });
+ if (systemBundle == null) systemBundle = ctx;
+ systemBundle.addBundleListener(cacheClearoutListener);
+ systemBundle.addServiceListener(cacheClearoutListener);
+ }
+ }
+
+ private static final class ServiceKey {
+ private final Bundle requesting;
+ private final Bundle registering;
+ private final Long serviceId;
+ private final int hash;
+
+ public ServiceKey(Bundle owningBundle, Bundle registeringBundle, Long property) {
+ requesting = owningBundle;
+ registering = registeringBundle;
+ serviceId = property;
+ hash = serviceId.intValue() * 100003 + System.identityHashCode(requesting);
+ }
+
+ public int hashCode() {
+ return hash;
+ }
+
+ public boolean equals(Object other) {
+ if (other == this) return true;
+ if (other == null) return false;
+
+ if (other instanceof ServiceKey) {
+ ServiceKey otherKey = (ServiceKey) other;
+ return (otherKey.requesting == requesting && otherKey.serviceId.equals(serviceId));
+ }
+
+ return false;
+ }
+ }
+
+ private static class JNDIServiceDamper implements Callable<Object> {
+ private BundleContext ctx;
+ private ServicePair pair;
+ private String interfaceName;
+ private String filter;
+ private boolean dynamic;
+ private int rebindTimeout;
+
+ public JNDIServiceDamper(BundleContext context, String i, String f, ServicePair service,
+ boolean d, int timeout) {
+ ctx = context;
+ pair = service;
+ interfaceName = i;
+ filter = f;
+ dynamic = d;
+ rebindTimeout = timeout;
+ }
+
+ public Object call() throws NamingException {
+ if (pair == null || pair.ref.getBundle() == null) {
+ if (dynamic) {
+ pair = findService(ctx, interfaceName, filter);
+ if (pair == null && rebindTimeout > 0) {
+ long startTime = System.currentTimeMillis();
+ try {
+ while (pair == null && System.currentTimeMillis() - startTime < rebindTimeout) {
+ Thread.sleep(100);
+ pair = findService(ctx, interfaceName, filter);
+ }
+ } catch (InterruptedException e) {
+ }
+ }
+ } else {
+ pair = null;
+ }
+ }
+
+ if (pair == null) {
+ throw new ServiceException(interfaceName, ServiceException.UNREGISTERED);
+ }
+ return pair.service;
+ }
+ }
+
+ private static class ServicePair {
+ private ServiceReference ref;
+ private Object service;
+ }
}
Modified: aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/AbstractName.java
URL: http://svn.apache.org/viewvc/aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/AbstractName.java?rev=1824942&r1=1824941&r2=1824942&view=diff
==============================================================================
--- aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/AbstractName.java (original)
+++ aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/AbstractName.java Wed Feb 21 09:04:41 2018
@@ -19,71 +19,66 @@
package org.apache.aries.jndi.url;
+import javax.naming.CompositeName;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
-import javax.naming.CompositeName;
-
@SuppressWarnings("serial")
-public abstract class AbstractName extends CompositeName
-{
- public AbstractName (String name) {
- super(split(name));
- }
-
- protected static Enumeration<String> split(String name)
- {
- List<String> elements = new ArrayList<String>();
-
- StringBuilder builder = new StringBuilder();
-
- int len = name.length();
- int count = 0;
-
- for (int i = 0; i < len; i++) {
- char c = name.charAt(i);
-
- if (c == '/' && count == 0) {
+public abstract class AbstractName extends CompositeName {
+ public AbstractName(String name) {
+ super(split(name));
+ }
+
+ protected static Enumeration<String> split(String name) {
+ List<String> elements = new ArrayList<String>();
+
+ StringBuilder builder = new StringBuilder();
+
+ int len = name.length();
+ int count = 0;
+
+ for (int i = 0; i < len; i++) {
+ char c = name.charAt(i);
+
+ if (c == '/' && count == 0) {
+ elements.add(builder.toString());
+ builder = new StringBuilder();
+ continue;
+ } else if (c == '(') count++;
+ else if (c == ')') count++;
+
+ builder.append(c);
+ }
+
elements.add(builder.toString());
- builder = new StringBuilder();
- continue;
- } else if (c == '(') count++;
- else if (c == ')') count++;
-
- builder.append(c);
+
+ return Collections.enumeration(elements);
}
-
- elements.add(builder.toString());
-
- return Collections.enumeration(elements);
- }
-
- public String getScheme()
- {
- String part0 = get(0);
- int index = part0.indexOf(':');
- if (index > 0) {
- return part0.substring(0, index);
- } else {
- return null;
+
+ public String getScheme() {
+ String part0 = get(0);
+ int index = part0.indexOf(':');
+ if (index > 0) {
+ return part0.substring(0, index);
+ } else {
+ return null;
+ }
}
- }
-
- public String getSchemePath()
- {
- String part0 = get(0);
- int index = part0.indexOf(':');
-
- String result;
-
- if (index > 0) {
- result = part0.substring(index + 1);
- } else {
- result = null;
+
+ public String getSchemePath() {
+ String part0 = get(0);
+ int index = part0.indexOf(':');
+
+ String result;
+
+ if (index > 0) {
+ result = part0.substring(index + 1);
+ } else {
+ result = null;
+ }
+
+ return result;
}
-
- return result;
- }
}
Modified: aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/AbstractServiceRegistryContext.java
URL: http://svn.apache.org/viewvc/aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/AbstractServiceRegistryContext.java?rev=1824942&r1=1824941&r2=1824942&view=diff
==============================================================================
--- aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/AbstractServiceRegistryContext.java (original)
+++ aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/AbstractServiceRegistryContext.java Wed Feb 21 09:04:41 2018
@@ -18,213 +18,184 @@
*/
package org.apache.aries.jndi.url;
+import org.apache.aries.jndi.spi.AugmenterInvoker;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.jndi.JNDIConstants;
+
+import javax.naming.*;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
-import javax.naming.Context;
-import javax.naming.Name;
-import javax.naming.NameParser;
-import javax.naming.NamingException;
-import javax.naming.OperationNotSupportedException;
+public abstract class AbstractServiceRegistryContext implements Context {
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.jndi.JNDIConstants;
+ private static final String ARIES_SERVICES = "aries:services/";
+ private static AugmenterInvoker augmenterInvoker = null;
+ protected BundleContext callerContext;
+ /**
+ * The environment for this context
+ */
+ protected Map<String, Object> env;
+ /**
+ * The name parser for the service registry name space
+ */
+ protected NameParser parser = new OsgiNameParser();
-import org.apache.aries.jndi.spi.AugmenterInvoker;
+ @SuppressWarnings("unchecked")
+ public AbstractServiceRegistryContext(BundleContext callerContext, Hashtable<?, ?> environment) {
+ env = new HashMap<String, Object>();
+ env.putAll((Map<? extends String, ? extends Object>) environment);
+ // ARIES-397:, If the caller has provided a BundleContext
+ // in the hashtable, use this in preference to callerContext
+ if (augmenterInvoker == null && callerContext != null) {
+ ServiceReference augmenterSR = callerContext.getServiceReference(AugmenterInvoker.class.getName());
+ if (augmenterSR != null) augmenterInvoker = (AugmenterInvoker) callerContext.getService(augmenterSR);
+ }
+ if (augmenterInvoker != null) augmenterInvoker.augmentEnvironment(environment);
+ BundleContext bc = (BundleContext) env.get(JNDIConstants.BUNDLE_CONTEXT);
+ if (augmenterInvoker != null) augmenterInvoker.unaugmentEnvironment(environment);
+ if (bc != null) {
+ this.callerContext = bc;
+ } else {
+ this.callerContext = callerContext;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public AbstractServiceRegistryContext(BundleContext callerContext, Map<?, ?> environment) {
+ env = new HashMap<String, Object>();
+ env.putAll((Map<? extends String, ? extends Object>) environment);
+ Hashtable<String, Object> environmentHT = new Hashtable<String, Object>();
+ environmentHT.putAll(env);
+ // ARIES-397: If the caller has provided a BundleContext
+ // in the hashtable, use this in preference to callerContext
+ if (augmenterInvoker == null && callerContext != null) {
+ ServiceReference augmenterSR = callerContext.getServiceReference(AugmenterInvoker.class.getName());
+ if (augmenterSR != null) augmenterInvoker = (AugmenterInvoker) callerContext.getService(augmenterSR);
+ }
+ if (augmenterInvoker != null) augmenterInvoker.augmentEnvironment(environmentHT);
+ BundleContext bc = (BundleContext) env.get(JNDIConstants.BUNDLE_CONTEXT);
+ if (augmenterInvoker != null) augmenterInvoker.unaugmentEnvironment(environmentHT);
+ if (bc != null) {
+ this.callerContext = bc;
+ } else {
+ this.callerContext = callerContext;
+ }
+ }
+
+ public Object addToEnvironment(String propName, Object propVal) throws NamingException {
+ return env.put(propName, propVal);
+ }
+
+ public void bind(Name name, Object obj) throws NamingException {
+ throw new OperationNotSupportedException();
+ }
+
+ public void bind(String name, Object obj) throws NamingException {
+ throw new OperationNotSupportedException();
+ }
+
+ public void close() throws NamingException {
+ env = null;
+ parser = null;
+ }
+
+ public Name composeName(Name name, Name prefix) throws NamingException {
+ String result = prefix + "/" + name;
+
+ String ns = ARIES_SERVICES;
+
+ if (result.startsWith(ns)) {
+ ns = "";
+ }
+
+ return parser.parse(ns + result);
+ }
+
+ public String composeName(String name, String prefix) throws NamingException {
+ String result = prefix + "/" + name;
+
+ String ns = ARIES_SERVICES;
+
+ if (result.startsWith(ns)) {
+ ns = "";
+ }
+
+ parser.parse(ns + result);
+
+ return result;
+ }
+
+ public Context createSubcontext(Name name) throws NamingException {
+ throw new OperationNotSupportedException();
+ }
+
+ public Context createSubcontext(String name) throws NamingException {
+ throw new OperationNotSupportedException();
+ }
+
+ public void destroySubcontext(Name name) throws NamingException {
+ //No-op we don't support sub-contexts in our context
+ }
+
+ public void destroySubcontext(String name) throws NamingException {
+ //No-op we don't support sub-contexts in our context
+
+ }
+
+ public Hashtable<?, ?> getEnvironment() throws NamingException {
+ Hashtable<Object, Object> environment = new Hashtable<Object, Object>();
+ environment.putAll(env);
+ return environment;
+ }
+
+ public String getNameInNamespace() throws NamingException {
+ throw new OperationNotSupportedException();
+ }
+
+ public NameParser getNameParser(Name name) throws NamingException {
+ return parser;
+ }
+
+ public NameParser getNameParser(String name) throws NamingException {
+ return parser;
+ }
-public abstract class AbstractServiceRegistryContext implements Context
-{
+ public Object lookupLink(Name name) throws NamingException {
+ throw new OperationNotSupportedException();
+ }
+
+ public Object lookupLink(String name) throws NamingException {
+ throw new OperationNotSupportedException();
+ }
+
+ public void rebind(Name name, Object obj) throws NamingException {
+ throw new OperationNotSupportedException();
+ }
+
+ public void rebind(String name, Object obj) throws NamingException {
+ throw new OperationNotSupportedException();
+ }
+
+ public Object removeFromEnvironment(String propName) throws NamingException {
+ return env.remove(propName);
+ }
+
+ public void rename(Name oldName, Name newName) throws NamingException {
+ throw new OperationNotSupportedException();
+ }
+
+ public void rename(String oldName, String newName) throws NamingException {
+ throw new OperationNotSupportedException();
+ }
+
+ public void unbind(Name name) throws NamingException {
+ throw new OperationNotSupportedException();
+ }
- protected BundleContext callerContext;
- /** The environment for this context */
- protected Map<String, Object> env;
- /** The name parser for the service registry name space */
- protected NameParser parser = new OsgiNameParser();
- private static final String ARIES_SERVICES = "aries:services/";
-
- private static AugmenterInvoker augmenterInvoker = null;
-
- @SuppressWarnings("unchecked")
- public AbstractServiceRegistryContext(BundleContext callerContext, Hashtable<?, ?> environment)
- {
- env = new HashMap<String, Object>();
- env.putAll((Map<? extends String, ? extends Object>) environment);
- // ARIES-397:, If the caller has provided a BundleContext
- // in the hashtable, use this in preference to callerContext
- if (augmenterInvoker == null && callerContext != null) {
- ServiceReference augmenterSR = callerContext.getServiceReference(AugmenterInvoker.class.getName());
- if (augmenterSR != null) augmenterInvoker = (AugmenterInvoker) callerContext.getService(augmenterSR);
- }
- if (augmenterInvoker != null) augmenterInvoker.augmentEnvironment(environment);
- BundleContext bc = (BundleContext) env.get(JNDIConstants.BUNDLE_CONTEXT);
- if (augmenterInvoker != null) augmenterInvoker.unaugmentEnvironment(environment);
- if (bc != null) {
- this.callerContext = bc;
- } else {
- this.callerContext = callerContext;
- }
- }
-
- @SuppressWarnings("unchecked")
- public AbstractServiceRegistryContext(BundleContext callerContext, Map<?, ?> environment)
- {
- env = new HashMap<String, Object>();
- env.putAll((Map<? extends String, ? extends Object>) environment);
- Hashtable<String, Object> environmentHT = new Hashtable<String,Object>();
- environmentHT.putAll(env);
- // ARIES-397: If the caller has provided a BundleContext
- // in the hashtable, use this in preference to callerContext
- if (augmenterInvoker == null && callerContext != null) {
- ServiceReference augmenterSR = callerContext.getServiceReference(AugmenterInvoker.class.getName());
- if (augmenterSR != null) augmenterInvoker = (AugmenterInvoker) callerContext.getService(augmenterSR);
- }
- if (augmenterInvoker != null) augmenterInvoker.augmentEnvironment(environmentHT);
- BundleContext bc = (BundleContext) env.get(JNDIConstants.BUNDLE_CONTEXT);
- if (augmenterInvoker != null) augmenterInvoker.unaugmentEnvironment(environmentHT);
- if (bc != null) {
- this.callerContext = bc;
- } else {
- this.callerContext = callerContext;
- }
- }
-
- public Object addToEnvironment(String propName, Object propVal) throws NamingException
- {
- return env.put(propName, propVal);
- }
-
- public void bind(Name name, Object obj) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void bind(String name, Object obj) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void close() throws NamingException
- {
- env = null;
- parser = null;
- }
-
- public Name composeName(Name name, Name prefix) throws NamingException
- {
- String result = prefix + "/" + name;
-
- String ns = ARIES_SERVICES;
-
- if (result.startsWith(ns)) {
- ns = "";
- }
-
- return parser.parse(ns + result);
- }
-
- public String composeName(String name, String prefix) throws NamingException
- {
- String result = prefix + "/" + name;
-
- String ns = ARIES_SERVICES;
-
- if (result.startsWith(ns)) {
- ns = "";
- }
-
- parser.parse(ns + result);
-
- return result;
- }
-
- public Context createSubcontext(Name name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public Context createSubcontext(String name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void destroySubcontext(Name name) throws NamingException
- {
- //No-op we don't support sub-contexts in our context
- }
-
- public void destroySubcontext(String name) throws NamingException
- {
- //No-op we don't support sub-contexts in our context
-
- }
-
- public Hashtable<?, ?> getEnvironment() throws NamingException
- {
- Hashtable<Object, Object> environment = new Hashtable<Object, Object>();
- environment.putAll(env);
- return environment;
- }
-
- public String getNameInNamespace() throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public NameParser getNameParser(Name name) throws NamingException
- {
- return parser;
- }
-
- public NameParser getNameParser(String name) throws NamingException
- {
- return parser;
- }
-
- public Object lookupLink(Name name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public Object lookupLink(String name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void rebind(Name name, Object obj) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void rebind(String name, Object obj) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public Object removeFromEnvironment(String propName) throws NamingException
- {
- return env.remove(propName);
- }
-
- public void rename(Name oldName, Name newName) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void rename(String oldName, String newName) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void unbind(Name name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
-
- public void unbind(String name) throws NamingException
- {
- throw new OperationNotSupportedException();
- }
+ public void unbind(String name) throws NamingException {
+ throw new OperationNotSupportedException();
+ }
}
Modified: aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/Activator.java
URL: http://svn.apache.org/viewvc/aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/Activator.java?rev=1824942&r1=1824941&r2=1824942&view=diff
==============================================================================
--- aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/Activator.java (original)
+++ aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/Activator.java Wed Feb 21 09:04:41 2018
@@ -18,13 +18,6 @@
*/
package org.apache.aries.jndi.url;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.naming.spi.ObjectFactory;
-
import org.apache.aries.proxy.ProxyManager;
import org.apache.aries.util.AriesFrameworkUtil;
import org.apache.aries.util.tracker.SingleServiceTracker;
@@ -34,16 +27,24 @@ import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.jndi.JNDIConstants;
-public class Activator implements BundleActivator, SingleServiceListener
-{
+import javax.naming.spi.ObjectFactory;
+import java.util.Dictionary;
+import java.util.Hashtable;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class Activator implements BundleActivator, SingleServiceListener {
+ private static SingleServiceTracker<ProxyManager> proxyManager;
private BundleContext ctx;
private volatile ServiceRegistration osgiUrlReg = null;
private volatile ServiceRegistration blueprintUrlReg = null;
- private static SingleServiceTracker<ProxyManager> proxyManager;
+
+ public static ProxyManager getProxyManager() {
+ return proxyManager == null ? null : proxyManager.getService();
+ }
@Override
- public void start(BundleContext context)
- {
+ public void start(BundleContext context) {
ctx = context;
proxyManager = new SingleServiceTracker<ProxyManager>(context, ProxyManager.class, this);
proxyManager.open();
@@ -52,51 +53,42 @@ public class Activator implements Bundle
// on org.osgi.service.blueprint.container: only register the blueprint:comp/URL
// scheme if it's present
try {
- ctx.getBundle().loadClass("org.osgi.service.blueprint.container.BlueprintContainer");
- Hashtable<Object, Object> blueprintURlSchemeProps = new Hashtable<Object, Object>();
- blueprintURlSchemeProps.put(JNDIConstants.JNDI_URLSCHEME, new String[] { "blueprint" });
- blueprintUrlReg = ctx.registerService(ObjectFactory.class.getName(),
- new BlueprintURLContextServiceFactory(), (Dictionary) blueprintURlSchemeProps);
+ ctx.getBundle().loadClass("org.osgi.service.blueprint.container.BlueprintContainer");
+ Hashtable<Object, Object> blueprintURlSchemeProps = new Hashtable<Object, Object>();
+ blueprintURlSchemeProps.put(JNDIConstants.JNDI_URLSCHEME, new String[]{"blueprint"});
+ blueprintUrlReg = ctx.registerService(ObjectFactory.class.getName(),
+ new BlueprintURLContextServiceFactory(), (Dictionary) blueprintURlSchemeProps);
} catch (ClassNotFoundException cnfe) {
- // The blueprint packages aren't available, so do nothing. That's fine.
- Logger logger = Logger.getLogger("org.apache.aries.jndi");
- logger.log(Level.INFO, "Blueprint support disabled: " + cnfe);
- logger.log(Level.FINE, "Blueprint support disabled", cnfe);
+ // The blueprint packages aren't available, so do nothing. That's fine.
+ Logger logger = Logger.getLogger("org.apache.aries.jndi");
+ logger.log(Level.INFO, "Blueprint support disabled: " + cnfe);
+ logger.log(Level.FINE, "Blueprint support disabled", cnfe);
}
}
@Override
public void stop(BundleContext context) {
- proxyManager.close();
- AriesFrameworkUtil.safeUnregisterService(osgiUrlReg);
- AriesFrameworkUtil.safeUnregisterService(blueprintUrlReg);
- }
-
-
- @Override
- public void serviceFound()
- {
- Hashtable<Object, Object> osgiUrlprops = new Hashtable<Object, Object>();
- osgiUrlprops.put(JNDIConstants.JNDI_URLSCHEME, new String[] { "osgi", "aries" });
- osgiUrlReg = ctx.registerService(ObjectFactory.class.getName(),
- new OsgiURLContextServiceFactory(), (Dictionary) osgiUrlprops);
- }
-
- @Override
- public void serviceLost()
- {
- AriesFrameworkUtil.safeUnregisterService(osgiUrlReg);
- osgiUrlReg = null;
- }
-
- @Override
- public void serviceReplaced()
- {
-
- }
-
- public static ProxyManager getProxyManager()
- {
- return proxyManager == null ? null : proxyManager.getService();
- }
+ proxyManager.close();
+ AriesFrameworkUtil.safeUnregisterService(osgiUrlReg);
+ AriesFrameworkUtil.safeUnregisterService(blueprintUrlReg);
+ }
+
+ @Override
+ public void serviceFound() {
+ Hashtable<Object, Object> osgiUrlprops = new Hashtable<Object, Object>();
+ osgiUrlprops.put(JNDIConstants.JNDI_URLSCHEME, new String[]{"osgi", "aries"});
+ osgiUrlReg = ctx.registerService(ObjectFactory.class.getName(),
+ new OsgiURLContextServiceFactory(), (Dictionary) osgiUrlprops);
+ }
+
+ @Override
+ public void serviceLost() {
+ AriesFrameworkUtil.safeUnregisterService(osgiUrlReg);
+ osgiUrlReg = null;
+ }
+
+ @Override
+ public void serviceReplaced() {
+
+ }
}
\ No newline at end of file
Modified: aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintName.java
URL: http://svn.apache.org/viewvc/aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintName.java?rev=1824942&r1=1824941&r2=1824942&view=diff
==============================================================================
--- aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintName.java (original)
+++ aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintName.java Wed Feb 21 09:04:41 2018
@@ -22,29 +22,25 @@ package org.apache.aries.jndi.url;
import javax.naming.InvalidNameException;
import javax.naming.Name;
-public class BlueprintName extends AbstractName
-{
- /**
- *
- */
- private static final long serialVersionUID = 7460901600614300179L;
+public class BlueprintName extends AbstractName {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 7460901600614300179L;
- public BlueprintName(String name) throws InvalidNameException
- {
- super(name);
- }
+ public BlueprintName(String name) throws InvalidNameException {
+ super(name);
+ }
- public BlueprintName(Name name) throws InvalidNameException
- {
- this(name.toString());
- }
+ public BlueprintName(Name name) throws InvalidNameException {
+ this(name.toString());
+ }
- public String getComponentId()
- {
- return get(1);
- }
-
- public boolean hasComponent() {
- return size() > 1;
- }
+ public String getComponentId() {
+ return get(1);
+ }
+
+ public boolean hasComponent() {
+ return size() > 1;
+ }
}
Modified: aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintNameParser.java
URL: http://svn.apache.org/viewvc/aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintNameParser.java?rev=1824942&r1=1824941&r2=1824942&view=diff
==============================================================================
--- aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintNameParser.java (original)
+++ aries/trunk/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintNameParser.java Wed Feb 21 09:04:41 2018
@@ -26,33 +26,29 @@ import javax.naming.NamingException;
/**
* A parser for the aries namespace
*/
-public final class BlueprintNameParser implements NameParser
-{
- private static final String BLUEPRINT_SCHEME = "blueprint";
- private static final String COMP_PATH = "comp";
-
- @Override
- public Name parse(String name) throws NamingException
- {
- BlueprintName result = new BlueprintName(name);
- String urlScheme = result.getScheme();
- String schemePath = result.getSchemePath();
-
- if (!BLUEPRINT_SCHEME.equals(urlScheme) || !COMP_PATH.equals(schemePath)) {
- throw new InvalidNameException(name);
+public final class BlueprintNameParser implements NameParser {
+ private static final String BLUEPRINT_SCHEME = "blueprint";
+ private static final String COMP_PATH = "comp";
+
+ @Override
+ public Name parse(String name) throws NamingException {
+ BlueprintName result = new BlueprintName(name);
+ String urlScheme = result.getScheme();
+ String schemePath = result.getSchemePath();
+
+ if (!BLUEPRINT_SCHEME.equals(urlScheme) || !COMP_PATH.equals(schemePath)) {
+ throw new InvalidNameException(name);
+ }
+ return result;
}
- return result;
- }
- @Override
- public boolean equals(Object other)
- {
- return other instanceof OsgiNameParser;
- }
-
- @Override
- public int hashCode()
- {
- return 100004;
- }
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof OsgiNameParser;
+ }
+
+ @Override
+ public int hashCode() {
+ return 100004;
+ }
}
\ No newline at end of file