[jboss-cvs] JBossAS SVN: r80569 - in projects/naming/branches: Branch_5_0 and 7 other directories.
jboss-cvs-commits at lists.jboss.org
jboss-cvs-commits at lists.jboss.org
Wed Nov 5 19:53:22 EST 2008
Author: scott.stark at jboss.org
Date: 2008-11-05 19:53:21 -0500 (Wed, 05 Nov 2008)
New Revision: 80569
Added:
projects/naming/branches/Branch_5_0/
projects/naming/branches/Branch_5_0/jnpserver/pom.xml
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jboss/naming/BindingsInitializer.java
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/LocalOnlyContextFactory.java
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/NamingContext.java
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/Main.java
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/MainMBean.java
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingBeanImpl.java
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingServer.java
projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingMCUnitTest.java
projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingServerSecurityManagerUnitTest.java
projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/SecurityUtil.java
projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/log4j.xml
projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/org/jnp/test/NamingMCUnitTest#testInjectedSecurityManager.xml
projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/org/jnp/test/NamingMCUnitTest#testMultipleLocalOnlyContextFactory.xml
projects/naming/branches/Branch_5_0/pom.xml
Removed:
projects/naming/branches/Branch_5_0/jnpserver/pom.xml
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jboss/naming/BindingsInitializer.java
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/LocalOnlyContextFactory.java
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/NamingContext.java
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/Main.java
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/MainMBean.java
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingBeanImpl.java
projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingServer.java
projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingMCUnitTest.java
projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingServerSecurityManagerUnitTest.java
projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/log4j.xml
projects/naming/branches/Branch_5_0/pom.xml
Log:
[maven-release-plugin] copy for branch Branch_5_0
Copied: projects/naming/branches/Branch_5_0 (from rev 80546, projects/naming/trunk)
Deleted: projects/naming/branches/Branch_5_0/jnpserver/pom.xml
===================================================================
--- projects/naming/trunk/jnpserver/pom.xml 2008-11-05 04:14:24 UTC (rev 80546)
+++ projects/naming/branches/Branch_5_0/jnpserver/pom.xml 2008-11-06 00:53:21 UTC (rev 80569)
@@ -1,77 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <!-- Parent -->
- <parent>
- <groupId>org.jboss</groupId>
- <artifactId>jboss-parent</artifactId>
- <version>4-beta-2</version>
- </parent>
-
- <version>5.0.0-SNAPSHOT</version>
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.jboss.naming</groupId>
- <artifactId>jnpserver</artifactId>
- <packaging>jar</packaging>
- <name>JBoss Naming Server</name>
- <url>http://www.jboss.org</url>
- <description>The JBoss JNDI Server</description>
- <scm>
- <connection>scm:svn:https://svn.jboss.org/repos/jbossas/projects/naming/trunk</connection>
- </scm>
- <!-- Properties -->
- <properties>
- <version.org.jboss.common.core>2.2.8.GA</version.org.jboss.common.core>
- <version.org.jboss.microcontainer>2.0.0.CR2</version.org.jboss.microcontainer>
- </properties>
-
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <configuration>
- <descriptors>
- <descriptor>src/main/assembly/client.xml</descriptor>
- </descriptors>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <dependencies>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jboss-common-core</artifactId>
- <version>${version.org.jboss.common.core}</version>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.logging</groupId>
- <artifactId>jboss-logging-spi</artifactId>
- <version>2.0.5.GA</version>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.microcontainer</groupId>
- <artifactId>jboss-kernel</artifactId>
- <version>${version.org.jboss.microcontainer}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.man</groupId>
- <artifactId>jboss-managed</artifactId>
- <version>2.0.0.CR1</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.test</groupId>
- <artifactId>jboss-test</artifactId>
- <version>1.1.1.GA</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
Copied: projects/naming/branches/Branch_5_0/jnpserver/pom.xml (from rev 80567, projects/naming/trunk/jnpserver/pom.xml)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/pom.xml (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/pom.xml 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,77 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <!-- Parent -->
+ <parent>
+ <groupId>org.jboss</groupId>
+ <artifactId>jboss-parent</artifactId>
+ <version>4-beta-2</version>
+ </parent>
+
+ <version>5.0.0-SNAPSHOT</version>
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.jboss.naming</groupId>
+ <artifactId>jnpserver</artifactId>
+ <packaging>jar</packaging>
+ <name>JBoss Naming Server</name>
+ <url>http://www.jboss.org</url>
+ <description>The JBoss JNDI Server</description>
+ <scm>
+ <connection>scm:svn:https://svn.jboss.org/repos/jbossas/projects/naming/branches/Branch_5_0</connection>
+ </scm>
+ <!-- Properties -->
+ <properties>
+ <version.org.jboss.common.core>2.2.8.GA</version.org.jboss.common.core>
+ <version.org.jboss.microcontainer>2.0.0.CR2</version.org.jboss.microcontainer>
+ </properties>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/client.xml</descriptor>
+ </descriptors>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jboss-common-core</artifactId>
+ <version>${version.org.jboss.common.core}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.logging</groupId>
+ <artifactId>jboss-logging-spi</artifactId>
+ <version>2.0.5.GA</version>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>3.8.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.microcontainer</groupId>
+ <artifactId>jboss-kernel</artifactId>
+ <version>${version.org.jboss.microcontainer}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.man</groupId>
+ <artifactId>jboss-managed</artifactId>
+ <version>2.0.0.CR1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.test</groupId>
+ <artifactId>jboss-test</artifactId>
+ <version>1.1.1.GA</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
Deleted: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jboss/naming/BindingsInitializer.java
===================================================================
--- projects/naming/trunk/jnpserver/src/main/java/org/jboss/naming/BindingsInitializer.java 2008-11-05 04:14:24 UTC (rev 80546)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jboss/naming/BindingsInitializer.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -1,113 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.naming;
-
-import java.util.Map;
-
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-import org.jboss.logging.Logger;
-
-/**
- * A bean that can be used to create JNDI bindings
- * @author Scott.Stark at jboss.org
- * @version $Revision:$
- */
-public class BindingsInitializer
-{
- private static Logger log = Logger.getLogger(BindingsInitializer.class);
- private Map<String, ?> bindings;
- private InitialContext ctx;
-
- /**
- * The key/value bindings to add to jndi
- * @return The key/value bindings to add to jndi
- */
- public Map<String, ?> getBindings()
- {
- return bindings;
- }
- public void setBindings(Map<String, ?> bindings)
- {
- this.bindings = bindings;
- }
- /**
- * Get the InitialContext into which the bindings will be made.
- * @return
- */
- public InitialContext getCtx()
- {
- return ctx;
- }
- /**
- * Set the InitialContext into which the bindings will be made.
- * @param ctx
- */
- public void setCtx(InitialContext ctx)
- {
- this.ctx = ctx;
- }
- /**
- * Add the bindings to the ctx.
- *
- * @see #setBindings(Map)
- * @see #setCtx(InitialContext)
- * @throws NamingException
- */
- public void start()
- throws NamingException
- {
- log.debug("start");
- if(ctx != null)
- {
- if(bindings != null)
- {
- for(Map.Entry<String, ?> entry : bindings.entrySet())
- {
- String key = entry.getKey();
- Object value = entry.getValue();
- log.debug("Binding, key="+key+", value="+value+", type="+value.getClass());
- Util.bind(ctx, key, value);
- }
- }
- }
- }
- /**
- * Remove the bindings from the ctx.
- * @throws NamingException
- */
- public void stop()
- throws NamingException
- {
- if(ctx != null)
- {
- if(bindings != null)
- {
- for(String key : bindings.keySet())
- {
- Util.unbind(ctx, key);
- }
- }
- }
- }
-}
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jboss/naming/BindingsInitializer.java (from rev 80560, projects/naming/trunk/jnpserver/src/main/java/org/jboss/naming/BindingsInitializer.java)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jboss/naming/BindingsInitializer.java (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jboss/naming/BindingsInitializer.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,114 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.naming;
+
+import java.util.Map;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+import org.jboss.logging.Logger;
+
+/**
+ * A bean that can be used to create JNDI bindings
+ * @author Scott.Stark at jboss.org
+ * @version $Revision:$
+ */
+public class BindingsInitializer
+{
+ private static Logger log = Logger.getLogger(BindingsInitializer.class);
+ private Map<String, ?> bindings;
+ private Context ctx;
+
+ /**
+ * The key/value bindings to add to jndi
+ * @return The key/value bindings to add to jndi
+ */
+ public Map<String, ?> getBindings()
+ {
+ return bindings;
+ }
+ public void setBindings(Map<String, ?> bindings)
+ {
+ this.bindings = bindings;
+ }
+ /**
+ * Get the InitialContext into which the bindings will be made.
+ * @return
+ */
+ public Context getCtx()
+ {
+ return ctx;
+ }
+ /**
+ * Set the InitialContext into which the bindings will be made.
+ * @param ctx
+ */
+ public void setCtx(Context ctx)
+ {
+ this.ctx = ctx;
+ }
+ /**
+ * Add the bindings to the ctx.
+ *
+ * @see #setBindings(Map)
+ * @see #setCtx(InitialContext)
+ * @throws NamingException
+ */
+ public void start()
+ throws NamingException
+ {
+ log.debug("start");
+ if(ctx != null)
+ {
+ if(bindings != null)
+ {
+ for(Map.Entry<String, ?> entry : bindings.entrySet())
+ {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+ log.debug("Binding, key="+key+", value="+value+", type="+value.getClass());
+ Util.bind(ctx, key, value);
+ }
+ }
+ }
+ }
+ /**
+ * Remove the bindings from the ctx.
+ * @throws NamingException
+ */
+ public void stop()
+ throws NamingException
+ {
+ if(ctx != null)
+ {
+ if(bindings != null)
+ {
+ for(String key : bindings.keySet())
+ {
+ Util.unbind(ctx, key);
+ }
+ }
+ }
+ }
+}
Deleted: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/LocalOnlyContextFactory.java
===================================================================
--- projects/naming/trunk/jnpserver/src/main/java/org/jnp/interfaces/LocalOnlyContextFactory.java 2008-11-05 04:14:24 UTC (rev 80546)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/LocalOnlyContextFactory.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -1,64 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jnp.interfaces;
-
-import java.util.Hashtable;
-import javax.naming.Context;
-import javax.naming.Name;
-import javax.naming.NamingException;
-import javax.naming.Reference;
-import javax.naming.spi.InitialContextFactory;
-import javax.naming.spi.ObjectFactory;
-
-/**
- * An InitialContextFactory that uses the NamingContex.localServer naming server
- * which has to have been set.
- *
- * @author <a href="mailto:bill at jboss.org">Bill Burke</a>
- * @version $Revision$
- */
-public class LocalOnlyContextFactory
- implements InitialContextFactory, ObjectFactory
- {
- // InitialContextFactory implementation --------------------------
- public Context getInitialContext(Hashtable env)
- throws NamingException
- {
- Naming localServer = NamingContext.getLocal();
- if (localServer == null)
- throw new NamingException("Local server is not initialized");
- return new NamingContext(env, null, localServer);
- }
-
- // ObjectFactory implementation ----------------------------------
- public Object getObjectInstance(Object obj,
- Name name,
- Context nameCtx,
- Hashtable environment)
- throws Exception
- {
- Context ctx = getInitialContext(environment);
- Reference ref = (Reference)obj;
- return ctx.lookup((String)ref.get("URL").getContent());
- }
-
- }
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/LocalOnlyContextFactory.java (from rev 80559, projects/naming/trunk/jnpserver/src/main/java/org/jnp/interfaces/LocalOnlyContextFactory.java)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/LocalOnlyContextFactory.java (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/LocalOnlyContextFactory.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,121 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jnp.interfaces;
+
+import java.lang.ref.WeakReference;
+import java.util.Hashtable;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.naming.Context;
+import javax.naming.NamingException;
+import javax.naming.spi.InitialContextFactory;
+
+import org.jboss.logging.Logger;
+
+/**
+ * An InitialContextFactory that uses the either NamingContex.localServer naming
+ * server which has to have been set, or injected.
+ *
+ * @author <a href="mailto:bill at jboss.org">Bill Burke</a>
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public class LocalOnlyContextFactory implements InitialContextFactory
+{
+ private static final Logger log = Logger.getLogger(LocalOnlyContextFactory.class);
+
+ /** A set of Naming instances with names */
+ private static ConcurrentHashMap<String, WeakReference<Naming>> localServers = new ConcurrentHashMap<String, WeakReference<Naming>>();
+ private Naming naming;
+
+ public Naming getNaming()
+ {
+ return naming;
+ }
+ /**
+ * Set the Naming instance to use for the root content.
+ * @param naming - the Naming instance to use, null if the global
+ * NamingContext.getLocal value should be used.
+ */
+ public void setNaming(Naming naming)
+ {
+ this.naming = naming;
+ }
+
+ // InitialContextFactory implementation --------------------------
+ public Context getInitialContext(Hashtable<?,?> env)
+ throws NamingException
+ {
+ boolean trace = log.isTraceEnabled();
+ if(trace)
+ log.trace("getInitialContext, env: "+env);
+ String name = null;
+ Naming localServer = null;
+ if(env != null)
+ {
+ // First try the naming property instance
+ localServer = (Naming) env.get(NamingContext.JNP_NAMING_INSTANCE);
+ if(trace && localServer != null)
+ log.trace("Set naming from "+NamingContext.JNP_NAMING_INSTANCE);
+ name = (String) env.get(NamingContext.JNP_NAMING_INSTANCE_NAME);
+ }
+ // Next try the injected naming instance
+ if (localServer == null)
+ {
+ localServer = naming;
+ if(trace && localServer != null)
+ log.trace("Set naming from injected value");
+ }
+ // Next try to locate the instance by name
+ if (localServer == null && name != null)
+ {
+ WeakReference<Naming> lswr = localServers.get(name);
+ if(lswr != null)
+ localServer = lswr.get();
+ if(trace && localServer != null)
+ log.trace("Set naming from "+NamingContext.JNP_NAMING_INSTANCE_NAME+"="+name);
+ }
+ // Lastly try the JVM global NamingContext.local value
+ if (localServer == null)
+ {
+ localServer = NamingContext.getLocal();
+ if(trace && localServer != null)
+ log.trace("Set naming from NamingContext.getLocal");
+ }
+
+ if (localServer == null)
+ throw new NamingException("Failed to determine local server from: "+env);
+
+ // If this is a named instance add it to the localServers set
+ if (name != null && localServers.containsKey(name) == false)
+ {
+ localServers.put(name, new WeakReference<Naming>(localServer));
+ if(trace)
+ log.trace("Set localServers:"+name);
+ }
+
+ // Pass in an empty env if its null
+ if(env == null)
+ env = new Hashtable();
+ return new NamingContext(env, null, localServer);
+ }
+}
Deleted: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/NamingContext.java
===================================================================
--- projects/naming/trunk/jnpserver/src/main/java/org/jnp/interfaces/NamingContext.java 2008-11-05 04:14:24 UTC (rev 80546)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/NamingContext.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -1,1828 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jnp.interfaces;
-
-import java.io.BufferedInputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.SerializablePermission;
-import java.lang.ref.WeakReference;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.ReflectPermission;
-import java.net.DatagramPacket;
-import java.net.InetAddress;
-import java.net.MulticastSocket;
-import java.net.Socket;
-import java.net.InetSocketAddress;
-import java.rmi.ConnectException;
-import java.rmi.MarshalledObject;
-import java.rmi.NoSuchObjectException;
-import java.rmi.RemoteException;
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.StringTokenizer;
-import javax.naming.Binding;
-import javax.naming.CannotProceedException;
-import javax.naming.CommunicationException;
-import javax.naming.ConfigurationException;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.InvalidNameException;
-import javax.naming.LinkRef;
-import javax.naming.Name;
-import javax.naming.NameParser;
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-import javax.naming.NotContextException;
-import javax.naming.ContextNotEmptyException;
-import javax.naming.Reference;
-import javax.naming.Referenceable;
-import javax.naming.ServiceUnavailableException;
-import javax.naming.event.EventContext;
-import javax.naming.event.NamingListener;
-import javax.naming.spi.NamingManager;
-import javax.naming.spi.ResolveResult;
-import javax.net.SocketFactory;
-
-import org.jboss.logging.Logger;
-
-/**
- * This class provides the jnp provider Context implementation. It is a Context
- * interface wrapper for a RMI Naming instance that is obtained from either the
- * local server instance or by locating the server given by the
- * Context.PROVIDER_URL value.
- *
- * This class also serves as the jnp url resolution context. jnp style urls
- * passed to the
- * @author oberg
- * @author scott.stark at jboss.org
- * @version $Revision$
- */
-public class NamingContext
- implements EventContext, java.io.Serializable
-{
- // Constants -----------------------------------------------------
- /**
- * @since 1.7
- */
- static final long serialVersionUID = 8906455608484282128L;
- /**
- * The javax.net.SocketFactory impl to use for the bootstrap socket
- */
- public static final String JNP_SOCKET_FACTORY = "jnp.socketFactory";
- /**
- * The local address to bind the connected bootstrap socket to
- */
- public static final String JNP_LOCAL_ADDRESS = "jnp.localAddress";
- /**
- * The local port to bind the connected bootstrap socket to
- */
- public static final String JNP_LOCAL_PORT = "jnp.localPort";
- /**
- * A flag to disable the broadcast discovery queries
- */
- public static final String JNP_DISABLE_DISCOVERY = "jnp.disableDiscovery";
- /**
- * The cluster partition discovery should be restricted to
- */
- public static final String JNP_PARTITION_NAME = "jnp.partitionName";
- /**
- * The multicast IP/address to which the discovery query is sent
- */
- public static final String JNP_DISCOVERY_GROUP = "jnp.discoveryGroup";
- /**
- * The port to which the discovery query is sent
- */
- public static final String JNP_DISCOVERY_PORT = "jnp.discoveryPort";
-
- /** The time-to-live for the multicast discovery packets */
- public static final String JNP_DISCOVERY_TTL = "jnp.discoveryTTL";
-
- /**
- * The time in MS to wait for a discovery query response
- */
- public static final String JNP_DISCOVERY_TIMEOUT = "jnp.discoveryTimeout";
- /**
- * An internal property added by parseNameForScheme if the input name uses a
- * url prefix that was removed during cannonicalization. This is needed to
- * avoid modification of the incoming Name.
- */
- public static final String JNP_PARSED_NAME = "jnp.parsedName";
- /**
- * A flag indicating the style of names passed to NamingManager method.
- * True for api expected relative names, false for absolute names as used
- * historically by the jboss naming implementation.
- */
- public static final String JNP_USE_RELATIVE_NAME = "jnp.useRelativeName";
- /**
- * An integer that controls the number of connection retry attempts will
- * be made on the initial connection to the naming server. This only applies
- * to ConnectException failures. A value <= 1 means that only one attempt
- * will be made.
- */
- public static final String JNP_MAX_RETRIES = "jnp.maxRetries";
-
- /**
- * The default discovery multicast information
- */
- public final static String DEFAULT_DISCOVERY_GROUP_ADDRESS = "230.0.0.4";
- public final static int DEFAULT_DISCOVERY_GROUP_PORT = 1102;
- public final static int DEFAULT_DISCOVERY_TIMEOUT = 5000;
-
- /**
- * An obsolete constant replaced by the JNP_MAX_RETRIES value
- */
- public static int MAX_RETRIES = 1;
- /**
- * The JBoss logging interface
- */
- private static Logger log = Logger.getLogger(NamingContext.class);
-
- // Static --------------------------------------------------------
- /** HAJNDI keyed by partition name */
- private static Hashtable haServers = new Hashtable();
- private static RuntimePermission GET_HA_NAMING_SERVER = new RuntimePermission("org.jboss.naming.NamingContext.getHANamingServerForPartition");
- private static RuntimePermission SET_HA_NAMING_SERVER = new RuntimePermission("org.jboss.naming.NamingContext.setHANamingServerForPartition");
- public static void setHANamingServerForPartition(String partitionName, Naming haServer)
- {
- SecurityManager security = System.getSecurityManager();
- if(security != null)
- security.checkPermission(SET_HA_NAMING_SERVER);
- haServers.put(partitionName, haServer);
- }
-
- public static void removeHANamingServerForPartition(String partitionName)
- {
- SecurityManager security = System.getSecurityManager();
- if(security != null)
- security.checkPermission(SET_HA_NAMING_SERVER);
- haServers.remove(partitionName);
- }
-
- public static Naming getHANamingServerForPartition(String partitionName)
- {
- SecurityManager security = System.getSecurityManager();
- if(security != null)
- security.checkPermission(GET_HA_NAMING_SERVER);
- return (Naming) haServers.get(partitionName);
- }
-
- /**
- * The jvm local server used for non-transport access to the naming
- * server
- * @see #checkRef(Hashtable)
- * @see {@linkplain LocalOnlyContextFactory}
- */
- private static Naming localServer;
- private static RuntimePermission GET_LOCAL_SERVER = new RuntimePermission("org.jboss.naming.NamingContext.getLocal");
- private static RuntimePermission SET_LOCAL_SERVER = new RuntimePermission("org.jboss.naming.NamingContext.setLocal");
-
- // Attributes ----------------------------------------------------
- Naming naming;
- Hashtable env;
- Name prefix;
-
- NameParser parser = new NamingParser();
-
- // Static --------------------------------------------------------
-
- // Cache of naming server stubs
- // This is a critical optimization in the case where new InitialContext
- // is performed often. The server stub will be shared between all those
- // calls, which will improve performance.
- // Weak references are used so if no contexts use a particular server
- // it will be removed from the cache.
- static HashMap cachedServers = new HashMap();
-
- static void addServer(String name, Naming server)
- {
- // Add server to map
- synchronized (NamingContext.class)
- {
- cachedServers.put(name, new WeakReference(server));
- }
- }
-
- static Naming getServer(String host, int port, Hashtable serverEnv)
- throws NamingException
- {
- // Check the server cache for a host:port entry
- String hostKey = host + ":" + port;
- WeakReference ref = (WeakReference) cachedServers.get(hostKey);
- Naming server;
- if (ref != null)
- {
- server = (Naming) ref.get();
- if (server != null)
- {
- // JBAS-4622. Ensure the env for the request has the
- // hostKey so we can remove the cache entry if there is a failure
- serverEnv.put("hostKey", hostKey);
- return server;
- }
- }
-
- // Server not found; add it to cache
- try
- {
- SocketFactory factory = loadSocketFactory(serverEnv);
- Socket s;
-
- try
- {
- InetAddress localAddr = null;
- int localPort = 0;
- String localAddrStr = (String) serverEnv.get(JNP_LOCAL_ADDRESS);
- String localPortStr = (String) serverEnv.get(JNP_LOCAL_PORT);
- if (localAddrStr != null)
- localAddr = InetAddress.getByName(localAddrStr);
- if (localPortStr != null)
- localPort = Integer.parseInt(localPortStr);
- s = factory.createSocket(host, port, localAddr, localPort);
- }
- catch (IOException e)
- {
- NamingException ex = new ServiceUnavailableException("Failed to connect to server " + hostKey);
- ex.setRootCause(e);
- throw ex;
- }
-
- // Get stub from naming server
- BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
- ObjectInputStream in = new ObjectInputStream(bis);
- MarshalledObject stub = (MarshalledObject) in.readObject();
- server = (Naming) stub.get();
- s.close();
-
- // Add it to cache
- addServer(hostKey, server);
- serverEnv.put("hostKey", hostKey);
-
- return server;
- }
- catch (IOException e)
- {
- NamingException ex = new CommunicationException("Failed to retrieve stub from server " + hostKey);
- ex.setRootCause(e);
- throw ex;
- }
- catch (Exception e)
- {
- NamingException ex = new CommunicationException("Failed to connect to server " + hostKey);
- ex.setRootCause(e);
- throw ex;
- }
- }
-
- /**
- * Create a SocketFactory based on the JNP_SOCKET_FACTORY property in the
- * given env. If JNP_SOCKET_FACTORY is not specified default to the
- * TimedSocketFactory.
- */
- static SocketFactory loadSocketFactory(Hashtable serverEnv)
- throws ClassNotFoundException, IllegalAccessException,
- InstantiationException, InvocationTargetException
- {
- SocketFactory factory = null;
-
- // Get the socket factory classname
- String socketFactoryName = (String) serverEnv.get(JNP_SOCKET_FACTORY);
- if (socketFactoryName == null ||
- socketFactoryName.equals(TimedSocketFactory.class.getName()))
- {
- factory = new TimedSocketFactory(serverEnv);
- return factory;
- }
-
- /* Create the socket factory. Look for a ctor that accepts a
- Hashtable and if not found use the default ctor.
- */
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- Class factoryClass = loader.loadClass(socketFactoryName);
- try
- {
- Class[] ctorSig = {Hashtable.class};
- Constructor ctor = factoryClass.getConstructor(ctorSig);
- Object[] ctorArgs = {serverEnv};
- factory = (SocketFactory) ctor.newInstance(ctorArgs);
- }
- catch (NoSuchMethodException e)
- {
- // Use the default ctor
- factory = (SocketFactory) factoryClass.newInstance();
- }
- return factory;
- }
-
- static void removeServer(Hashtable serverEnv)
- {
- String host = "localhost";
- int port = 1099;
-
- // Locate naming service
- if (serverEnv.get(Context.PROVIDER_URL) != null)
- {
- String providerURL = (String) serverEnv.get(Context.PROVIDER_URL);
-
- StringTokenizer tokenizer = new StringTokenizer(providerURL, ", ");
- while (tokenizer.hasMoreElements())
- {
- String url = tokenizer.nextToken();
-
- try
- {
- // Parse the url into a host:port form, stripping any protocol
- Name urlAsName = new NamingParser().parse(url);
- String server = parseNameForScheme(urlAsName, null);
- if (server != null)
- url = server;
- int colon = url.indexOf(':');
- if (colon < 0)
- {
- host = url.trim();
- }
- else
- {
- host = url.substring(0, colon).trim();
- try
- {
- port = Integer.parseInt(url.substring(colon + 1).trim());
- }
- catch (Exception ex)
- {
- // Use default;
- }
- }
-
- // Remove server from map
- synchronized (NamingContext.class)
- {
- cachedServers.remove(host + ":" + port);
- }
- }
- catch (NamingException ignored)
- {
- }
- }
- }
-
- // JBAS-4622. Always do this.
- Object hostKey = serverEnv.remove("hostKey");
- if (hostKey != null)
- {
- synchronized (NamingContext.class)
- {
- cachedServers.remove(hostKey);
- }
- }
- }
-
- /**
- * Called to remove any url scheme atoms and extract the naming service
- * hostname:port information.
- * @param n the name component to the parsed. After returning n will have all
- * scheme related atoms removed.
- * @return the naming service hostname:port information string if name
- * contained the host information.
- */
- static String parseNameForScheme(Name n, Hashtable nameEnv)
- throws InvalidNameException
- {
- String serverInfo = null;
- if (n.size() > 0)
- {
- String scheme = n.get(0);
- int schemeLength = 0;
- if (scheme.startsWith("java:"))
- schemeLength = 5;
- else if (scheme.startsWith("jnp:"))
- schemeLength = 4;
- else if (scheme.startsWith("jnps:"))
- schemeLength = 5;
- else if (scheme.startsWith("jnp-http:"))
- schemeLength = 9;
- else if (scheme.startsWith("jnp-https:"))
- schemeLength = 10;
- if (schemeLength > 0)
- {
- // Make a copy of the name to avoid
- n = (Name) n.clone();
- String suffix = scheme.substring(schemeLength);
- if (suffix.length() == 0)
- {
- // Scheme was "url:/..."
- n.remove(0);
- if (n.size() > 1 && n.get(0).equals(""))
- {
- // Scheme was "url://hostname:port/..."
- // Get hostname:port value for the naming server
- serverInfo = n.get(1);
- n.remove(0);
- n.remove(0);
- // If n is a empty atom remove it or else a '/' will result
- if (n.size() == 1 && n.get(0).length() == 0)
- n.remove(0);
- }
- }
- else
- {
- // Scheme was "url:foo" -> reinsert "foo"
- n.remove(0);
- n.add(0, suffix);
- }
- if (nameEnv != null)
- nameEnv.put(JNP_PARSED_NAME, n);
- }
- }
- return serverInfo;
- }
-
- public static Naming getLocal()
- {
- SecurityManager security = System.getSecurityManager();
- if(security != null)
- security.checkPermission(GET_LOCAL_SERVER);
- return localServer;
- }
- public static void setLocal(Naming server)
- {
- SecurityManager security = System.getSecurityManager();
- if(security != null)
- security.checkPermission(SET_LOCAL_SERVER);
- localServer = server;
- }
-
- // Constructors --------------------------------------------------
- public NamingContext(Hashtable e, Name baseName, Naming server)
- throws NamingException
- {
- if (baseName == null)
- this.prefix = parser.parse("");
- else
- this.prefix = baseName;
-
- if (e != null)
- this.env = (Hashtable) e.clone();
- else
- this.env = new Hashtable();
-
- this.naming = server;
- }
-
- // Public --------------------------------------------------------
- public Naming getNaming()
- {
- return this.naming;
- }
-
- public void setNaming(Naming server)
- {
- this.naming = server;
- }
-
- // Context implementation ----------------------------------------
- public void rebind(String name, Object obj)
- throws NamingException
- {
- rebind(getNameParser(name).parse(name), obj);
- }
-
- public void rebind(Name name, Object obj)
- throws NamingException
- {
- Hashtable refEnv = getEnv(name);
- checkRef(refEnv);
- Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
- if (parsedName != null)
- name = parsedName;
-
- // Allow state factories to change the stored object
- obj = getStateToBind(obj, name, refEnv);
-
- try
- {
- String className = null;
-
- // Referenceable
- if (obj instanceof Referenceable)
- obj = ((Referenceable) obj).getReference();
-
- if (!(obj instanceof Reference))
- {
- if( obj != null )
- className = obj.getClass().getName();
- obj = createMarshalledValuePair(obj);
- }
- else
- {
- className = ((Reference) obj).getClassName();
- }
- try
- {
- naming.rebind(getAbsoluteName(name), obj, className);
- }
- catch (RemoteException re)
- {
- // Check for JBAS-4574.
- if (handleStaleNamingStub(re, refEnv))
- {
- // try again with new naming stub
- naming.rebind(getAbsoluteName(name), obj, className);
- }
- else
- {
- // Not JBAS-4574. Throw exception and let outer logic handle it.
- throw re;
- }
- }
- }
- catch (CannotProceedException cpe)
- {
- cpe.setEnvironment(refEnv);
- Context cctx = NamingManager.getContinuationContext(cpe);
- cctx.rebind(cpe.getRemainingName(), obj);
- }
- catch (IOException e)
- {
- naming = null;
- removeServer(refEnv);
- NamingException ex = new CommunicationException();
- ex.setRootCause(e);
- throw ex;
- }
- }
-
- public void bind(String name, Object obj)
- throws NamingException
- {
- bind(getNameParser(name).parse(name), obj);
- }
-
- public void bind(Name name, Object obj)
- throws NamingException
- {
- Hashtable refEnv = getEnv(name);
- checkRef(refEnv);
- Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
- if (parsedName != null)
- name = parsedName;
-
- // Allow state factories to change the stored object
- obj = getStateToBind(obj, name, refEnv);
-
- try
- {
- String className = null;
-
- // Referenceable
- if (obj instanceof Referenceable)
- obj = ((Referenceable) obj).getReference();
-
- if (!(obj instanceof Reference))
- {
- if( obj != null )
- className = obj.getClass().getName();
-
- // Normal object - serialize using a MarshalledValuePair
- obj = createMarshalledValuePair(obj);
- }
- else
- {
- className = ((Reference) obj).getClassName();
- }
- name = getAbsoluteName(name);
-
- try
- {
- naming.bind(name, obj, className);
- }
- catch (RemoteException re)
- {
- // Check for JBAS-4574.
- if (handleStaleNamingStub(re, refEnv))
- {
- // try again with new naming stub
- naming.bind(name, obj, className);
- }
- else
- {
- // Not JBAS-4574. Throw exception and let outer logic handle it.
- throw re;
- }
- }
- }
- catch (CannotProceedException cpe)
- {
- cpe.setEnvironment(refEnv);
- Context cctx = NamingManager.getContinuationContext(cpe);
- cctx.bind(cpe.getRemainingName(), obj);
- }
- catch (IOException e)
- {
- naming = null;
- removeServer(refEnv);
- NamingException ex = new CommunicationException();
- ex.setRootCause(e);
- throw ex;
- }
- }
-
- public Object lookup(String name)
- throws NamingException
- {
- return lookup(getNameParser(name).parse(name));
- }
-
- public Object lookup(Name name)
- throws NamingException
- {
- Hashtable refEnv = getEnv(name);
- checkRef(refEnv);
- Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
- if (parsedName != null)
- name = parsedName;
-
- // Empty?
- if (name.isEmpty())
- return new NamingContext(refEnv, prefix, naming);
-
- try
- {
- int maxTries = 1;
- try
- {
- String n = (String) refEnv.get(JNP_MAX_RETRIES);
- if( n != null )
- maxTries = Integer.parseInt(n);
- if( maxTries <= 0 )
- maxTries = 1;
- }
- catch(Exception e)
- {
- log.debug("Failed to get JNP_MAX_RETRIES, using 1", e);
- }
- Name n = getAbsoluteName(name);
- Object res = null;
- boolean trace = log.isTraceEnabled();
- for (int i = 0; i < maxTries; i++)
- {
- try
- {
- try
- {
- res = naming.lookup(n);
- }
- catch (RemoteException re)
- {
- // Check for JBAS-4574.
- if (handleStaleNamingStub(re, refEnv))
- {
- // try again with new naming stub
- res = naming.lookup(n);
- }
- else
- {
- // Not JBAS-4574. Throw exception and let outer logic handle it.
- throw re;
- }
- }
- // If we got here, we succeeded, so break the loop
- break;
- }
- catch (ConnectException ce)
- {
- int retries = maxTries - i - 1;
- if( trace )
- log.trace("Connect failed, retry count: "+retries, ce);
- // We may overload server so sleep and retry
- if (retries > 0)
- {
- try
- {
- Thread.sleep(1);
- }
- catch (InterruptedException ignored)
- {
- }
- continue;
- }
- // Throw the exception to flush the bad server
- throw ce;
- }
- }
- if (res instanceof MarshalledValuePair)
- {
- MarshalledValuePair mvp = (MarshalledValuePair) res;
- Object storedObj = mvp.get();
- return getObjectInstanceWrapFailure(storedObj, name, refEnv);
- }
- else if (res instanceof MarshalledObject)
- {
- MarshalledObject mo = (MarshalledObject) res;
- return mo.get();
- }
- else if (res instanceof Context)
- {
- // Add env
- Enumeration keys = refEnv.keys();
- while (keys.hasMoreElements())
- {
- String key = (String) keys.nextElement();
- ((Context) res).addToEnvironment(key, refEnv.get(key));
- }
- return res;
- }
- else if (res instanceof ResolveResult)
- {
- // Dereference partial result
- ResolveResult rr = (ResolveResult) res;
- Object resolveRes = rr.getResolvedObj();
- Object context;
- Object instanceID;
-
- if (resolveRes instanceof LinkRef)
- {
- context = resolveLink(resolveRes, null);
- instanceID = ((LinkRef) resolveRes).getLinkName();
- }
- else
- {
- context = getObjectInstanceWrapFailure(resolveRes, name, refEnv);
- instanceID = context;
- }
-
- if ((context instanceof Context) == false)
- {
- throw new NotContextException(instanceID + " is not a Context");
- }
- Context ncontext = (Context) context;
- return ncontext.lookup(rr.getRemainingName());
- }
- else if (res instanceof LinkRef)
- {
- // Dereference link
- res = resolveLink(res, refEnv);
- }
- else if (res instanceof Reference)
- {
- // Dereference object
- res = getObjectInstanceWrapFailure(res, name, refEnv);
- if (res instanceof LinkRef)
- res = resolveLink(res, refEnv);
- }
-
- return res;
- }
- catch (CannotProceedException cpe)
- {
- cpe.setEnvironment(refEnv);
- Context cctx = NamingManager.getContinuationContext(cpe);
- return cctx.lookup(cpe.getRemainingName());
- }
- catch (IOException e)
- {
- naming = null;
- removeServer(refEnv);
- NamingException ex = new CommunicationException();
- ex.setRootCause(e);
- throw ex;
- }
- catch (ClassNotFoundException e)
- {
- NamingException ex = new CommunicationException();
- ex.setRootCause(e);
- throw ex;
- }
- }
-
- public void unbind(String name)
- throws NamingException
- {
- unbind(getNameParser(name).parse(name));
- }
-
-
- public void unbind(Name name)
- throws NamingException
- {
- Hashtable refEnv = getEnv(name);
- checkRef(refEnv);
- Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
- if (parsedName != null)
- name = parsedName;
-
- try
- {
- try
- {
- naming.unbind(getAbsoluteName(name));
- }
- catch (RemoteException re)
- {
- // Check for JBAS-4574.
- if (handleStaleNamingStub(re, refEnv))
- {
- // try again with new naming stub
- naming.unbind(getAbsoluteName(name));
- }
- else
- {
- // Not JBAS-4574. Throw exception and let outer logic handle it.
- throw re;
- }
- }
- }
- catch (CannotProceedException cpe)
- {
- cpe.setEnvironment(refEnv);
- Context cctx = NamingManager.getContinuationContext(cpe);
- cctx.unbind(cpe.getRemainingName());
- }
- catch (IOException e)
- {
- naming = null;
- removeServer(refEnv);
- NamingException ex = new CommunicationException();
- ex.setRootCause(e);
- throw ex;
- }
- }
-
- public void rename(String oldname, String newname)
- throws NamingException
- {
- rename(getNameParser(oldname).parse(oldname), getNameParser(newname).parse(newname));
- }
-
- public void rename(Name oldName, Name newName)
- throws NamingException
- {
- bind(newName, lookup(oldName));
- unbind(oldName);
- }
-
- public NamingEnumeration list(String name)
- throws NamingException
- {
- return list(getNameParser(name).parse(name));
- }
-
- public NamingEnumeration list(Name name)
- throws NamingException
- {
- Hashtable refEnv = getEnv(name);
- checkRef(refEnv);
- Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
- if (parsedName != null)
- name = parsedName;
-
- try
- {
- Collection c = null;
- try
- {
- c = naming.list(getAbsoluteName(name));
- }
- catch (RemoteException re)
- {
- // Check for JBAS-4574.
- if (handleStaleNamingStub(re, refEnv))
- {
- // try again with new naming stub
- c = naming.list(getAbsoluteName(name));
- }
- else
- {
- // Not JBAS-4574. Throw exception and let outer logic handle it.
- throw re;
- }
- }
- return new NamingEnumerationImpl(c);
- }
- catch (CannotProceedException cpe)
- {
- cpe.setEnvironment(refEnv);
- Context cctx = NamingManager.getContinuationContext(cpe);
- return cctx.list(cpe.getRemainingName());
- }
- catch (IOException e)
- {
- naming = null;
- removeServer(refEnv);
- NamingException ex = new CommunicationException();
- ex.setRootCause(e);
- throw ex;
- }
- }
-
- public NamingEnumeration listBindings(String name)
- throws NamingException
- {
- return listBindings(getNameParser(name).parse(name));
- }
-
- public NamingEnumeration listBindings(Name name)
- throws NamingException
- {
- Hashtable refEnv = getEnv(name);
- checkRef(refEnv);
- Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
- if (parsedName != null)
- name = parsedName;
-
- try
- {
- // Get list
- Collection bindings = null;
- try
- {
- // Get list
- bindings = naming.listBindings(getAbsoluteName(name));
- }
- catch (RemoteException re)
- {
- // Check for JBAS-4574.
- if (handleStaleNamingStub(re, refEnv))
- {
- // try again with new naming stub
- bindings = naming.listBindings(getAbsoluteName(name));
- }
- else
- {
- // Not JBAS-4574. Throw exception and let outer logic handle it.
- throw re;
- }
- }
- Collection realBindings = new ArrayList(bindings.size());
-
- // Convert marshalled objects
- Iterator i = bindings.iterator();
- while (i.hasNext())
- {
- Binding binding = (Binding) i.next();
- Object obj = binding.getObject();
- if (obj instanceof MarshalledValuePair)
- {
- try
- {
- obj = ((MarshalledValuePair) obj).get();
- }
- catch (ClassNotFoundException e)
- {
- NamingException ex = new CommunicationException();
- ex.setRootCause(e);
- throw ex;
- }
- }
- else if (obj instanceof MarshalledObject)
- {
- try
- {
- obj = ((MarshalledObject) obj).get();
- }
- catch (ClassNotFoundException e)
- {
- NamingException ex = new CommunicationException();
- ex.setRootCause(e);
- throw ex;
- }
- }
- realBindings.add(new Binding(binding.getName(), binding.getClassName(), obj));
- }
-
- // Return transformed list of bindings
- return new NamingEnumerationImpl(realBindings);
- }
- catch (CannotProceedException cpe)
- {
- cpe.setEnvironment(refEnv);
- Context cctx = NamingManager.getContinuationContext(cpe);
- return cctx.listBindings(cpe.getRemainingName());
- }
- catch (IOException e)
- {
- naming = null;
- removeServer(refEnv);
- NamingException ex = new CommunicationException();
- ex.setRootCause(e);
- throw ex;
- }
- }
-
- public String composeName(String name, String prefix)
- throws NamingException
- {
- Name result = composeName(parser.parse(name),
- parser.parse(prefix));
- return result.toString();
- }
-
- public Name composeName(Name name, Name prefix)
- throws NamingException
- {
- Name result = (Name) (prefix.clone());
- result.addAll(name);
- return result;
- }
-
- public NameParser getNameParser(String name)
- throws NamingException
- {
- return parser;
- }
-
- public NameParser getNameParser(Name name)
- throws NamingException
- {
- return getNameParser(name.toString());
- }
-
- public Context createSubcontext(String name)
- throws NamingException
- {
- return createSubcontext(getNameParser(name).parse(name));
- }
-
- public Context createSubcontext(Name name)
- throws NamingException
- {
- if (name.size() == 0)
- throw new InvalidNameException("Cannot pass an empty name to createSubcontext");
-
- Hashtable refEnv = getEnv(name);
- checkRef(refEnv);
- Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
- if (parsedName != null)
- name = parsedName;
-
- try
- {
- name = getAbsoluteName(name);
- try
- {
- return naming.createSubcontext(name);
- }
- catch (RemoteException re)
- {
- // Check for JBAS-4574.
- if (handleStaleNamingStub(re, refEnv))
- {
- // try again with new naming stub
- return naming.createSubcontext(name);
- }
- else
- {
- // Not JBAS-4574. Throw exception and let outer logic handle it.
- throw re;
- }
- }
- }
- catch (CannotProceedException cpe)
- {
- cpe.setEnvironment(refEnv);
- Context cctx = NamingManager.getContinuationContext(cpe);
- return cctx.createSubcontext(cpe.getRemainingName());
- }
- catch (IOException e)
- {
- naming = null;
- removeServer(refEnv);
- NamingException ex = new CommunicationException();
- ex.setRootCause(e);
- throw ex;
- }
- }
-
- public Object addToEnvironment(String propName, Object propVal)
- throws NamingException
- {
- Object old = env.get(propName);
- env.put(propName, propVal);
- return old;
- }
-
- public Object removeFromEnvironment(String propName)
- throws NamingException
- {
- return env.remove(propName);
- }
-
- public Hashtable getEnvironment()
- throws NamingException
- {
- return env;
- }
-
- public void close()
- throws NamingException
- {
- env = null;
- naming = null;
- }
-
- public String getNameInNamespace()
- throws NamingException
- {
- return prefix.toString();
- }
-
- public void destroySubcontext(String name)
- throws NamingException
- {
- destroySubcontext(getNameParser(name).parse(name));
- }
-
- public void destroySubcontext(Name name)
- throws NamingException
- {
- if (!list(name).hasMore())
- {
- unbind(name);
- }
- else
- throw new ContextNotEmptyException();
- }
-
- public Object lookupLink(String name)
- throws NamingException
- {
- return lookupLink(getNameParser(name).parse(name));
- }
-
- /**
- * Lookup the object referred to by name but don't dereferrence the final
- * component. This really just involves returning the raw value returned by
- * the Naming.lookup() method.
- * @return the raw object bound under name.
- */
- public Object lookupLink(Name name)
- throws NamingException
- {
- Hashtable refEnv = getEnv(name);
- checkRef(refEnv);
- Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
- if (parsedName != null)
- name = parsedName;
-
- if (name.isEmpty())
- return lookup(name);
-
- Object link = null;
- try
- {
- Name n = getAbsoluteName(name);
- try
- {
- link = naming.lookup(n);
- }
- catch (RemoteException re)
- {
- // Check for JBAS-4574.
- if (handleStaleNamingStub(re, refEnv))
- {
- // try again with new naming stub
- link = naming.lookup(n);
- }
- else
- {
- // Not JBAS-4574. Throw exception and let outer logic handle it.
- throw re;
- }
- }
- if (!(link instanceof LinkRef) && link instanceof Reference)
- link = getObjectInstance(link, name, null);
- ;
- }
- catch (IOException e)
- {
- naming = null;
- removeServer(refEnv);
- NamingException ex = new CommunicationException();
- ex.setRootCause(e);
- throw ex;
- }
- catch (Exception e)
- {
- NamingException ex = new NamingException("Could not lookup link");
- ex.setRemainingName(name);
- ex.setRootCause(e);
- throw ex;
- }
- return link;
- }
-
- // Begin EventContext methods
- public void addNamingListener(Name target, int scope, NamingListener l)
- throws NamingException
- {
- if((naming instanceof NamingEvents) == false)
- {
- throw new UnsupportedOperationException("Naming implementation does not support NamingExt");
- }
- NamingEvents next = (NamingEvents) naming;
- try
- {
- next.addNamingListener(this, target, scope, l);
- }
- catch (RemoteException e)
- {
- CommunicationException ce = new CommunicationException("addNamingListener failed");
- ce.initCause(e);
- }
- }
-
- public void addNamingListener(String target, int scope, NamingListener l)
- throws NamingException
- {
- Name targetName = parser.parse(target);
- addNamingListener(targetName, scope, l);
- }
-
- public void removeNamingListener(NamingListener l)
- throws NamingException
- {
- if((naming instanceof NamingEvents) == false)
- {
- throw new UnsupportedOperationException("Naming implementation does not support NamingExt");
- }
- NamingEvents next = (NamingEvents) naming;
- try
- {
- next.removeNamingListener(l);
- }
- catch (RemoteException e)
- {
- CommunicationException ce = new CommunicationException("removeNamingListener failed");
- ce.initCause(e);
- }
- }
-
- public boolean targetMustExist()
- throws NamingException
- {
- if((naming instanceof NamingEvents) == false)
- {
- throw new UnsupportedOperationException("Naming implementation does not support NamingExt");
- }
- NamingEvents next = (NamingEvents) naming;
- boolean targetMustExist = true;
- try
- {
- targetMustExist = next.targetMustExist();
- }
- catch (RemoteException e)
- {
- CommunicationException ce = new CommunicationException("removeNamingListener failed");
- ce.initCause(e);
- }
- return targetMustExist;
- }
- // End EventContext methods
-
- protected Object resolveLink(Object res, Hashtable refEnv)
- throws NamingException
- {
- Object linkResult = null;
- try
- {
- LinkRef link = (LinkRef) res;
- String ref = link.getLinkName();
- if (ref.startsWith("./"))
- linkResult = lookup(ref.substring(2));
- else if (refEnv != null)
- linkResult = new InitialContext(refEnv).lookup(ref);
- else
- linkResult = new InitialContext().lookup(ref);
- }
- catch (Exception e)
- {
- NamingException ex = new NamingException("Could not dereference object");
- ex.setRootCause(e);
- throw ex;
- }
- return linkResult;
- }
-
- // Private -------------------------------------------------------
-
- /**
- * Isolate the creation of the MarshalledValuePair in a privileged block
- * when running under a security manager so the following permissions can
- * be isolated from the caller:
- * RuntimePermission("createClassLoader")
- ReflectPermission("suppressAccessChecks")
- SerializablePermission("enableSubstitution")
- @return the MarshalledValuePair wrapping obj
- */
- private Object createMarshalledValuePair(final Object obj)
- throws IOException
- {
- MarshalledValuePair mvp = null;
- SecurityManager sm = System.getSecurityManager();
- if(sm != null)
- {
- try
- {
- mvp = AccessController.doPrivileged(new PrivilegedExceptionAction<MarshalledValuePair>()
- {
- public MarshalledValuePair run() throws Exception
- {
- return new MarshalledValuePair(obj);
- }
- }
- );
- }
- catch(PrivilegedActionException e)
- {
- IOException ioe = new IOException();
- ioe.initCause(e.getException());
- throw ioe;
- }
- }
- else
- {
- mvp = new MarshalledValuePair(obj);
- }
- return mvp;
- }
-
- /**
- * Determine the form of the name to pass to the NamingManager operations.
- * This is supposed to be a context relative name according to the javaodcs
- * for NamingManager, but historically the absolute name of the target
- * context has been passed in.
- *
- * @param env - the env of NamingContext that op was called on
- * @return true if the legacy and technically incorrect absolute name should
- * be used, false if the context relative name should be used.
- */
- private boolean useAbsoluteName(Hashtable env)
- {
- if (env == null)
- return true;
- String useRelativeName = (String) env.get(JNP_USE_RELATIVE_NAME);
- return Boolean.valueOf(useRelativeName) == Boolean.FALSE;
- }
-
- /**
- * Use the NamingManager.getStateToBind to obtain the actual object to bind
- * into jndi.
- * @param obj - the value passed to bind/rebind
- * @param name - the name passed to bind/rebind
- * @param env - the env of NamingContext that bind/rebind was called on
- * @return the object to bind to the naming server
- * @throws NamingException
- */
- private Object getStateToBind(Object obj, Name name, Hashtable env)
- throws NamingException
- {
- if (useAbsoluteName(env))
- name = getAbsoluteName(name);
- return NamingManager.getStateToBind(obj, name, this, env);
- }
-
- /**
- * Use the NamingManager.getObjectInstance to resolve the raw object obtained
- * from the naming server.
- * @param obj - raw value obtained from the naming server
- * @param name - the name passed to the lookup op
- * @param env - the env of NamingContext that the op was called on
- * @return the fully resolved object
- * @throws Exception
- */
- private Object getObjectInstance(Object obj, Name name, Hashtable env)
- throws Exception
- {
- if (useAbsoluteName(env))
- name = getAbsoluteName(name);
- return NamingManager.getObjectInstance(obj, name, this, env);
- }
-
- /**
- * Resolve the final object and wrap any non-NamingException errors in a
- * NamingException with the cause passed as the root cause.
- * @param obj - raw value obtained from the naming server
- * @param name - the name passed to the lookup op
- * @param env - the env of NamingContext that the op was called on
- * @return the fully resolved object
- * @throws NamingException
- */
- private Object getObjectInstanceWrapFailure(Object obj, Name name, Hashtable env)
- throws NamingException
- {
- try
- {
- return getObjectInstance(obj, name, env);
- }
- catch (NamingException e)
- {
- throw e;
- }
- catch (Exception e)
- {
- NamingException ex = new NamingException("Could not dereference object");
- ex.setRootCause(e);
- throw ex;
- }
- }
-
- /**
- * This methods sends a broadcast message on the network and asks and HA-JNDI
- * server to sent it the HA-JNDI stub
- */
- private Naming discoverServer(Hashtable serverEnv) throws NamingException
- {
- boolean trace = log.isTraceEnabled();
- // Check if discovery should be done
- String disableDiscovery = (String) serverEnv.get(JNP_DISABLE_DISCOVERY);
- if (Boolean.valueOf(disableDiscovery) == Boolean.TRUE)
- {
- if (trace)
- log.trace("Skipping discovery due to disable flag");
- return null;
- }
-
- // we first try to discover the server locally
- //
- String partitionName = (String) serverEnv.get(JNP_PARTITION_NAME);
- Naming server = null;
- if (partitionName != null)
- {
- server = getHANamingServerForPartition(partitionName);
- if (server != null)
- return server;
- }
-
- // We next broadcast a HelloWorld datagram (multicast)
- // Any listening server will answer with its IP address:port in another datagram
- // we will then use this to make a standard "lookup"
- //
- MulticastSocket s = null;
- InetAddress iaGroup = null;
- try
- {
- String group = DEFAULT_DISCOVERY_GROUP_ADDRESS;
- int port = DEFAULT_DISCOVERY_GROUP_PORT;
- int timeout = DEFAULT_DISCOVERY_TIMEOUT;
- int ttl = 16;
-
- String discoveryGroup = (String) serverEnv.get(JNP_DISCOVERY_GROUP);
- if (discoveryGroup != null)
- group = discoveryGroup;
-
- String discoveryTTL = (String) serverEnv.get(JNP_DISCOVERY_TTL);
- if(discoveryTTL != null)
- ttl = Integer.parseInt(discoveryTTL);
-
- String discoveryTimeout = (String) serverEnv.get(JNP_DISCOVERY_TIMEOUT);
- if (discoveryTimeout == null)
- {
- // Check the old property name
- discoveryTimeout = (String) serverEnv.get("DISCOVERY_TIMEOUT");
- }
- if (discoveryTimeout != null && !discoveryTimeout.equals(""))
- timeout = Integer.parseInt(discoveryTimeout);
-
- String discoveryGroupPort = (String) serverEnv.get(JNP_DISCOVERY_PORT);
- if (discoveryGroupPort == null)
- {
- // Check the old property name
- discoveryGroupPort = (String) serverEnv.get("DISCOVERY_GROUP");
- }
- if (discoveryGroupPort != null && !discoveryGroupPort.equals(""))
- {
- int colon = discoveryGroupPort.indexOf(':');
- if (colon < 0)
- {
- // No group given, just the port
- try
- {
- port = Integer.parseInt(discoveryGroupPort);
- }
- catch (Exception ex)
- {
- log.warn("Failed to parse port: " + discoveryGroupPort, ex);
- }
- }
- else
- {
- // The old group:port syntax was given
- group = discoveryGroupPort.substring(0, colon);
- String portStr = discoveryGroupPort.substring(colon + 1);
- try
- {
- port = Integer.parseInt(portStr);
- }
- catch (Exception ex)
- {
- log.warn("Failed to parse port: " + portStr, ex);
- }
- }
- }
-
- iaGroup = InetAddress.getByName(group);
- String localAddrStr = (String) serverEnv.get(JNP_LOCAL_ADDRESS);
- String localPortStr = (String) serverEnv.get(JNP_LOCAL_PORT);
- int localPort = 0;
- if (localPortStr != null)
- localPort = Integer.parseInt(localPortStr);
- if (localAddrStr != null)
- {
- InetSocketAddress localAddr = new InetSocketAddress(localAddrStr, localPort);
- s = new MulticastSocket(localAddr);
- }
- else
- {
- s = new MulticastSocket(localPort);
- }
- s.setSoTimeout(timeout);
- s.setTimeToLive(ttl);
- if(log.isTraceEnabled())
- log.trace("TTL on multicast discovery socket is " + ttl);
- s.joinGroup(iaGroup);
- if (trace)
- log.trace("MulticastSocket: " + s);
- DatagramPacket packet;
- // Send a request optionally restricted to a cluster partition
- StringBuffer data = new StringBuffer("GET_ADDRESS");
- if (partitionName != null)
- data.append(":" + partitionName);
- byte[] buf = data.toString().getBytes();
- packet = new DatagramPacket(buf, buf.length, iaGroup, port);
- if (trace)
- log.trace("Sending discovery packet(" + data + ") to: " + iaGroup + ":" + port);
- s.send(packet);
- // Look for a reply
- // IP address + port number = 128.128.128.128:65535 => (12+3) + 1 + (5) = 21
-
- buf = new byte[50];
- packet = new DatagramPacket(buf, buf.length);
- s.receive(packet);
- String myServer = new String(packet.getData()).trim();
- if (trace)
- log.trace("Received answer packet: " + myServer);
- while (myServer != null && myServer.startsWith("GET_ADDRESS"))
- {
- Arrays.fill(buf, (byte) 0);
- packet.setLength(buf.length);
- s.receive(packet);
- byte[] reply = packet.getData();
- myServer = new String(reply).trim();
- if (trace)
- log.trace("Received answer packet: " + myServer);
- }
- String serverHost;
- int serverPort;
-
- int colon = myServer.indexOf(':');
- if (colon >= 0)
- {
- serverHost = myServer.substring(0, colon);
- serverPort = Integer.valueOf(myServer.substring(colon + 1)).intValue();
- server = getServer(serverHost, serverPort, serverEnv);
- }
- return server;
- }
- catch (IOException e)
- {
- if (trace)
- log.trace("Discovery failed", e);
- NamingException ex = new CommunicationException(e.getMessage());
- ex.setRootCause(e);
- throw ex;
- }
- finally
- {
- try
- {
- if (s != null)
- s.leaveGroup(iaGroup);
- }
- catch (Exception ignore)
- {
- }
- try
- {
- if (s != null)
- s.close();
- }
- catch (Exception ignore)
- {
- }
- }
- }
-
- private void checkRef(Hashtable refEnv)
- throws NamingException
- {
- if (naming == null)
- {
- String host = "localhost";
- int port = 1099;
- Exception serverEx = null;
-
- // Locate first available naming service
- String urls = (String) refEnv.get(Context.PROVIDER_URL);
- if (urls != null && urls.length() > 0)
- {
- StringTokenizer tokenizer = new StringTokenizer(urls, ",");
-
- while (naming == null && tokenizer.hasMoreElements())
- {
- String url = tokenizer.nextToken();
- // Parse the url into a host:port form, stripping any protocol
- Name urlAsName = getNameParser("").parse(url);
- String server = parseNameForScheme(urlAsName, null);
- if (server != null)
- url = server;
- int colon = url.indexOf(':');
- if (colon < 0)
- {
- host = url;
- }
- else
- {
- host = url.substring(0, colon).trim();
- try
- {
- port = Integer.parseInt(url.substring(colon + 1).trim());
- }
- catch (Exception ex)
- {
- // Use default;
- }
- }
- try
- {
- // Get server from cache
- naming = getServer(host, port, refEnv);
- }
- catch (Exception e)
- {
- serverEx = e;
- log.debug("Failed to connect to " + host + ":" + port, e);
- }
- }
-
- // If there is still no
- Exception discoveryFailure = null;
- if (naming == null)
- {
- try
- {
- naming = discoverServer(refEnv);
- }
- catch (Exception e)
- {
- discoveryFailure = e;
- if (serverEx == null)
- serverEx = e;
- }
- if (naming == null)
- {
- StringBuffer buffer = new StringBuffer(50);
- buffer.append("Could not obtain connection to any of these urls: ").append(urls);
- if (discoveryFailure != null)
- buffer.append(" and discovery failed with error: ").append(discoveryFailure);
- CommunicationException ce = new CommunicationException(buffer.toString());
- ce.setRootCause(serverEx);
- throw ce;
- }
- }
- }
- else
- {
- // If we are in a clustering scenario, the client code may request a context
- // for a *specific* HA-JNDI service (i.e. linked to a *specific* partition)
- // EVEN if the lookup is done inside a JBoss VM. For example, a JBoss service
- // may do a lookup on a HA-JNDI service running on another host *without*
- // explicitly providing a PROVIDER_URL but simply by providing a JNP_PARTITON_NAME
- // parameter so that dynamic discovery can be used
- //
- String jnpPartitionName = (String) refEnv.get(JNP_PARTITION_NAME);
- if (jnpPartitionName != null)
- {
- // the client is requesting for a specific partition name
- //
- naming = discoverServer(refEnv);
- if (naming == null)
- throw new ConfigurationException
- ("No valid context could be build for jnp.partitionName=" + jnpPartitionName);
- }
- else
- {
- // Use server in same JVM
- naming = localServer;
-
- if (naming == null)
- {
- naming = discoverServer(refEnv);
- if (naming == null)
- // Local, but no local JNDI provider found!
- throw new ConfigurationException("No valid Context.PROVIDER_URL was found");
- }
- }
- }
- }
- }
-
- private Name getAbsoluteName(Name n)
- throws NamingException
- {
- if (n.isEmpty())
- return composeName(n, prefix);
- else if (n.get(0).toString().equals("")) // Absolute name
- return n.getSuffix(1);
- else // Add prefix
- return composeName(n, prefix);
- }
-
- private Hashtable getEnv(Name n)
- throws InvalidNameException
- {
- Hashtable nameEnv = env;
- env.remove(JNP_PARSED_NAME);
- String serverInfo = parseNameForScheme(n, nameEnv);
- if (serverInfo != null)
- {
- // Set hostname:port value for the naming server
- nameEnv = (Hashtable) env.clone();
- nameEnv.put(Context.PROVIDER_URL, serverInfo);
- }
- return nameEnv;
- }
-
- /**
- * JBAS-4574. Check if the given exception is because the server has
- * been restarted while the cached naming stub hasn't been dgc-ed yet.
- * If yes, we will flush out the naming stub from our cache and
- * acquire a new stub. BW.
- *
- * @param e the exception that may be due to a stale stub
- * @param refEnv the naming environment associated with the failed call
- *
- * @return <code>true</code> if <code>e</code> indicates a stale
- * naming stub and we were able to succesfully flush the
- * cache and acquire a new stub; <code>false</code> otherwise.
- */
- private boolean handleStaleNamingStub(Exception e, Hashtable refEnv)
- {
- if (e instanceof NoSuchObjectException
- || e.getCause() instanceof NoSuchObjectException)
- {
- try
- {
- if( log.isTraceEnabled() )
- {
- log.trace("Call failed with NoSuchObjectException, " +
- "flushing server cache and retrying", e);
- }
- naming = null;
- removeServer(refEnv);
-
- checkRef(refEnv);
-
- return true;
- }
- catch (Exception e1)
- {
- // Just log and return false; let caller continue processing
- // the original exception passed in to this method
- log.error("Caught exception flushing server cache and " +
- "re-establish naming after exception " +
- e.getLocalizedMessage(), e1);
- }
- }
- return false;
- }
-
- // Inner classes -------------------------------------------------
-}
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/NamingContext.java (from rev 80561, projects/naming/trunk/jnpserver/src/main/java/org/jnp/interfaces/NamingContext.java)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/NamingContext.java (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/interfaces/NamingContext.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,1840 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jnp.interfaces;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.SerializablePermission;
+import java.lang.ref.WeakReference;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.ReflectPermission;
+import java.net.DatagramPacket;
+import java.net.InetAddress;
+import java.net.MulticastSocket;
+import java.net.Socket;
+import java.net.InetSocketAddress;
+import java.rmi.ConnectException;
+import java.rmi.MarshalledObject;
+import java.rmi.NoSuchObjectException;
+import java.rmi.RemoteException;
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.StringTokenizer;
+import javax.naming.Binding;
+import javax.naming.CannotProceedException;
+import javax.naming.CommunicationException;
+import javax.naming.ConfigurationException;
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.InvalidNameException;
+import javax.naming.LinkRef;
+import javax.naming.Name;
+import javax.naming.NameParser;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.NotContextException;
+import javax.naming.ContextNotEmptyException;
+import javax.naming.Reference;
+import javax.naming.Referenceable;
+import javax.naming.ServiceUnavailableException;
+import javax.naming.event.EventContext;
+import javax.naming.event.NamingListener;
+import javax.naming.spi.NamingManager;
+import javax.naming.spi.ResolveResult;
+import javax.net.SocketFactory;
+
+import org.jboss.logging.Logger;
+
+/**
+ * This class provides the jnp provider Context implementation. It is a Context
+ * interface wrapper for a RMI Naming instance that is obtained from either the
+ * local server instance or by locating the server given by the
+ * Context.PROVIDER_URL value.
+ *
+ * This class also serves as the jnp url resolution context. jnp style urls
+ * passed to the
+ * @author oberg
+ * @author scott.stark at jboss.org
+ * @version $Revision$
+ */
+public class NamingContext
+ implements EventContext, java.io.Serializable
+{
+ // Constants -----------------------------------------------------
+ /**
+ * @since 1.7
+ */
+ static final long serialVersionUID = 8906455608484282128L;
+ /**
+ * The javax.net.SocketFactory impl to use for the bootstrap socket
+ */
+ public static final String JNP_SOCKET_FACTORY = "jnp.socketFactory";
+ /**
+ * The local address to bind the connected bootstrap socket to
+ */
+ public static final String JNP_LOCAL_ADDRESS = "jnp.localAddress";
+ /**
+ * The local port to bind the connected bootstrap socket to
+ */
+ public static final String JNP_LOCAL_PORT = "jnp.localPort";
+ /**
+ * A flag to disable the broadcast discovery queries
+ */
+ public static final String JNP_DISABLE_DISCOVERY = "jnp.disableDiscovery";
+ /**
+ * The cluster partition discovery should be restricted to
+ */
+ public static final String JNP_PARTITION_NAME = "jnp.partitionName";
+ /**
+ * The multicast IP/address to which the discovery query is sent
+ */
+ public static final String JNP_DISCOVERY_GROUP = "jnp.discoveryGroup";
+ /**
+ * The port to which the discovery query is sent
+ */
+ public static final String JNP_DISCOVERY_PORT = "jnp.discoveryPort";
+
+ /** The time-to-live for the multicast discovery packets */
+ public static final String JNP_DISCOVERY_TTL = "jnp.discoveryTTL";
+
+ /**
+ * The time in MS to wait for a discovery query response
+ */
+ public static final String JNP_DISCOVERY_TIMEOUT = "jnp.discoveryTimeout";
+ /**
+ * An internal property added by parseNameForScheme if the input name uses a
+ * url prefix that was removed during cannonicalization. This is needed to
+ * avoid modification of the incoming Name.
+ */
+ public static final String JNP_PARSED_NAME = "jnp.parsedName";
+ /**
+ * A flag indicating the style of names passed to NamingManager method.
+ * True for api expected relative names, false for absolute names as used
+ * historically by the jboss naming implementation.
+ */
+ public static final String JNP_USE_RELATIVE_NAME = "jnp.useRelativeName";
+ /**
+ * An integer that controls the number of connection retry attempts will
+ * be made on the initial connection to the naming server. This only applies
+ * to ConnectException failures. A value <= 1 means that only one attempt
+ * will be made.
+ */
+ public static final String JNP_MAX_RETRIES = "jnp.maxRetries";
+ /**
+ * The Naming instance to use for the root Context creation
+ */
+ public static final String JNP_NAMING_INSTANCE = "jnp.namingInstance";
+ /**
+ * The name to associate with Naming instance to use for the root Context
+ */
+ public static final String JNP_NAMING_INSTANCE_NAME = "jnp.namingInstanceName";
+
+ /**
+ * The default discovery multicast information
+ */
+ public final static String DEFAULT_DISCOVERY_GROUP_ADDRESS = "230.0.0.4";
+ public final static int DEFAULT_DISCOVERY_GROUP_PORT = 1102;
+ public final static int DEFAULT_DISCOVERY_TIMEOUT = 5000;
+
+ /**
+ * An obsolete constant replaced by the JNP_MAX_RETRIES value
+ */
+ public static int MAX_RETRIES = 1;
+ /**
+ * The JBoss logging interface
+ */
+ private static Logger log = Logger.getLogger(NamingContext.class);
+
+ // Static --------------------------------------------------------
+ /** HAJNDI keyed by partition name */
+ private static Hashtable haServers = new Hashtable();
+ private static RuntimePermission GET_HA_NAMING_SERVER = new RuntimePermission("org.jboss.naming.NamingContext.getHANamingServerForPartition");
+ private static RuntimePermission SET_HA_NAMING_SERVER = new RuntimePermission("org.jboss.naming.NamingContext.setHANamingServerForPartition");
+ public static void setHANamingServerForPartition(String partitionName, Naming haServer)
+ {
+ SecurityManager security = System.getSecurityManager();
+ if(security != null)
+ security.checkPermission(SET_HA_NAMING_SERVER);
+ haServers.put(partitionName, haServer);
+ }
+
+ public static void removeHANamingServerForPartition(String partitionName)
+ {
+ SecurityManager security = System.getSecurityManager();
+ if(security != null)
+ security.checkPermission(SET_HA_NAMING_SERVER);
+ haServers.remove(partitionName);
+ }
+
+ public static Naming getHANamingServerForPartition(String partitionName)
+ {
+ SecurityManager security = System.getSecurityManager();
+ if(security != null)
+ security.checkPermission(GET_HA_NAMING_SERVER);
+ return (Naming) haServers.get(partitionName);
+ }
+
+ /**
+ * The jvm local server used for non-transport access to the naming
+ * server
+ * @see #checkRef(Hashtable)
+ * @see {@linkplain LocalOnlyContextFactory}
+ */
+ private static Naming localServer;
+ private static RuntimePermission GET_LOCAL_SERVER = new RuntimePermission("org.jboss.naming.NamingContext.getLocal");
+ private static RuntimePermission SET_LOCAL_SERVER = new RuntimePermission("org.jboss.naming.NamingContext.setLocal");
+
+ // Attributes ----------------------------------------------------
+ Naming naming;
+ Hashtable env;
+ Name prefix;
+
+ NameParser parser = new NamingParser();
+
+ // Static --------------------------------------------------------
+
+ // Cache of naming server stubs
+ // This is a critical optimization in the case where new InitialContext
+ // is performed often. The server stub will be shared between all those
+ // calls, which will improve performance.
+ // Weak references are used so if no contexts use a particular server
+ // it will be removed from the cache.
+ static HashMap cachedServers = new HashMap();
+
+ static void addServer(String name, Naming server)
+ {
+ // Add server to map
+ synchronized (NamingContext.class)
+ {
+ cachedServers.put(name, new WeakReference(server));
+ }
+ }
+
+ static Naming getServer(String host, int port, Hashtable serverEnv)
+ throws NamingException
+ {
+ // Check the server cache for a host:port entry
+ String hostKey = host + ":" + port;
+ WeakReference ref = (WeakReference) cachedServers.get(hostKey);
+ Naming server;
+ if (ref != null)
+ {
+ server = (Naming) ref.get();
+ if (server != null)
+ {
+ // JBAS-4622. Ensure the env for the request has the
+ // hostKey so we can remove the cache entry if there is a failure
+ serverEnv.put("hostKey", hostKey);
+ return server;
+ }
+ }
+
+ // Server not found; add it to cache
+ try
+ {
+ SocketFactory factory = loadSocketFactory(serverEnv);
+ Socket s;
+
+ try
+ {
+ InetAddress localAddr = null;
+ int localPort = 0;
+ String localAddrStr = (String) serverEnv.get(JNP_LOCAL_ADDRESS);
+ String localPortStr = (String) serverEnv.get(JNP_LOCAL_PORT);
+ if (localAddrStr != null)
+ localAddr = InetAddress.getByName(localAddrStr);
+ if (localPortStr != null)
+ localPort = Integer.parseInt(localPortStr);
+ s = factory.createSocket(host, port, localAddr, localPort);
+ }
+ catch (IOException e)
+ {
+ NamingException ex = new ServiceUnavailableException("Failed to connect to server " + hostKey);
+ ex.setRootCause(e);
+ throw ex;
+ }
+
+ // Get stub from naming server
+ BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
+ ObjectInputStream in = new ObjectInputStream(bis);
+ MarshalledObject stub = (MarshalledObject) in.readObject();
+ server = (Naming) stub.get();
+ s.close();
+
+ // Add it to cache
+ addServer(hostKey, server);
+ serverEnv.put("hostKey", hostKey);
+
+ return server;
+ }
+ catch (IOException e)
+ {
+ if(log.isTraceEnabled())
+ log.trace("Failed to retrieve stub from server " + hostKey, e);
+ NamingException ex = new CommunicationException("Failed to retrieve stub from server " + hostKey);
+ ex.setRootCause(e);
+ throw ex;
+ }
+ catch (Exception e)
+ {
+ if(log.isTraceEnabled())
+ log.trace("Failed to connect server " + hostKey, e);
+ NamingException ex = new CommunicationException("Failed to connect to server " + hostKey);
+ ex.setRootCause(e);
+ throw ex;
+ }
+ }
+
+ /**
+ * Create a SocketFactory based on the JNP_SOCKET_FACTORY property in the
+ * given env. If JNP_SOCKET_FACTORY is not specified default to the
+ * TimedSocketFactory.
+ */
+ static SocketFactory loadSocketFactory(Hashtable serverEnv)
+ throws ClassNotFoundException, IllegalAccessException,
+ InstantiationException, InvocationTargetException
+ {
+ SocketFactory factory = null;
+
+ // Get the socket factory classname
+ String socketFactoryName = (String) serverEnv.get(JNP_SOCKET_FACTORY);
+ if (socketFactoryName == null ||
+ socketFactoryName.equals(TimedSocketFactory.class.getName()))
+ {
+ factory = new TimedSocketFactory(serverEnv);
+ return factory;
+ }
+
+ /* Create the socket factory. Look for a ctor that accepts a
+ Hashtable and if not found use the default ctor.
+ */
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ Class factoryClass = loader.loadClass(socketFactoryName);
+ try
+ {
+ Class[] ctorSig = {Hashtable.class};
+ Constructor ctor = factoryClass.getConstructor(ctorSig);
+ Object[] ctorArgs = {serverEnv};
+ factory = (SocketFactory) ctor.newInstance(ctorArgs);
+ }
+ catch (NoSuchMethodException e)
+ {
+ // Use the default ctor
+ factory = (SocketFactory) factoryClass.newInstance();
+ }
+ return factory;
+ }
+
+ static void removeServer(Hashtable serverEnv)
+ {
+ String host = "localhost";
+ int port = 1099;
+
+ // Locate naming service
+ if (serverEnv.get(Context.PROVIDER_URL) != null)
+ {
+ String providerURL = (String) serverEnv.get(Context.PROVIDER_URL);
+
+ StringTokenizer tokenizer = new StringTokenizer(providerURL, ", ");
+ while (tokenizer.hasMoreElements())
+ {
+ String url = tokenizer.nextToken();
+
+ try
+ {
+ // Parse the url into a host:port form, stripping any protocol
+ Name urlAsName = new NamingParser().parse(url);
+ String server = parseNameForScheme(urlAsName, null);
+ if (server != null)
+ url = server;
+ int colon = url.indexOf(':');
+ if (colon < 0)
+ {
+ host = url.trim();
+ }
+ else
+ {
+ host = url.substring(0, colon).trim();
+ try
+ {
+ port = Integer.parseInt(url.substring(colon + 1).trim());
+ }
+ catch (Exception ex)
+ {
+ // Use default;
+ }
+ }
+
+ // Remove server from map
+ synchronized (NamingContext.class)
+ {
+ cachedServers.remove(host + ":" + port);
+ }
+ }
+ catch (NamingException ignored)
+ {
+ }
+ }
+ }
+
+ // JBAS-4622. Always do this.
+ Object hostKey = serverEnv.remove("hostKey");
+ if (hostKey != null)
+ {
+ synchronized (NamingContext.class)
+ {
+ cachedServers.remove(hostKey);
+ }
+ }
+ }
+
+ /**
+ * Called to remove any url scheme atoms and extract the naming service
+ * hostname:port information.
+ * @param n the name component to the parsed. After returning n will have all
+ * scheme related atoms removed.
+ * @return the naming service hostname:port information string if name
+ * contained the host information.
+ */
+ static String parseNameForScheme(Name n, Hashtable nameEnv)
+ throws InvalidNameException
+ {
+ String serverInfo = null;
+ if (n.size() > 0)
+ {
+ String scheme = n.get(0);
+ int schemeLength = 0;
+ if (scheme.startsWith("java:"))
+ schemeLength = 5;
+ else if (scheme.startsWith("jnp:"))
+ schemeLength = 4;
+ else if (scheme.startsWith("jnps:"))
+ schemeLength = 5;
+ else if (scheme.startsWith("jnp-http:"))
+ schemeLength = 9;
+ else if (scheme.startsWith("jnp-https:"))
+ schemeLength = 10;
+ if (schemeLength > 0)
+ {
+ // Make a copy of the name to avoid
+ n = (Name) n.clone();
+ String suffix = scheme.substring(schemeLength);
+ if (suffix.length() == 0)
+ {
+ // Scheme was "url:/..."
+ n.remove(0);
+ if (n.size() > 1 && n.get(0).equals(""))
+ {
+ // Scheme was "url://hostname:port/..."
+ // Get hostname:port value for the naming server
+ serverInfo = n.get(1);
+ n.remove(0);
+ n.remove(0);
+ // If n is a empty atom remove it or else a '/' will result
+ if (n.size() == 1 && n.get(0).length() == 0)
+ n.remove(0);
+ }
+ }
+ else
+ {
+ // Scheme was "url:foo" -> reinsert "foo"
+ n.remove(0);
+ n.add(0, suffix);
+ }
+ if (nameEnv != null)
+ nameEnv.put(JNP_PARSED_NAME, n);
+ }
+ }
+ return serverInfo;
+ }
+
+ public static Naming getLocal()
+ {
+ SecurityManager security = System.getSecurityManager();
+ if(security != null)
+ security.checkPermission(GET_LOCAL_SERVER);
+ return localServer;
+ }
+ public static void setLocal(Naming server)
+ {
+ SecurityManager security = System.getSecurityManager();
+ if(security != null)
+ security.checkPermission(SET_LOCAL_SERVER);
+ localServer = server;
+ }
+
+ // Constructors --------------------------------------------------
+ public NamingContext(Hashtable e, Name baseName, Naming server)
+ throws NamingException
+ {
+ if (baseName == null)
+ this.prefix = parser.parse("");
+ else
+ this.prefix = baseName;
+
+ if (e != null)
+ this.env = (Hashtable) e.clone();
+ else
+ this.env = new Hashtable();
+
+ this.naming = server;
+ }
+
+ // Public --------------------------------------------------------
+ public Naming getNaming()
+ {
+ return this.naming;
+ }
+
+ public void setNaming(Naming server)
+ {
+ this.naming = server;
+ }
+
+ // Context implementation ----------------------------------------
+ public void rebind(String name, Object obj)
+ throws NamingException
+ {
+ rebind(getNameParser(name).parse(name), obj);
+ }
+
+ public void rebind(Name name, Object obj)
+ throws NamingException
+ {
+ Hashtable refEnv = getEnv(name);
+ checkRef(refEnv);
+ Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
+ if (parsedName != null)
+ name = parsedName;
+
+ // Allow state factories to change the stored object
+ obj = getStateToBind(obj, name, refEnv);
+
+ try
+ {
+ String className = null;
+
+ // Referenceable
+ if (obj instanceof Referenceable)
+ obj = ((Referenceable) obj).getReference();
+
+ if (!(obj instanceof Reference))
+ {
+ if( obj != null )
+ className = obj.getClass().getName();
+ obj = createMarshalledValuePair(obj);
+ }
+ else
+ {
+ className = ((Reference) obj).getClassName();
+ }
+ try
+ {
+ naming.rebind(getAbsoluteName(name), obj, className);
+ }
+ catch (RemoteException re)
+ {
+ // Check for JBAS-4574.
+ if (handleStaleNamingStub(re, refEnv))
+ {
+ // try again with new naming stub
+ naming.rebind(getAbsoluteName(name), obj, className);
+ }
+ else
+ {
+ // Not JBAS-4574. Throw exception and let outer logic handle it.
+ throw re;
+ }
+ }
+ }
+ catch (CannotProceedException cpe)
+ {
+ cpe.setEnvironment(refEnv);
+ Context cctx = NamingManager.getContinuationContext(cpe);
+ cctx.rebind(cpe.getRemainingName(), obj);
+ }
+ catch (IOException e)
+ {
+ naming = null;
+ removeServer(refEnv);
+ NamingException ex = new CommunicationException();
+ ex.setRootCause(e);
+ throw ex;
+ }
+ }
+
+ public void bind(String name, Object obj)
+ throws NamingException
+ {
+ bind(getNameParser(name).parse(name), obj);
+ }
+
+ public void bind(Name name, Object obj)
+ throws NamingException
+ {
+ Hashtable refEnv = getEnv(name);
+ checkRef(refEnv);
+ Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
+ if (parsedName != null)
+ name = parsedName;
+
+ // Allow state factories to change the stored object
+ obj = getStateToBind(obj, name, refEnv);
+
+ try
+ {
+ String className = null;
+
+ // Referenceable
+ if (obj instanceof Referenceable)
+ obj = ((Referenceable) obj).getReference();
+
+ if (!(obj instanceof Reference))
+ {
+ if( obj != null )
+ className = obj.getClass().getName();
+
+ // Normal object - serialize using a MarshalledValuePair
+ obj = createMarshalledValuePair(obj);
+ }
+ else
+ {
+ className = ((Reference) obj).getClassName();
+ }
+ name = getAbsoluteName(name);
+
+ try
+ {
+ naming.bind(name, obj, className);
+ }
+ catch (RemoteException re)
+ {
+ // Check for JBAS-4574.
+ if (handleStaleNamingStub(re, refEnv))
+ {
+ // try again with new naming stub
+ naming.bind(name, obj, className);
+ }
+ else
+ {
+ // Not JBAS-4574. Throw exception and let outer logic handle it.
+ throw re;
+ }
+ }
+ }
+ catch (CannotProceedException cpe)
+ {
+ cpe.setEnvironment(refEnv);
+ Context cctx = NamingManager.getContinuationContext(cpe);
+ cctx.bind(cpe.getRemainingName(), obj);
+ }
+ catch (IOException e)
+ {
+ naming = null;
+ removeServer(refEnv);
+ NamingException ex = new CommunicationException();
+ ex.setRootCause(e);
+ throw ex;
+ }
+ }
+
+ public Object lookup(String name)
+ throws NamingException
+ {
+ return lookup(getNameParser(name).parse(name));
+ }
+
+ public Object lookup(Name name)
+ throws NamingException
+ {
+ Hashtable refEnv = getEnv(name);
+ checkRef(refEnv);
+ Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
+ if (parsedName != null)
+ name = parsedName;
+
+ // Empty?
+ if (name.isEmpty())
+ return new NamingContext(refEnv, prefix, naming);
+
+ try
+ {
+ int maxTries = 1;
+ try
+ {
+ String n = (String) refEnv.get(JNP_MAX_RETRIES);
+ if( n != null )
+ maxTries = Integer.parseInt(n);
+ if( maxTries <= 0 )
+ maxTries = 1;
+ }
+ catch(Exception e)
+ {
+ log.debug("Failed to get JNP_MAX_RETRIES, using 1", e);
+ }
+ Name n = getAbsoluteName(name);
+ Object res = null;
+ boolean trace = log.isTraceEnabled();
+ for (int i = 0; i < maxTries; i++)
+ {
+ try
+ {
+ try
+ {
+ res = naming.lookup(n);
+ }
+ catch (RemoteException re)
+ {
+ // Check for JBAS-4574.
+ if (handleStaleNamingStub(re, refEnv))
+ {
+ // try again with new naming stub
+ res = naming.lookup(n);
+ }
+ else
+ {
+ // Not JBAS-4574. Throw exception and let outer logic handle it.
+ throw re;
+ }
+ }
+ // If we got here, we succeeded, so break the loop
+ break;
+ }
+ catch (ConnectException ce)
+ {
+ int retries = maxTries - i - 1;
+ if( trace )
+ log.trace("Connect failed, retry count: "+retries, ce);
+ // We may overload server so sleep and retry
+ if (retries > 0)
+ {
+ try
+ {
+ Thread.sleep(1);
+ }
+ catch (InterruptedException ignored)
+ {
+ }
+ continue;
+ }
+ // Throw the exception to flush the bad server
+ throw ce;
+ }
+ }
+ if (res instanceof MarshalledValuePair)
+ {
+ MarshalledValuePair mvp = (MarshalledValuePair) res;
+ Object storedObj = mvp.get();
+ return getObjectInstanceWrapFailure(storedObj, name, refEnv);
+ }
+ else if (res instanceof MarshalledObject)
+ {
+ MarshalledObject mo = (MarshalledObject) res;
+ return mo.get();
+ }
+ else if (res instanceof Context)
+ {
+ // Add env
+ Enumeration keys = refEnv.keys();
+ while (keys.hasMoreElements())
+ {
+ String key = (String) keys.nextElement();
+ ((Context) res).addToEnvironment(key, refEnv.get(key));
+ }
+ return res;
+ }
+ else if (res instanceof ResolveResult)
+ {
+ // Dereference partial result
+ ResolveResult rr = (ResolveResult) res;
+ Object resolveRes = rr.getResolvedObj();
+ Object context;
+ Object instanceID;
+
+ if (resolveRes instanceof LinkRef)
+ {
+ context = resolveLink(resolveRes, null);
+ instanceID = ((LinkRef) resolveRes).getLinkName();
+ }
+ else
+ {
+ context = getObjectInstanceWrapFailure(resolveRes, name, refEnv);
+ instanceID = context;
+ }
+
+ if ((context instanceof Context) == false)
+ {
+ throw new NotContextException(instanceID + " is not a Context");
+ }
+ Context ncontext = (Context) context;
+ return ncontext.lookup(rr.getRemainingName());
+ }
+ else if (res instanceof LinkRef)
+ {
+ // Dereference link
+ res = resolveLink(res, refEnv);
+ }
+ else if (res instanceof Reference)
+ {
+ // Dereference object
+ res = getObjectInstanceWrapFailure(res, name, refEnv);
+ if (res instanceof LinkRef)
+ res = resolveLink(res, refEnv);
+ }
+
+ return res;
+ }
+ catch (CannotProceedException cpe)
+ {
+ cpe.setEnvironment(refEnv);
+ Context cctx = NamingManager.getContinuationContext(cpe);
+ return cctx.lookup(cpe.getRemainingName());
+ }
+ catch (IOException e)
+ {
+ naming = null;
+ removeServer(refEnv);
+ NamingException ex = new CommunicationException();
+ ex.setRootCause(e);
+ throw ex;
+ }
+ catch (ClassNotFoundException e)
+ {
+ NamingException ex = new CommunicationException();
+ ex.setRootCause(e);
+ throw ex;
+ }
+ }
+
+ public void unbind(String name)
+ throws NamingException
+ {
+ unbind(getNameParser(name).parse(name));
+ }
+
+
+ public void unbind(Name name)
+ throws NamingException
+ {
+ Hashtable refEnv = getEnv(name);
+ checkRef(refEnv);
+ Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
+ if (parsedName != null)
+ name = parsedName;
+
+ try
+ {
+ try
+ {
+ naming.unbind(getAbsoluteName(name));
+ }
+ catch (RemoteException re)
+ {
+ // Check for JBAS-4574.
+ if (handleStaleNamingStub(re, refEnv))
+ {
+ // try again with new naming stub
+ naming.unbind(getAbsoluteName(name));
+ }
+ else
+ {
+ // Not JBAS-4574. Throw exception and let outer logic handle it.
+ throw re;
+ }
+ }
+ }
+ catch (CannotProceedException cpe)
+ {
+ cpe.setEnvironment(refEnv);
+ Context cctx = NamingManager.getContinuationContext(cpe);
+ cctx.unbind(cpe.getRemainingName());
+ }
+ catch (IOException e)
+ {
+ naming = null;
+ removeServer(refEnv);
+ NamingException ex = new CommunicationException();
+ ex.setRootCause(e);
+ throw ex;
+ }
+ }
+
+ public void rename(String oldname, String newname)
+ throws NamingException
+ {
+ rename(getNameParser(oldname).parse(oldname), getNameParser(newname).parse(newname));
+ }
+
+ public void rename(Name oldName, Name newName)
+ throws NamingException
+ {
+ bind(newName, lookup(oldName));
+ unbind(oldName);
+ }
+
+ public NamingEnumeration list(String name)
+ throws NamingException
+ {
+ return list(getNameParser(name).parse(name));
+ }
+
+ public NamingEnumeration list(Name name)
+ throws NamingException
+ {
+ Hashtable refEnv = getEnv(name);
+ checkRef(refEnv);
+ Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
+ if (parsedName != null)
+ name = parsedName;
+
+ try
+ {
+ Collection c = null;
+ try
+ {
+ c = naming.list(getAbsoluteName(name));
+ }
+ catch (RemoteException re)
+ {
+ // Check for JBAS-4574.
+ if (handleStaleNamingStub(re, refEnv))
+ {
+ // try again with new naming stub
+ c = naming.list(getAbsoluteName(name));
+ }
+ else
+ {
+ // Not JBAS-4574. Throw exception and let outer logic handle it.
+ throw re;
+ }
+ }
+ return new NamingEnumerationImpl(c);
+ }
+ catch (CannotProceedException cpe)
+ {
+ cpe.setEnvironment(refEnv);
+ Context cctx = NamingManager.getContinuationContext(cpe);
+ return cctx.list(cpe.getRemainingName());
+ }
+ catch (IOException e)
+ {
+ naming = null;
+ removeServer(refEnv);
+ NamingException ex = new CommunicationException();
+ ex.setRootCause(e);
+ throw ex;
+ }
+ }
+
+ public NamingEnumeration listBindings(String name)
+ throws NamingException
+ {
+ return listBindings(getNameParser(name).parse(name));
+ }
+
+ public NamingEnumeration listBindings(Name name)
+ throws NamingException
+ {
+ Hashtable refEnv = getEnv(name);
+ checkRef(refEnv);
+ Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
+ if (parsedName != null)
+ name = parsedName;
+
+ try
+ {
+ // Get list
+ Collection bindings = null;
+ try
+ {
+ // Get list
+ bindings = naming.listBindings(getAbsoluteName(name));
+ }
+ catch (RemoteException re)
+ {
+ // Check for JBAS-4574.
+ if (handleStaleNamingStub(re, refEnv))
+ {
+ // try again with new naming stub
+ bindings = naming.listBindings(getAbsoluteName(name));
+ }
+ else
+ {
+ // Not JBAS-4574. Throw exception and let outer logic handle it.
+ throw re;
+ }
+ }
+ Collection realBindings = new ArrayList(bindings.size());
+
+ // Convert marshalled objects
+ Iterator i = bindings.iterator();
+ while (i.hasNext())
+ {
+ Binding binding = (Binding) i.next();
+ Object obj = binding.getObject();
+ if (obj instanceof MarshalledValuePair)
+ {
+ try
+ {
+ obj = ((MarshalledValuePair) obj).get();
+ }
+ catch (ClassNotFoundException e)
+ {
+ NamingException ex = new CommunicationException();
+ ex.setRootCause(e);
+ throw ex;
+ }
+ }
+ else if (obj instanceof MarshalledObject)
+ {
+ try
+ {
+ obj = ((MarshalledObject) obj).get();
+ }
+ catch (ClassNotFoundException e)
+ {
+ NamingException ex = new CommunicationException();
+ ex.setRootCause(e);
+ throw ex;
+ }
+ }
+ realBindings.add(new Binding(binding.getName(), binding.getClassName(), obj));
+ }
+
+ // Return transformed list of bindings
+ return new NamingEnumerationImpl(realBindings);
+ }
+ catch (CannotProceedException cpe)
+ {
+ cpe.setEnvironment(refEnv);
+ Context cctx = NamingManager.getContinuationContext(cpe);
+ return cctx.listBindings(cpe.getRemainingName());
+ }
+ catch (IOException e)
+ {
+ naming = null;
+ removeServer(refEnv);
+ NamingException ex = new CommunicationException();
+ ex.setRootCause(e);
+ throw ex;
+ }
+ }
+
+ public String composeName(String name, String prefix)
+ throws NamingException
+ {
+ Name result = composeName(parser.parse(name),
+ parser.parse(prefix));
+ return result.toString();
+ }
+
+ public Name composeName(Name name, Name prefix)
+ throws NamingException
+ {
+ Name result = (Name) (prefix.clone());
+ result.addAll(name);
+ return result;
+ }
+
+ public NameParser getNameParser(String name)
+ throws NamingException
+ {
+ return parser;
+ }
+
+ public NameParser getNameParser(Name name)
+ throws NamingException
+ {
+ return getNameParser(name.toString());
+ }
+
+ public Context createSubcontext(String name)
+ throws NamingException
+ {
+ return createSubcontext(getNameParser(name).parse(name));
+ }
+
+ public Context createSubcontext(Name name)
+ throws NamingException
+ {
+ if (name.size() == 0)
+ throw new InvalidNameException("Cannot pass an empty name to createSubcontext");
+
+ Hashtable refEnv = getEnv(name);
+ checkRef(refEnv);
+ Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
+ if (parsedName != null)
+ name = parsedName;
+
+ try
+ {
+ name = getAbsoluteName(name);
+ try
+ {
+ return naming.createSubcontext(name);
+ }
+ catch (RemoteException re)
+ {
+ // Check for JBAS-4574.
+ if (handleStaleNamingStub(re, refEnv))
+ {
+ // try again with new naming stub
+ return naming.createSubcontext(name);
+ }
+ else
+ {
+ // Not JBAS-4574. Throw exception and let outer logic handle it.
+ throw re;
+ }
+ }
+ }
+ catch (CannotProceedException cpe)
+ {
+ cpe.setEnvironment(refEnv);
+ Context cctx = NamingManager.getContinuationContext(cpe);
+ return cctx.createSubcontext(cpe.getRemainingName());
+ }
+ catch (IOException e)
+ {
+ naming = null;
+ removeServer(refEnv);
+ NamingException ex = new CommunicationException();
+ ex.setRootCause(e);
+ throw ex;
+ }
+ }
+
+ public Object addToEnvironment(String propName, Object propVal)
+ throws NamingException
+ {
+ Object old = env.get(propName);
+ env.put(propName, propVal);
+ return old;
+ }
+
+ public Object removeFromEnvironment(String propName)
+ throws NamingException
+ {
+ return env.remove(propName);
+ }
+
+ public Hashtable getEnvironment()
+ throws NamingException
+ {
+ return env;
+ }
+
+ public void close()
+ throws NamingException
+ {
+ env = null;
+ naming = null;
+ }
+
+ public String getNameInNamespace()
+ throws NamingException
+ {
+ return prefix.toString();
+ }
+
+ public void destroySubcontext(String name)
+ throws NamingException
+ {
+ destroySubcontext(getNameParser(name).parse(name));
+ }
+
+ public void destroySubcontext(Name name)
+ throws NamingException
+ {
+ if (!list(name).hasMore())
+ {
+ unbind(name);
+ }
+ else
+ throw new ContextNotEmptyException();
+ }
+
+ public Object lookupLink(String name)
+ throws NamingException
+ {
+ return lookupLink(getNameParser(name).parse(name));
+ }
+
+ /**
+ * Lookup the object referred to by name but don't dereferrence the final
+ * component. This really just involves returning the raw value returned by
+ * the Naming.lookup() method.
+ * @return the raw object bound under name.
+ */
+ public Object lookupLink(Name name)
+ throws NamingException
+ {
+ Hashtable refEnv = getEnv(name);
+ checkRef(refEnv);
+ Name parsedName = (Name) refEnv.get(JNP_PARSED_NAME);
+ if (parsedName != null)
+ name = parsedName;
+
+ if (name.isEmpty())
+ return lookup(name);
+
+ Object link = null;
+ try
+ {
+ Name n = getAbsoluteName(name);
+ try
+ {
+ link = naming.lookup(n);
+ }
+ catch (RemoteException re)
+ {
+ // Check for JBAS-4574.
+ if (handleStaleNamingStub(re, refEnv))
+ {
+ // try again with new naming stub
+ link = naming.lookup(n);
+ }
+ else
+ {
+ // Not JBAS-4574. Throw exception and let outer logic handle it.
+ throw re;
+ }
+ }
+ if (!(link instanceof LinkRef) && link instanceof Reference)
+ link = getObjectInstance(link, name, null);
+ ;
+ }
+ catch (IOException e)
+ {
+ naming = null;
+ removeServer(refEnv);
+ NamingException ex = new CommunicationException();
+ ex.setRootCause(e);
+ throw ex;
+ }
+ catch (Exception e)
+ {
+ NamingException ex = new NamingException("Could not lookup link");
+ ex.setRemainingName(name);
+ ex.setRootCause(e);
+ throw ex;
+ }
+ return link;
+ }
+
+ // Begin EventContext methods
+ public void addNamingListener(Name target, int scope, NamingListener l)
+ throws NamingException
+ {
+ if((naming instanceof NamingEvents) == false)
+ {
+ throw new UnsupportedOperationException("Naming implementation does not support NamingExt");
+ }
+ NamingEvents next = (NamingEvents) naming;
+ try
+ {
+ next.addNamingListener(this, target, scope, l);
+ }
+ catch (RemoteException e)
+ {
+ CommunicationException ce = new CommunicationException("addNamingListener failed");
+ ce.initCause(e);
+ }
+ }
+
+ public void addNamingListener(String target, int scope, NamingListener l)
+ throws NamingException
+ {
+ Name targetName = parser.parse(target);
+ addNamingListener(targetName, scope, l);
+ }
+
+ public void removeNamingListener(NamingListener l)
+ throws NamingException
+ {
+ if((naming instanceof NamingEvents) == false)
+ {
+ throw new UnsupportedOperationException("Naming implementation does not support NamingExt");
+ }
+ NamingEvents next = (NamingEvents) naming;
+ try
+ {
+ next.removeNamingListener(l);
+ }
+ catch (RemoteException e)
+ {
+ CommunicationException ce = new CommunicationException("removeNamingListener failed");
+ ce.initCause(e);
+ }
+ }
+
+ public boolean targetMustExist()
+ throws NamingException
+ {
+ if((naming instanceof NamingEvents) == false)
+ {
+ throw new UnsupportedOperationException("Naming implementation does not support NamingExt");
+ }
+ NamingEvents next = (NamingEvents) naming;
+ boolean targetMustExist = true;
+ try
+ {
+ targetMustExist = next.targetMustExist();
+ }
+ catch (RemoteException e)
+ {
+ CommunicationException ce = new CommunicationException("removeNamingListener failed");
+ ce.initCause(e);
+ }
+ return targetMustExist;
+ }
+ // End EventContext methods
+
+ protected Object resolveLink(Object res, Hashtable refEnv)
+ throws NamingException
+ {
+ Object linkResult = null;
+ try
+ {
+ LinkRef link = (LinkRef) res;
+ String ref = link.getLinkName();
+ if (ref.startsWith("./"))
+ linkResult = lookup(ref.substring(2));
+ else if (refEnv != null)
+ linkResult = new InitialContext(refEnv).lookup(ref);
+ else
+ linkResult = new InitialContext().lookup(ref);
+ }
+ catch (Exception e)
+ {
+ NamingException ex = new NamingException("Could not dereference object");
+ ex.setRootCause(e);
+ throw ex;
+ }
+ return linkResult;
+ }
+
+ // Private -------------------------------------------------------
+
+ /**
+ * Isolate the creation of the MarshalledValuePair in a privileged block
+ * when running under a security manager so the following permissions can
+ * be isolated from the caller:
+ * RuntimePermission("createClassLoader")
+ ReflectPermission("suppressAccessChecks")
+ SerializablePermission("enableSubstitution")
+ @return the MarshalledValuePair wrapping obj
+ */
+ private Object createMarshalledValuePair(final Object obj)
+ throws IOException
+ {
+ MarshalledValuePair mvp = null;
+ SecurityManager sm = System.getSecurityManager();
+ if(sm != null)
+ {
+ try
+ {
+ mvp = AccessController.doPrivileged(new PrivilegedExceptionAction<MarshalledValuePair>()
+ {
+ public MarshalledValuePair run() throws Exception
+ {
+ return new MarshalledValuePair(obj);
+ }
+ }
+ );
+ }
+ catch(PrivilegedActionException e)
+ {
+ IOException ioe = new IOException();
+ ioe.initCause(e.getException());
+ throw ioe;
+ }
+ }
+ else
+ {
+ mvp = new MarshalledValuePair(obj);
+ }
+ return mvp;
+ }
+
+ /**
+ * Determine the form of the name to pass to the NamingManager operations.
+ * This is supposed to be a context relative name according to the javaodcs
+ * for NamingManager, but historically the absolute name of the target
+ * context has been passed in.
+ *
+ * @param env - the env of NamingContext that op was called on
+ * @return true if the legacy and technically incorrect absolute name should
+ * be used, false if the context relative name should be used.
+ */
+ private boolean useAbsoluteName(Hashtable env)
+ {
+ if (env == null)
+ return true;
+ String useRelativeName = (String) env.get(JNP_USE_RELATIVE_NAME);
+ return Boolean.valueOf(useRelativeName) == Boolean.FALSE;
+ }
+
+ /**
+ * Use the NamingManager.getStateToBind to obtain the actual object to bind
+ * into jndi.
+ * @param obj - the value passed to bind/rebind
+ * @param name - the name passed to bind/rebind
+ * @param env - the env of NamingContext that bind/rebind was called on
+ * @return the object to bind to the naming server
+ * @throws NamingException
+ */
+ private Object getStateToBind(Object obj, Name name, Hashtable env)
+ throws NamingException
+ {
+ if (useAbsoluteName(env))
+ name = getAbsoluteName(name);
+ return NamingManager.getStateToBind(obj, name, this, env);
+ }
+
+ /**
+ * Use the NamingManager.getObjectInstance to resolve the raw object obtained
+ * from the naming server.
+ * @param obj - raw value obtained from the naming server
+ * @param name - the name passed to the lookup op
+ * @param env - the env of NamingContext that the op was called on
+ * @return the fully resolved object
+ * @throws Exception
+ */
+ private Object getObjectInstance(Object obj, Name name, Hashtable env)
+ throws Exception
+ {
+ if (useAbsoluteName(env))
+ name = getAbsoluteName(name);
+ return NamingManager.getObjectInstance(obj, name, this, env);
+ }
+
+ /**
+ * Resolve the final object and wrap any non-NamingException errors in a
+ * NamingException with the cause passed as the root cause.
+ * @param obj - raw value obtained from the naming server
+ * @param name - the name passed to the lookup op
+ * @param env - the env of NamingContext that the op was called on
+ * @return the fully resolved object
+ * @throws NamingException
+ */
+ private Object getObjectInstanceWrapFailure(Object obj, Name name, Hashtable env)
+ throws NamingException
+ {
+ try
+ {
+ return getObjectInstance(obj, name, env);
+ }
+ catch (NamingException e)
+ {
+ throw e;
+ }
+ catch (Exception e)
+ {
+ NamingException ex = new NamingException("Could not dereference object");
+ ex.setRootCause(e);
+ throw ex;
+ }
+ }
+
+ /**
+ * This methods sends a broadcast message on the network and asks and HA-JNDI
+ * server to sent it the HA-JNDI stub
+ */
+ private Naming discoverServer(Hashtable serverEnv) throws NamingException
+ {
+ boolean trace = log.isTraceEnabled();
+ // Check if discovery should be done
+ String disableDiscovery = (String) serverEnv.get(JNP_DISABLE_DISCOVERY);
+ if (Boolean.valueOf(disableDiscovery) == Boolean.TRUE)
+ {
+ if (trace)
+ log.trace("Skipping discovery due to disable flag");
+ return null;
+ }
+
+ // we first try to discover the server locally
+ //
+ String partitionName = (String) serverEnv.get(JNP_PARTITION_NAME);
+ Naming server = null;
+ if (partitionName != null)
+ {
+ server = getHANamingServerForPartition(partitionName);
+ if (server != null)
+ return server;
+ }
+
+ // We next broadcast a HelloWorld datagram (multicast)
+ // Any listening server will answer with its IP address:port in another datagram
+ // we will then use this to make a standard "lookup"
+ //
+ MulticastSocket s = null;
+ InetAddress iaGroup = null;
+ try
+ {
+ String group = DEFAULT_DISCOVERY_GROUP_ADDRESS;
+ int port = DEFAULT_DISCOVERY_GROUP_PORT;
+ int timeout = DEFAULT_DISCOVERY_TIMEOUT;
+ int ttl = 16;
+
+ String discoveryGroup = (String) serverEnv.get(JNP_DISCOVERY_GROUP);
+ if (discoveryGroup != null)
+ group = discoveryGroup;
+
+ String discoveryTTL = (String) serverEnv.get(JNP_DISCOVERY_TTL);
+ if(discoveryTTL != null)
+ ttl = Integer.parseInt(discoveryTTL);
+
+ String discoveryTimeout = (String) serverEnv.get(JNP_DISCOVERY_TIMEOUT);
+ if (discoveryTimeout == null)
+ {
+ // Check the old property name
+ discoveryTimeout = (String) serverEnv.get("DISCOVERY_TIMEOUT");
+ }
+ if (discoveryTimeout != null && !discoveryTimeout.equals(""))
+ timeout = Integer.parseInt(discoveryTimeout);
+
+ String discoveryGroupPort = (String) serverEnv.get(JNP_DISCOVERY_PORT);
+ if (discoveryGroupPort == null)
+ {
+ // Check the old property name
+ discoveryGroupPort = (String) serverEnv.get("DISCOVERY_GROUP");
+ }
+ if (discoveryGroupPort != null && !discoveryGroupPort.equals(""))
+ {
+ int colon = discoveryGroupPort.indexOf(':');
+ if (colon < 0)
+ {
+ // No group given, just the port
+ try
+ {
+ port = Integer.parseInt(discoveryGroupPort);
+ }
+ catch (Exception ex)
+ {
+ log.warn("Failed to parse port: " + discoveryGroupPort, ex);
+ }
+ }
+ else
+ {
+ // The old group:port syntax was given
+ group = discoveryGroupPort.substring(0, colon);
+ String portStr = discoveryGroupPort.substring(colon + 1);
+ try
+ {
+ port = Integer.parseInt(portStr);
+ }
+ catch (Exception ex)
+ {
+ log.warn("Failed to parse port: " + portStr, ex);
+ }
+ }
+ }
+
+ iaGroup = InetAddress.getByName(group);
+ String localAddrStr = (String) serverEnv.get(JNP_LOCAL_ADDRESS);
+ String localPortStr = (String) serverEnv.get(JNP_LOCAL_PORT);
+ int localPort = 0;
+ if (localPortStr != null)
+ localPort = Integer.parseInt(localPortStr);
+ if (localAddrStr != null)
+ {
+ InetSocketAddress localAddr = new InetSocketAddress(localAddrStr, localPort);
+ s = new MulticastSocket(localAddr);
+ }
+ else
+ {
+ s = new MulticastSocket(localPort);
+ }
+ s.setSoTimeout(timeout);
+ s.setTimeToLive(ttl);
+ if(log.isTraceEnabled())
+ log.trace("TTL on multicast discovery socket is " + ttl);
+ s.joinGroup(iaGroup);
+ if (trace)
+ log.trace("MulticastSocket: " + s);
+ DatagramPacket packet;
+ // Send a request optionally restricted to a cluster partition
+ StringBuffer data = new StringBuffer("GET_ADDRESS");
+ if (partitionName != null)
+ data.append(":" + partitionName);
+ byte[] buf = data.toString().getBytes();
+ packet = new DatagramPacket(buf, buf.length, iaGroup, port);
+ if (trace)
+ log.trace("Sending discovery packet(" + data + ") to: " + iaGroup + ":" + port);
+ s.send(packet);
+ // Look for a reply
+ // IP address + port number = 128.128.128.128:65535 => (12+3) + 1 + (5) = 21
+
+ buf = new byte[50];
+ packet = new DatagramPacket(buf, buf.length);
+ s.receive(packet);
+ String myServer = new String(packet.getData()).trim();
+ if (trace)
+ log.trace("Received answer packet: " + myServer);
+ while (myServer != null && myServer.startsWith("GET_ADDRESS"))
+ {
+ Arrays.fill(buf, (byte) 0);
+ packet.setLength(buf.length);
+ s.receive(packet);
+ byte[] reply = packet.getData();
+ myServer = new String(reply).trim();
+ if (trace)
+ log.trace("Received answer packet: " + myServer);
+ }
+ String serverHost;
+ int serverPort;
+
+ int colon = myServer.indexOf(':');
+ if (colon >= 0)
+ {
+ serverHost = myServer.substring(0, colon);
+ serverPort = Integer.valueOf(myServer.substring(colon + 1)).intValue();
+ server = getServer(serverHost, serverPort, serverEnv);
+ }
+ return server;
+ }
+ catch (IOException e)
+ {
+ if (trace)
+ log.trace("Discovery failed", e);
+ NamingException ex = new CommunicationException(e.getMessage());
+ ex.setRootCause(e);
+ throw ex;
+ }
+ finally
+ {
+ try
+ {
+ if (s != null)
+ s.leaveGroup(iaGroup);
+ }
+ catch (Exception ignore)
+ {
+ }
+ try
+ {
+ if (s != null)
+ s.close();
+ }
+ catch (Exception ignore)
+ {
+ }
+ }
+ }
+
+ private void checkRef(Hashtable refEnv)
+ throws NamingException
+ {
+ if (naming == null)
+ {
+ String host = "localhost";
+ int port = 1099;
+ Exception serverEx = null;
+
+ // Locate first available naming service
+ String urls = (String) refEnv.get(Context.PROVIDER_URL);
+ if (urls != null && urls.length() > 0)
+ {
+ StringTokenizer tokenizer = new StringTokenizer(urls, ",");
+
+ while (naming == null && tokenizer.hasMoreElements())
+ {
+ String url = tokenizer.nextToken();
+ // Parse the url into a host:port form, stripping any protocol
+ Name urlAsName = getNameParser("").parse(url);
+ String server = parseNameForScheme(urlAsName, null);
+ if (server != null)
+ url = server;
+ int colon = url.indexOf(':');
+ if (colon < 0)
+ {
+ host = url;
+ }
+ else
+ {
+ host = url.substring(0, colon).trim();
+ try
+ {
+ port = Integer.parseInt(url.substring(colon + 1).trim());
+ }
+ catch (Exception ex)
+ {
+ // Use default;
+ }
+ }
+ try
+ {
+ // Get server from cache
+ naming = getServer(host, port, refEnv);
+ }
+ catch (Exception e)
+ {
+ serverEx = e;
+ log.debug("Failed to connect to " + host + ":" + port, e);
+ }
+ }
+
+ // If there is still no
+ Exception discoveryFailure = null;
+ if (naming == null)
+ {
+ try
+ {
+ naming = discoverServer(refEnv);
+ }
+ catch (Exception e)
+ {
+ discoveryFailure = e;
+ if (serverEx == null)
+ serverEx = e;
+ }
+ if (naming == null)
+ {
+ StringBuffer buffer = new StringBuffer(50);
+ buffer.append("Could not obtain connection to any of these urls: ").append(urls);
+ if (discoveryFailure != null)
+ buffer.append(" and discovery failed with error: ").append(discoveryFailure);
+ CommunicationException ce = new CommunicationException(buffer.toString());
+ ce.setRootCause(serverEx);
+ throw ce;
+ }
+ }
+ }
+ else
+ {
+ // If we are in a clustering scenario, the client code may request a context
+ // for a *specific* HA-JNDI service (i.e. linked to a *specific* partition)
+ // EVEN if the lookup is done inside a JBoss VM. For example, a JBoss service
+ // may do a lookup on a HA-JNDI service running on another host *without*
+ // explicitly providing a PROVIDER_URL but simply by providing a JNP_PARTITON_NAME
+ // parameter so that dynamic discovery can be used
+ //
+ String jnpPartitionName = (String) refEnv.get(JNP_PARTITION_NAME);
+ if (jnpPartitionName != null)
+ {
+ // the client is requesting for a specific partition name
+ //
+ naming = discoverServer(refEnv);
+ if (naming == null)
+ throw new ConfigurationException
+ ("No valid context could be build for jnp.partitionName=" + jnpPartitionName);
+ }
+ else
+ {
+ // Use server in same JVM
+ naming = localServer;
+
+ if (naming == null)
+ {
+ naming = discoverServer(refEnv);
+ if (naming == null)
+ // Local, but no local JNDI provider found!
+ throw new ConfigurationException("No valid Context.PROVIDER_URL was found");
+ }
+ }
+ }
+ }
+ }
+
+ private Name getAbsoluteName(Name n)
+ throws NamingException
+ {
+ if (n.isEmpty())
+ return composeName(n, prefix);
+ else if (n.get(0).toString().equals("")) // Absolute name
+ return n.getSuffix(1);
+ else // Add prefix
+ return composeName(n, prefix);
+ }
+
+ private Hashtable getEnv(Name n)
+ throws InvalidNameException
+ {
+ Hashtable nameEnv = env;
+ env.remove(JNP_PARSED_NAME);
+ String serverInfo = parseNameForScheme(n, nameEnv);
+ if (serverInfo != null)
+ {
+ // Set hostname:port value for the naming server
+ nameEnv = (Hashtable) env.clone();
+ nameEnv.put(Context.PROVIDER_URL, serverInfo);
+ }
+ return nameEnv;
+ }
+
+ /**
+ * JBAS-4574. Check if the given exception is because the server has
+ * been restarted while the cached naming stub hasn't been dgc-ed yet.
+ * If yes, we will flush out the naming stub from our cache and
+ * acquire a new stub. BW.
+ *
+ * @param e the exception that may be due to a stale stub
+ * @param refEnv the naming environment associated with the failed call
+ *
+ * @return <code>true</code> if <code>e</code> indicates a stale
+ * naming stub and we were able to succesfully flush the
+ * cache and acquire a new stub; <code>false</code> otherwise.
+ */
+ private boolean handleStaleNamingStub(Exception e, Hashtable refEnv)
+ {
+ if (e instanceof NoSuchObjectException
+ || e.getCause() instanceof NoSuchObjectException)
+ {
+ try
+ {
+ if( log.isTraceEnabled() )
+ {
+ log.trace("Call failed with NoSuchObjectException, " +
+ "flushing server cache and retrying", e);
+ }
+ naming = null;
+ removeServer(refEnv);
+
+ checkRef(refEnv);
+
+ return true;
+ }
+ catch (Exception e1)
+ {
+ // Just log and return false; let caller continue processing
+ // the original exception passed in to this method
+ log.error("Caught exception flushing server cache and " +
+ "re-establish naming after exception " +
+ e.getLocalizedMessage(), e1);
+ }
+ }
+ return false;
+ }
+
+ // Inner classes -------------------------------------------------
+}
Deleted: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/Main.java
===================================================================
--- projects/naming/trunk/jnpserver/src/main/java/org/jnp/server/Main.java 2008-11-05 04:14:24 UTC (rev 80546)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/Main.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -1,627 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2006, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jnp.server;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectOutputStream;
-import java.io.OutputStream;
-import java.lang.reflect.Method;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import java.rmi.MarshalledObject;
-import java.rmi.Remote;
-import java.rmi.server.RMIClientSocketFactory;
-import java.rmi.server.RMIServerSocketFactory;
-import java.rmi.server.UnicastRemoteObject;
-import java.util.concurrent.Executor;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import javax.net.ServerSocketFactory;
-
-import org.jboss.logging.Logger;
-import org.jboss.net.sockets.DefaultSocketFactory;
-import org.jboss.util.threadpool.ThreadPool;
-import org.jnp.interfaces.MarshalledValuePair;
-import org.jnp.interfaces.Naming;
-
-/**
- * A main() entry point for running the jnp naming service implementation as
- * a standalone process.
- *
- * @author Rickard Oberg
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-public class Main implements MainMBean
-{
- // Constants -----------------------------------------------------
-
- // Attributes ----------------------------------------------------
- /** The Naming interface server implementation */
- protected NamingBean theServer;
- protected MarshalledObject serverStub;
- protected boolean isStubExported;
- /** The jnp server socket through which the NamingServer stub is vended */
- protected ServerSocket serverSocket;
- /** An optional custom client socket factory */
- protected RMIClientSocketFactory clientSocketFactory;
- /** An optional custom server socket factory */
- protected RMIServerSocketFactory serverSocketFactory;
- /** An optional custom server socket factory */
- protected ServerSocketFactory jnpServerSocketFactory;
- /** The class name of the optional custom client socket factory */
- protected String clientSocketFactoryName;
- /** The class name of the optional custom server socket factory */
- protected String serverSocketFactoryName;
- /** The class name of the optional custom JNP server socket factory */
- protected String jnpServerSocketFactoryName;
- /** The interface to bind to for the lookup socket. This is useful for
- * multi-homed hosts that want control over which interfaces accept
- * connections */
- protected InetAddress bindAddress;
- /** The interface to bind to for the Naming RMI server */
- protected InetAddress rmiBindAddress;
- /** Should the java.rmi.server.hostname property to rmiBindAddress */
- private boolean enableRmiServerHostname;
- /** The serverSocket listen queue depth */
- protected int backlog = 50;
- /** The jnp protocol listening port. The default is 1099, the same as
- the RMI registry default port. */
- protected int port = 1099;
- /** The RMI port on which the Naming implementation will be exported. The
- default is 0 which means use any available port. */
- protected int rmiPort = 0;
- /** A flag indicating if theServer will be set as the NamingContext.setLocal value */
- protected boolean InstallGlobalService = true;
- /** A flag indicating if theServer will try to use the NamingContext.setLocal value */
- protected boolean UseGlobalService = true;
- protected Logger log;
- /** The thread pool used to handle jnp stub lookup requests */
- private Executor lookupExector;
-
- // Static --------------------------------------------------------
- public static void main(String[] args)
- throws Exception
- {
- new Main().start();
- }
-
- // Constructors --------------------------------------------------
- public Main()
- {
- this("org.jboss.naming.Naming");
- }
- public Main(String categoryName)
- {
- // Load properties from properties file
- try
- {
- ClassLoader loader = getClass().getClassLoader();
- InputStream is = loader.getResourceAsStream("jnp.properties");
- System.getProperties().load(is);
- }
- catch (Exception e)
- {
- // Ignore
- }
-
- // Set configuration from the system properties
- setPort(Integer.getInteger("jnp.port",getPort()).intValue());
- setRmiPort(Integer.getInteger("jnp.rmiPort",getRmiPort()).intValue());
- log = Logger.getLogger(categoryName);
- log.debug("isTraceEnabled: "+log.isTraceEnabled());
- }
-
- // Public --------------------------------------------------------
- public NamingBean getNamingInfo()
- {
- return theServer;
- }
- /**
- * Set the NamingBean/Naming implementation
- * @param info
- */
- public void setNamingInfo(NamingBean info)
- {
- this.theServer = info;
- }
-
- @Deprecated
- public void setLookupPool(ThreadPool lookupPool)
- {
- this.lookupExector = new ThreadPoolToExecutor(lookupPool);
- }
-
- public Executor getLookupExector()
- {
- return lookupExector;
- }
- /**
- * Set the Executor to use for bootstrap socket lookup handling. Note
- * that this must support at least 2 thread to avoid hanging the AcceptHandler
- * accept loop.
- * @param lookupExector - An Executor that supports at least 2 threads
- */
- public void setLookupExector(Executor lookupExector)
- {
- this.lookupExector = lookupExector;
- }
-
- /** Get the call by value flag for jndi lookups.
- *
- * @return true if all lookups are unmarshalled using the caller's TCL,
- * false if in VM lookups return the value by reference.
- */
- public boolean getCallByValue()
- {
- return MarshalledValuePair.getEnableCallByReference() == false;
- }
- /** Set the call by value flag for jndi lookups.
- *
- * @param flag - true if all lookups are unmarshalled using the caller's TCL,
- * false if in VM lookups return the value by reference.
- */
- public void setCallByValue(boolean flag)
- {
- boolean callByValue = ! flag;
- MarshalledValuePair.setEnableCallByReference(callByValue);
- }
-
- public Object getNamingProxy(Object proxy)
- throws Exception
- {
- return serverStub.get();
- }
- public void setNamingProxy(Object proxy)
- throws IOException
- {
- serverStub = new MarshalledObject(proxy);
- }
-
- public void setRmiPort(int p)
- {
- rmiPort = p;
- }
- public int getRmiPort()
- {
- return rmiPort;
- }
-
- public void setPort(int p)
- {
- port = p;
- }
- public int getPort()
- {
- return port;
- }
-
- public String getBindAddress()
- {
- String address = null;
- if( bindAddress != null )
- address = bindAddress.getHostAddress();
- return address;
- }
- public void setBindAddress(String host) throws UnknownHostException
- {
- if( host == null || host.length() == 0 )
- bindAddress = null;
- else
- bindAddress = InetAddress.getByName(host);
- }
-
- public String getRmiBindAddress()
- {
- String address = null;
- if( rmiBindAddress != null )
- address = rmiBindAddress.getHostAddress();
- return address;
- }
- public void setRmiBindAddress(String host) throws UnknownHostException
- {
- if( host == null || host.length() == 0 )
- rmiBindAddress = null;
- else
- rmiBindAddress = InetAddress.getByName(host);
- }
-
-
- public boolean isEnableRmiServerHostname()
- {
- return enableRmiServerHostname;
- }
- public void setEnableRmiServerHostname(boolean enableRmiServerHostname)
- {
- this.enableRmiServerHostname = enableRmiServerHostname;
- }
-
- public int getBacklog()
- {
- return backlog;
- }
- public void setBacklog(int backlog)
- {
- if( backlog <= 0 )
- backlog = 50;
- this.backlog = backlog;
- }
-
- public boolean getInstallGlobalService()
- {
- return InstallGlobalService;
- }
- public void setInstallGlobalService(boolean flag)
- {
- this.InstallGlobalService = flag;
- }
- public boolean getUseGlobalService()
- {
- return UseGlobalService;
- }
- public void setUseGlobalService(boolean flag)
- {
- this.UseGlobalService = flag;
- }
-
- public String getClientSocketFactory()
- {
- return clientSocketFactoryName;
- }
- public void setClientSocketFactory(String factoryClassName)
- throws ClassNotFoundException, InstantiationException, IllegalAccessException
- {
- this.clientSocketFactoryName = factoryClassName;
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- Class<?> clazz = loader.loadClass(clientSocketFactoryName);
- clientSocketFactory = (RMIClientSocketFactory) clazz.newInstance();
- }
-
- public RMIClientSocketFactory getClientSocketFactoryBean()
- {
- return clientSocketFactory;
- }
- public void setClientSocketFactoryBean(RMIClientSocketFactory factory)
- {
- this.clientSocketFactory = factory;
- }
-
- public String getServerSocketFactory()
- {
- return serverSocketFactoryName;
- }
- public void setServerSocketFactory(String factoryClassName)
- throws ClassNotFoundException, InstantiationException, IllegalAccessException
- {
- this.serverSocketFactoryName = factoryClassName;
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- Class<?> clazz = loader.loadClass(serverSocketFactoryName);
- serverSocketFactory = (RMIServerSocketFactory) clazz.newInstance();
- }
-
- public RMIServerSocketFactory getServerSocketFactoryBean()
- {
- return serverSocketFactory;
- }
- public void setServerSocketFactoryBean(RMIServerSocketFactory factory)
- {
- this.serverSocketFactory = factory;
- }
-
- public String getJNPServerSocketFactory()
- {
- return jnpServerSocketFactoryName;
- }
- public void setJNPServerSocketFactory(String factoryClassName)
- throws ClassNotFoundException, InstantiationException, IllegalAccessException
- {
- this.jnpServerSocketFactoryName = factoryClassName;
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- Class<?> clazz = loader.loadClass(jnpServerSocketFactoryName);
- jnpServerSocketFactory = (ServerSocketFactory) clazz.newInstance();
- }
-
- public ServerSocketFactory getJNPServerSocketFactoryBean()
- {
- return jnpServerSocketFactory;
- }
- public void setJNPServerSocketFactoryBean(ServerSocketFactory factory)
- {
- this.jnpServerSocketFactory = factory;
- }
-
- /**
- * Access the
- */
- public Naming getNamingInstance()
- {
- return theServer.getNamingInstance();
- }
-
- public void start()
- throws Exception
- {
- log.debug("Begin start");
- // Set the java.rmi.server.hostname to the bind address if not set
- if(rmiBindAddress != null && System.getProperty("java.rmi.server.hostname") == null)
- System.setProperty("java.rmi.server.hostname", rmiBindAddress.getHostAddress());
-
- // Initialize the custom socket factories with any bind address
- initCustomSocketFactories();
- /* Only export server RMI interface and setup the listening socket if
- the port is >= 0 and an external proxy has not been installed.
- A value < 0 indicates no socket based access
- */
- if( this.serverStub == null && port >= 0 )
- {
- initJnpInvoker();
- }
- // Only bring up the bootstrap listener if there is a naming proxy
- if( this.serverStub != null )
- {
- initBootstrapListener();
- }
- log.debug("End start");
- }
-
- public void stop()
- {
- try
- {
- // Stop listener and unexport the RMI object
- if( serverSocket != null )
- {
- ServerSocket s = serverSocket;
- serverSocket = null;
- s.close();
- }
- if( isStubExported == true )
- UnicastRemoteObject.unexportObject(theServer.getNamingInstance(), false);
- }
- catch (Exception e)
- {
- log.error("Exception during shutdown", e);
- }
- }
-
- /** This code should be moved to a seperate invoker in the org.jboss.naming
- *package.
- */
- protected void initJnpInvoker() throws IOException
- {
- log.debug("Creating NamingServer stub, theServer="+theServer
- +",rmiPort="+rmiPort
- +",clientSocketFactory="+clientSocketFactory
- +",serverSocketFactory="+serverSocketFactory);
- Naming instance = getNamingInstance();
- Remote stub = UnicastRemoteObject.exportObject(instance,
- rmiPort, clientSocketFactory, serverSocketFactory);
- log.debug("NamingServer stub: "+stub);
- serverStub = new MarshalledObject(stub);
- isStubExported = true;
- }
-
- /** Bring up the bootstrap lookup port for obtaining the naming service
- * proxy
- */
- protected void initBootstrapListener()
- {
- // Start listener
- try
- {
- // Get the default ServerSocketFactory is one was not specified
- if( jnpServerSocketFactory == null )
- jnpServerSocketFactory = ServerSocketFactory.getDefault();
- serverSocket = jnpServerSocketFactory.createServerSocket(port, backlog, bindAddress);
- // If an anonymous port was specified get the actual port used
- if( port == 0 )
- port = serverSocket.getLocalPort();
- String msg = "JNDI bootstrap JNP=" + bindAddress + ":" + port
- + ", RMI=" + bindAddress + ":" + rmiPort
- + ", backlog="+backlog;
-
- if (clientSocketFactory == null)
- msg+= ", no client SocketFactory";
- else
- msg+= ", Client SocketFactory="+clientSocketFactory.toString();
-
- if (serverSocketFactory == null)
- msg+= ", no server SocketFactory";
- else
- msg+= ", Server SocketFactory="+serverSocketFactory.toString();
-
- log.debug(msg);
- }
- catch (IOException e)
- {
- log.error("Could not start on port " + port, e);
- }
-
- if( lookupExector == null )
- {
- log.debug("Using default newFixedThreadPool(2)");
- lookupExector = Executors.newFixedThreadPool(2, BootstrapThreadFactory.getInstance());
- }
- AcceptHandler handler = new AcceptHandler();
- lookupExector.execute(handler);
- }
-
- /**
- * Init the clientSocketFactory, serverSocketFactory using the bind address.
- */
- protected void initCustomSocketFactories()
- {
- // Use either the rmiBindAddress or bindAddress for the RMI service
- InetAddress addr = rmiBindAddress != null ? rmiBindAddress : bindAddress;
-
- if( clientSocketFactory != null && addr != null )
- {
- // See if the client socket supports setBindAddress(String)
- try
- {
- Class<?> csfClass = clientSocketFactory.getClass();
- Class<?>[] parameterTypes = {String.class};
- Method m = csfClass.getMethod("setBindAddress", parameterTypes);
- Object[] args = {addr.getHostAddress()};
- m.invoke(clientSocketFactory, args);
- }
- catch (NoSuchMethodException e)
- {
- log.warn("Socket factory does not support setBindAddress(String)");
- // Go with default address
- }
- catch (Exception e)
- {
- log.warn("Failed to setBindAddress="+addr+" on socket factory", e);
- // Go with default address
- }
- }
-
- try
- {
- if (serverSocketFactory == null)
- serverSocketFactory = new DefaultSocketFactory(addr);
- else
- {
- if (addr != null)
- {
- // See if the server socket supports setBindAddress(String)
- try
- {
- Class<?> ssfClass = serverSocketFactory.getClass();
- Class<?>[] parameterTypes = {String.class};
- Method m = ssfClass.getMethod("setBindAddress", parameterTypes);
- Object[] args = {addr.getHostAddress()};
- m.invoke(serverSocketFactory, args);
- }
- catch (NoSuchMethodException e)
- {
- log.warn("Socket factory does not support setBindAddress(String)");
- // Go with default address
- }
- catch (Exception e)
- {
- log.warn("Failed to setBindAddress="+addr+" on socket factory", e);
- // Go with default address
- }
- }
- }
- }
- catch (Exception e)
- {
- log.error("operation failed", e);
- serverSocketFactory = null;
- }
- }
-
- private class AcceptHandler implements Runnable
- {
- public void run()
- {
- boolean trace = log.isTraceEnabled();
- while( serverSocket != null )
- {
- Socket socket = null;
- // Accept a connection
- try
- {
- if( trace )
- log.trace("Enter accept on: "+serverSocket);
- socket = serverSocket.accept();
- if( trace )
- log.trace("Accepted bootstrap client: "+socket);
- BootstrapRequestHandler handler = new BootstrapRequestHandler(socket);
- lookupExector.execute(handler);
- }
- catch (IOException e)
- {
- // Stopped by normal means
- if (serverSocket == null)
- return;
- log.error("Naming accept handler stopping", e);
- }
- catch(Throwable e)
- {
- log.error("Unexpected exception during accept", e);
- }
- }
- }
- }
-
- private class BootstrapRequestHandler implements Runnable
- {
- private Socket socket;
- BootstrapRequestHandler(Socket socket)
- {
- this.socket = socket;
- }
- public void run()
- {
- // Return the naming server stub
- try
- {
- if(log.isTraceEnabled())
- log.trace("BootstrapRequestHandler.run start");
- OutputStream os = socket.getOutputStream();
- ObjectOutputStream out = new ObjectOutputStream(os);
- out.writeObject(serverStub);
- out.close();
- if(log.isTraceEnabled())
- log.trace("BootstrapRequestHandler.run end");
- }
- catch (IOException ex)
- {
- log.debug("Error writing response to " + socket.getInetAddress(), ex);
- }
- finally
- {
- try
- {
- socket.close();
- } catch (IOException e)
- {
- }
- }
- }
- }
- private static class BootstrapThreadFactory implements ThreadFactory
- {
- private static final AtomicInteger tnumber = new AtomicInteger(1);
- static BootstrapThreadFactory instance;
- static synchronized ThreadFactory getInstance()
- {
- if(instance == null)
- instance = new BootstrapThreadFactory();
- return instance;
- }
- public Thread newThread(Runnable r)
- {
- Thread t = new Thread(r, "Naming Bootstrap#"+tnumber.getAndIncrement());
- return t;
- }
- }
-}
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/Main.java (from rev 80562, projects/naming/trunk/jnpserver/src/main/java/org/jnp/server/Main.java)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/Main.java (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/Main.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,627 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jnp.server;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.UnknownHostException;
+import java.rmi.MarshalledObject;
+import java.rmi.Remote;
+import java.rmi.server.RMIClientSocketFactory;
+import java.rmi.server.RMIServerSocketFactory;
+import java.rmi.server.UnicastRemoteObject;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.net.ServerSocketFactory;
+
+import org.jboss.logging.Logger;
+import org.jboss.net.sockets.DefaultSocketFactory;
+import org.jboss.util.threadpool.ThreadPool;
+import org.jnp.interfaces.MarshalledValuePair;
+import org.jnp.interfaces.Naming;
+
+/**
+ * A main() entry point for running the jnp naming service implementation as
+ * a standalone process.
+ *
+ * @author Rickard Oberg
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public class Main implements MainMBean
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+ /** The Naming interface server implementation */
+ protected NamingBean theServer;
+ protected MarshalledObject serverStub;
+ protected boolean isStubExported;
+ /** The jnp server socket through which the NamingServer stub is vended */
+ protected ServerSocket serverSocket;
+ /** An optional custom client socket factory */
+ protected RMIClientSocketFactory clientSocketFactory;
+ /** An optional custom server socket factory */
+ protected RMIServerSocketFactory serverSocketFactory;
+ /** An optional custom server socket factory */
+ protected ServerSocketFactory jnpServerSocketFactory;
+ /** The class name of the optional custom client socket factory */
+ protected String clientSocketFactoryName;
+ /** The class name of the optional custom server socket factory */
+ protected String serverSocketFactoryName;
+ /** The class name of the optional custom JNP server socket factory */
+ protected String jnpServerSocketFactoryName;
+ /** The interface to bind to for the lookup socket. This is useful for
+ * multi-homed hosts that want control over which interfaces accept
+ * connections */
+ protected InetAddress bindAddress;
+ /** The interface to bind to for the Naming RMI server */
+ protected InetAddress rmiBindAddress;
+ /** Should the java.rmi.server.hostname property to rmiBindAddress */
+ private boolean enableRmiServerHostname;
+ /** The serverSocket listen queue depth */
+ protected int backlog = 50;
+ /** The jnp protocol listening port. The default is 1099, the same as
+ the RMI registry default port. */
+ protected int port = 1099;
+ /** The RMI port on which the Naming implementation will be exported. The
+ default is 0 which means use any available port. */
+ protected int rmiPort = 0;
+ /** A flag indicating if theServer will be set as the NamingContext.setLocal value */
+ protected boolean InstallGlobalService = true;
+ /** A flag indicating if theServer will try to use the NamingContext.setLocal value */
+ protected boolean UseGlobalService = true;
+ protected Logger log;
+ /** The thread pool used to handle jnp stub lookup requests */
+ private Executor lookupExector;
+
+ // Static --------------------------------------------------------
+ public static void main(String[] args)
+ throws Exception
+ {
+ new Main().start();
+ }
+
+ // Constructors --------------------------------------------------
+ public Main()
+ {
+ this("org.jboss.naming.Naming");
+ }
+ public Main(String categoryName)
+ {
+ // Load properties from properties file
+ try
+ {
+ ClassLoader loader = getClass().getClassLoader();
+ InputStream is = loader.getResourceAsStream("jnp.properties");
+ System.getProperties().load(is);
+ }
+ catch (Exception e)
+ {
+ // Ignore
+ }
+
+ // Set configuration from the system properties
+ setPort(Integer.getInteger("jnp.port",getPort()).intValue());
+ setRmiPort(Integer.getInteger("jnp.rmiPort",getRmiPort()).intValue());
+ log = Logger.getLogger(categoryName);
+ log.debug("isTraceEnabled: "+log.isTraceEnabled());
+ }
+
+ // Public --------------------------------------------------------
+ public NamingBean getNamingInfo()
+ {
+ return theServer;
+ }
+ /**
+ * Set the NamingBean/Naming implementation
+ * @param info
+ */
+ public void setNamingInfo(NamingBean info)
+ {
+ this.theServer = info;
+ }
+
+ @Deprecated
+ public void setLookupPool(ThreadPool lookupPool)
+ {
+ this.lookupExector = new ThreadPoolToExecutor(lookupPool);
+ }
+
+ public Executor getLookupExector()
+ {
+ return lookupExector;
+ }
+ /**
+ * Set the Executor to use for bootstrap socket lookup handling. Note
+ * that this must support at least 2 thread to avoid hanging the AcceptHandler
+ * accept loop.
+ * @param lookupExector - An Executor that supports at least 2 threads
+ */
+ public void setLookupExector(Executor lookupExector)
+ {
+ this.lookupExector = lookupExector;
+ }
+
+ /** Get the call by value flag for jndi lookups.
+ *
+ * @return true if all lookups are unmarshalled using the caller's TCL,
+ * false if in VM lookups return the value by reference.
+ */
+ public boolean getCallByValue()
+ {
+ return MarshalledValuePair.getEnableCallByReference() == false;
+ }
+ /** Set the call by value flag for jndi lookups.
+ *
+ * @param flag - true if all lookups are unmarshalled using the caller's TCL,
+ * false if in VM lookups return the value by reference.
+ */
+ public void setCallByValue(boolean flag)
+ {
+ boolean callByValue = ! flag;
+ MarshalledValuePair.setEnableCallByReference(callByValue);
+ }
+
+ public Object getNamingProxy()
+ throws Exception
+ {
+ return serverStub.get();
+ }
+ public void setNamingProxy(Object proxy)
+ throws IOException
+ {
+ serverStub = new MarshalledObject(proxy);
+ }
+
+ public void setRmiPort(int p)
+ {
+ rmiPort = p;
+ }
+ public int getRmiPort()
+ {
+ return rmiPort;
+ }
+
+ public void setPort(int p)
+ {
+ port = p;
+ }
+ public int getPort()
+ {
+ return port;
+ }
+
+ public String getBindAddress()
+ {
+ String address = null;
+ if( bindAddress != null )
+ address = bindAddress.getHostAddress();
+ return address;
+ }
+ public void setBindAddress(String host) throws UnknownHostException
+ {
+ if( host == null || host.length() == 0 )
+ bindAddress = null;
+ else
+ bindAddress = InetAddress.getByName(host);
+ }
+
+ public String getRmiBindAddress()
+ {
+ String address = null;
+ if( rmiBindAddress != null )
+ address = rmiBindAddress.getHostAddress();
+ return address;
+ }
+ public void setRmiBindAddress(String host) throws UnknownHostException
+ {
+ if( host == null || host.length() == 0 )
+ rmiBindAddress = null;
+ else
+ rmiBindAddress = InetAddress.getByName(host);
+ }
+
+
+ public boolean isEnableRmiServerHostname()
+ {
+ return enableRmiServerHostname;
+ }
+ public void setEnableRmiServerHostname(boolean enableRmiServerHostname)
+ {
+ this.enableRmiServerHostname = enableRmiServerHostname;
+ }
+
+ public int getBacklog()
+ {
+ return backlog;
+ }
+ public void setBacklog(int backlog)
+ {
+ if( backlog <= 0 )
+ backlog = 50;
+ this.backlog = backlog;
+ }
+
+ public boolean getInstallGlobalService()
+ {
+ return InstallGlobalService;
+ }
+ public void setInstallGlobalService(boolean flag)
+ {
+ this.InstallGlobalService = flag;
+ }
+ public boolean getUseGlobalService()
+ {
+ return UseGlobalService;
+ }
+ public void setUseGlobalService(boolean flag)
+ {
+ this.UseGlobalService = flag;
+ }
+
+ public String getClientSocketFactory()
+ {
+ return clientSocketFactoryName;
+ }
+ public void setClientSocketFactory(String factoryClassName)
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException
+ {
+ this.clientSocketFactoryName = factoryClassName;
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ Class<?> clazz = loader.loadClass(clientSocketFactoryName);
+ clientSocketFactory = (RMIClientSocketFactory) clazz.newInstance();
+ }
+
+ public RMIClientSocketFactory getClientSocketFactoryBean()
+ {
+ return clientSocketFactory;
+ }
+ public void setClientSocketFactoryBean(RMIClientSocketFactory factory)
+ {
+ this.clientSocketFactory = factory;
+ }
+
+ public String getServerSocketFactory()
+ {
+ return serverSocketFactoryName;
+ }
+ public void setServerSocketFactory(String factoryClassName)
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException
+ {
+ this.serverSocketFactoryName = factoryClassName;
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ Class<?> clazz = loader.loadClass(serverSocketFactoryName);
+ serverSocketFactory = (RMIServerSocketFactory) clazz.newInstance();
+ }
+
+ public RMIServerSocketFactory getServerSocketFactoryBean()
+ {
+ return serverSocketFactory;
+ }
+ public void setServerSocketFactoryBean(RMIServerSocketFactory factory)
+ {
+ this.serverSocketFactory = factory;
+ }
+
+ public String getJNPServerSocketFactory()
+ {
+ return jnpServerSocketFactoryName;
+ }
+ public void setJNPServerSocketFactory(String factoryClassName)
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException
+ {
+ this.jnpServerSocketFactoryName = factoryClassName;
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ Class<?> clazz = loader.loadClass(jnpServerSocketFactoryName);
+ jnpServerSocketFactory = (ServerSocketFactory) clazz.newInstance();
+ }
+
+ public ServerSocketFactory getJNPServerSocketFactoryBean()
+ {
+ return jnpServerSocketFactory;
+ }
+ public void setJNPServerSocketFactoryBean(ServerSocketFactory factory)
+ {
+ this.jnpServerSocketFactory = factory;
+ }
+
+ /**
+ * Access the
+ */
+ public Naming getNamingInstance()
+ {
+ return theServer.getNamingInstance();
+ }
+
+ public void start()
+ throws Exception
+ {
+ log.debug("Begin start");
+ // Set the java.rmi.server.hostname to the bind address if not set
+ if(rmiBindAddress != null && System.getProperty("java.rmi.server.hostname") == null)
+ System.setProperty("java.rmi.server.hostname", rmiBindAddress.getHostAddress());
+
+ // Initialize the custom socket factories with any bind address
+ initCustomSocketFactories();
+ /* Only export server RMI interface and setup the listening socket if
+ the port is >= 0 and an external proxy has not been installed.
+ A value < 0 indicates no socket based access
+ */
+ if( this.serverStub == null && port >= 0 )
+ {
+ initJnpInvoker();
+ }
+ // Only bring up the bootstrap listener if there is a naming proxy
+ if( this.serverStub != null )
+ {
+ initBootstrapListener();
+ }
+ log.debug("End start");
+ }
+
+ public void stop()
+ {
+ try
+ {
+ // Stop listener and unexport the RMI object
+ if( serverSocket != null )
+ {
+ ServerSocket s = serverSocket;
+ serverSocket = null;
+ s.close();
+ }
+ if( isStubExported == true )
+ UnicastRemoteObject.unexportObject(theServer.getNamingInstance(), false);
+ }
+ catch (Exception e)
+ {
+ log.error("Exception during shutdown", e);
+ }
+ }
+
+ /** This code should be moved to a seperate invoker in the org.jboss.naming
+ *package.
+ */
+ protected void initJnpInvoker() throws IOException
+ {
+ log.debug("Creating NamingServer stub, theServer="+theServer
+ +",rmiPort="+rmiPort
+ +",clientSocketFactory="+clientSocketFactory
+ +",serverSocketFactory="+serverSocketFactory);
+ Naming instance = getNamingInstance();
+ Remote stub = UnicastRemoteObject.exportObject(instance,
+ rmiPort, clientSocketFactory, serverSocketFactory);
+ log.debug("NamingServer stub: "+stub);
+ serverStub = new MarshalledObject(stub);
+ isStubExported = true;
+ }
+
+ /** Bring up the bootstrap lookup port for obtaining the naming service
+ * proxy
+ */
+ protected void initBootstrapListener()
+ {
+ // Start listener
+ try
+ {
+ // Get the default ServerSocketFactory is one was not specified
+ if( jnpServerSocketFactory == null )
+ jnpServerSocketFactory = ServerSocketFactory.getDefault();
+ serverSocket = jnpServerSocketFactory.createServerSocket(port, backlog, bindAddress);
+ // If an anonymous port was specified get the actual port used
+ if( port == 0 )
+ port = serverSocket.getLocalPort();
+ String msg = "JNDI bootstrap JNP=" + bindAddress + ":" + port
+ + ", RMI=" + bindAddress + ":" + rmiPort
+ + ", backlog="+backlog;
+
+ if (clientSocketFactory == null)
+ msg+= ", no client SocketFactory";
+ else
+ msg+= ", Client SocketFactory="+clientSocketFactory.toString();
+
+ if (serverSocketFactory == null)
+ msg+= ", no server SocketFactory";
+ else
+ msg+= ", Server SocketFactory="+serverSocketFactory.toString();
+
+ log.debug(msg);
+ }
+ catch (IOException e)
+ {
+ log.error("Could not start on port " + port, e);
+ }
+
+ if( lookupExector == null )
+ {
+ log.debug("Using default newFixedThreadPool(2)");
+ lookupExector = Executors.newFixedThreadPool(2, BootstrapThreadFactory.getInstance());
+ }
+ AcceptHandler handler = new AcceptHandler();
+ lookupExector.execute(handler);
+ }
+
+ /**
+ * Init the clientSocketFactory, serverSocketFactory using the bind address.
+ */
+ protected void initCustomSocketFactories()
+ {
+ // Use either the rmiBindAddress or bindAddress for the RMI service
+ InetAddress addr = rmiBindAddress != null ? rmiBindAddress : bindAddress;
+
+ if( clientSocketFactory != null && addr != null )
+ {
+ // See if the client socket supports setBindAddress(String)
+ try
+ {
+ Class<?> csfClass = clientSocketFactory.getClass();
+ Class<?>[] parameterTypes = {String.class};
+ Method m = csfClass.getMethod("setBindAddress", parameterTypes);
+ Object[] args = {addr.getHostAddress()};
+ m.invoke(clientSocketFactory, args);
+ }
+ catch (NoSuchMethodException e)
+ {
+ log.warn("Socket factory does not support setBindAddress(String)");
+ // Go with default address
+ }
+ catch (Exception e)
+ {
+ log.warn("Failed to setBindAddress="+addr+" on socket factory", e);
+ // Go with default address
+ }
+ }
+
+ try
+ {
+ if (serverSocketFactory == null)
+ serverSocketFactory = new DefaultSocketFactory(addr);
+ else
+ {
+ if (addr != null)
+ {
+ // See if the server socket supports setBindAddress(String)
+ try
+ {
+ Class<?> ssfClass = serverSocketFactory.getClass();
+ Class<?>[] parameterTypes = {String.class};
+ Method m = ssfClass.getMethod("setBindAddress", parameterTypes);
+ Object[] args = {addr.getHostAddress()};
+ m.invoke(serverSocketFactory, args);
+ }
+ catch (NoSuchMethodException e)
+ {
+ log.warn("Socket factory does not support setBindAddress(String)");
+ // Go with default address
+ }
+ catch (Exception e)
+ {
+ log.warn("Failed to setBindAddress="+addr+" on socket factory", e);
+ // Go with default address
+ }
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ log.error("operation failed", e);
+ serverSocketFactory = null;
+ }
+ }
+
+ private class AcceptHandler implements Runnable
+ {
+ public void run()
+ {
+ boolean trace = log.isTraceEnabled();
+ while( serverSocket != null )
+ {
+ Socket socket = null;
+ // Accept a connection
+ try
+ {
+ if( trace )
+ log.trace("Enter accept on: "+serverSocket);
+ socket = serverSocket.accept();
+ if( trace )
+ log.trace("Accepted bootstrap client: "+socket);
+ BootstrapRequestHandler handler = new BootstrapRequestHandler(socket);
+ lookupExector.execute(handler);
+ }
+ catch (IOException e)
+ {
+ // Stopped by normal means
+ if (serverSocket == null)
+ return;
+ log.error("Naming accept handler stopping", e);
+ }
+ catch(Throwable e)
+ {
+ log.error("Unexpected exception during accept", e);
+ }
+ }
+ }
+ }
+
+ private class BootstrapRequestHandler implements Runnable
+ {
+ private Socket socket;
+ BootstrapRequestHandler(Socket socket)
+ {
+ this.socket = socket;
+ }
+ public void run()
+ {
+ // Return the naming server stub
+ try
+ {
+ if(log.isTraceEnabled())
+ log.trace("BootstrapRequestHandler.run start");
+ OutputStream os = socket.getOutputStream();
+ ObjectOutputStream out = new ObjectOutputStream(os);
+ out.writeObject(serverStub);
+ out.close();
+ if(log.isTraceEnabled())
+ log.trace("BootstrapRequestHandler.run end");
+ }
+ catch (IOException ex)
+ {
+ log.debug("Error writing response to " + socket.getInetAddress(), ex);
+ }
+ finally
+ {
+ try
+ {
+ socket.close();
+ } catch (IOException e)
+ {
+ }
+ }
+ }
+ }
+ private static class BootstrapThreadFactory implements ThreadFactory
+ {
+ private static final AtomicInteger tnumber = new AtomicInteger(1);
+ static BootstrapThreadFactory instance;
+ static synchronized ThreadFactory getInstance()
+ {
+ if(instance == null)
+ instance = new BootstrapThreadFactory();
+ return instance;
+ }
+ public Thread newThread(Runnable r)
+ {
+ Thread t = new Thread(r, "Naming Bootstrap#"+tnumber.getAndIncrement());
+ return t;
+ }
+ }
+}
Deleted: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/MainMBean.java
===================================================================
--- projects/naming/trunk/jnpserver/src/main/java/org/jnp/server/MainMBean.java 2008-11-05 04:14:24 UTC (rev 80546)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/MainMBean.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -1,128 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2006, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jnp.server;
-
-import java.io.IOException;
-import java.net.UnknownHostException;
-import java.rmi.server.RMIClientSocketFactory;
-import java.rmi.server.RMIServerSocketFactory;
-
-import javax.net.ServerSocketFactory;
-
-/**
- * The Mbean interface for the jnp provider server.
- *
- * @author Rickard Oberg
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-public interface MainMBean extends NamingBean
-{
- // Attributes ---------------------------------------------------
-
- void setRmiPort(int port);
- int getRmiPort();
-
- void setPort(int port);
- int getPort();
-
- void setBindAddress(String host) throws UnknownHostException;
- String getBindAddress();
-
- void setRmiBindAddress(String host) throws UnknownHostException;
- String getRmiBindAddress();
-
- void setBacklog(int backlog);
- int getBacklog();
-
- public NamingBean getNamingInfo();
- /**
- * Set the NamingBean/Naming implementation
- * @param info
- */
- public void setNamingInfo(NamingBean info);
-
- /**
- * Get the call by value flag for jndi lookups.
- * @return true if all lookups are unmarshalled using the caller's TCL, false if in VM lookups return the value by reference. */
- boolean getCallByValue() ;
-
- /**
- * Set the call by value flag for jndi lookups.
- * @param flag - true if all lookups are unmarshalled using the caller's TCL, false if in VM lookups return the value by reference. */
- void setCallByValue(boolean flag) ;
-
- /** Whether the MainMBean's Naming server will be installed as the NamingContext.setLocal global value */
- void setInstallGlobalService(boolean flag);
- boolean getInstallGlobalService();
-
- /** Get the UseGlobalService which defines whether the MainMBean's
- * Naming server will initialized from the existing NamingContext.setLocal
- * global value.
- *
- * @return true if this should try to use VM global naming service, false otherwise
- */
- public boolean getUseGlobalService();
- /** Set the UseGlobalService which defines whether the MainMBean's
- * Naming server will initialized from the existing NamingContext.setLocal global
- * value. This allows one to export multiple servers via different transports
- * and still share the same underlying naming service.
- *
- * @return true if this should try to use VM global naming service, false otherwise
- */
- public void setUseGlobalService(boolean flag);
-
- /** The RMIClientSocketFactory implementation class */
- void setClientSocketFactory(String factoryClassName)
- throws ClassNotFoundException, InstantiationException, IllegalAccessException;
- String getClientSocketFactory();
- /** The RMIClientSocketFactory bean */
- public RMIClientSocketFactory getClientSocketFactoryBean();
- public void setClientSocketFactoryBean(RMIClientSocketFactory factory);
-
- /** The RMIServerSocketFactory implementation class */
- void setServerSocketFactory(String factoryClassName)
- throws ClassNotFoundException, InstantiationException, IllegalAccessException;
- String getServerSocketFactory();
- /** The RMIServerSocketFactory bean */
- public RMIServerSocketFactory getServerSocketFactoryBean();
- public void setServerSocketFactoryBean(RMIServerSocketFactory factory);
-
- /** The JNPServerSocketFactory implementation class */
- ServerSocketFactory getJNPServerSocketFactoryBean();
- void setJNPServerSocketFactoryBean(ServerSocketFactory factory);
- public String getJNPServerSocketFactory();
- void setJNPServerSocketFactory(String factoryClassName)
- throws ClassNotFoundException, InstantiationException, IllegalAccessException;
-
- public Object getNamingProxy(Object proxy)
- throws Exception;
- public void setNamingProxy(Object proxy)
- throws IOException;
-
- // Operations ----------------------------------------------------
-
- public void start() throws Exception;
-
- public void stop() throws Exception;
-
-}
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/MainMBean.java (from rev 80562, projects/naming/trunk/jnpserver/src/main/java/org/jnp/server/MainMBean.java)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/MainMBean.java (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/MainMBean.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,128 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jnp.server;
+
+import java.io.IOException;
+import java.net.UnknownHostException;
+import java.rmi.server.RMIClientSocketFactory;
+import java.rmi.server.RMIServerSocketFactory;
+
+import javax.net.ServerSocketFactory;
+
+/**
+ * The Mbean interface for the jnp provider server.
+ *
+ * @author Rickard Oberg
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public interface MainMBean extends NamingBean
+{
+ // Attributes ---------------------------------------------------
+
+ void setRmiPort(int port);
+ int getRmiPort();
+
+ void setPort(int port);
+ int getPort();
+
+ void setBindAddress(String host) throws UnknownHostException;
+ String getBindAddress();
+
+ void setRmiBindAddress(String host) throws UnknownHostException;
+ String getRmiBindAddress();
+
+ void setBacklog(int backlog);
+ int getBacklog();
+
+ public NamingBean getNamingInfo();
+ /**
+ * Set the NamingBean/Naming implementation
+ * @param info
+ */
+ public void setNamingInfo(NamingBean info);
+
+ /**
+ * Get the call by value flag for jndi lookups.
+ * @return true if all lookups are unmarshalled using the caller's TCL, false if in VM lookups return the value by reference. */
+ boolean getCallByValue() ;
+
+ /**
+ * Set the call by value flag for jndi lookups.
+ * @param flag - true if all lookups are unmarshalled using the caller's TCL, false if in VM lookups return the value by reference. */
+ void setCallByValue(boolean flag) ;
+
+ /** Whether the MainMBean's Naming server will be installed as the NamingContext.setLocal global value */
+ void setInstallGlobalService(boolean flag);
+ boolean getInstallGlobalService();
+
+ /** Get the UseGlobalService which defines whether the MainMBean's
+ * Naming server will initialized from the existing NamingContext.setLocal
+ * global value.
+ *
+ * @return true if this should try to use VM global naming service, false otherwise
+ */
+ public boolean getUseGlobalService();
+ /** Set the UseGlobalService which defines whether the MainMBean's
+ * Naming server will initialized from the existing NamingContext.setLocal global
+ * value. This allows one to export multiple servers via different transports
+ * and still share the same underlying naming service.
+ *
+ * @return true if this should try to use VM global naming service, false otherwise
+ */
+ public void setUseGlobalService(boolean flag);
+
+ /** The RMIClientSocketFactory implementation class */
+ void setClientSocketFactory(String factoryClassName)
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException;
+ String getClientSocketFactory();
+ /** The RMIClientSocketFactory bean */
+ public RMIClientSocketFactory getClientSocketFactoryBean();
+ public void setClientSocketFactoryBean(RMIClientSocketFactory factory);
+
+ /** The RMIServerSocketFactory implementation class */
+ void setServerSocketFactory(String factoryClassName)
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException;
+ String getServerSocketFactory();
+ /** The RMIServerSocketFactory bean */
+ public RMIServerSocketFactory getServerSocketFactoryBean();
+ public void setServerSocketFactoryBean(RMIServerSocketFactory factory);
+
+ /** The JNPServerSocketFactory implementation class */
+ ServerSocketFactory getJNPServerSocketFactoryBean();
+ void setJNPServerSocketFactoryBean(ServerSocketFactory factory);
+ public String getJNPServerSocketFactory();
+ void setJNPServerSocketFactory(String factoryClassName)
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException;
+
+ public Object getNamingProxy()
+ throws Exception;
+ public void setNamingProxy(Object proxy)
+ throws IOException;
+
+ // Operations ----------------------------------------------------
+
+ public void start() throws Exception;
+
+ public void stop() throws Exception;
+
+}
Deleted: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingBeanImpl.java
===================================================================
--- projects/naming/trunk/jnpserver/src/main/java/org/jnp/server/NamingBeanImpl.java 2008-11-05 04:14:24 UTC (rev 80546)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingBeanImpl.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -1,186 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2006, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jnp.server;
-
-import java.util.Hashtable;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.RefAddr;
-import javax.naming.Reference;
-import javax.naming.StringRefAddr;
-
-import org.jboss.logging.Logger;
-import org.jboss.naming.ENCFactory;
-import org.jnp.interfaces.Naming;
-import org.jnp.interfaces.NamingContext;
-
-/**
- * A naming pojo that wraps the Naming server implementation. This is
- * a refactoring of the legacy org.jnp.server.Main into a
- *
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-public class NamingBeanImpl
- implements NamingBean
-{
- private static Logger log = Logger.getLogger(NamingBeanImpl.class);
- // Attributes ----------------------------------------------------
- /** The Naming interface server implementation */
- protected Naming theServer;
- /** A flag indicating if theServer will be set as the NamingContext.setLocal value */
- protected boolean InstallGlobalService = true;
- /** A flag indicating if theServer will try to use the NamingContext.setLocal value */
- protected boolean UseGlobalService = true;
- /** The plugin for the manager which dispatches EventContext events to listeners */
- private EventMgr eventMgr;
-
- // Static --------------------------------------------------------
- public static void main(String[] args)
- throws Exception
- {
- new Main().start();
- }
-
- // Constructors --------------------------------------------------
- public NamingBeanImpl()
- {
- }
-
- // Public --------------------------------------------------------
- public Naming getNamingInstance()
- {
- return theServer;
- }
-
- public boolean getInstallGlobalService()
- {
- return InstallGlobalService;
- }
- public void setInstallGlobalService(boolean flag)
- {
- this.InstallGlobalService = flag;
- }
- public boolean getUseGlobalService()
- {
- return UseGlobalService;
- }
- public void setUseGlobalService(boolean flag)
- {
- this.UseGlobalService = flag;
- }
-
- public EventMgr getEventMgr()
- {
- return eventMgr;
- }
- public void setEventMgr(EventMgr eventMgr)
- {
- this.eventMgr = eventMgr;
- }
-
- /**
- * Util method for possible override.
- *
- * @return new naming instance
- * @throws Exception for any error
- */
- protected Naming createServer() throws Exception
- {
- return new NamingServer(null, null, eventMgr);
- }
-
- /**
- *
- * @throws Exception
- */
- public void start()
- throws Exception
- {
- // Create the local naming service instance if it does not exist
- if( theServer == null )
- {
- // See if we should try to reuse the current local server
- if( UseGlobalService == true )
- theServer = NamingContext.getLocal();
- // If not, or there is no server create one
- if( theServer == null )
- theServer = createServer();
- else
- {
- // We need to wrap the server to allow exporting it
- NamingServerWrapper wrapper = new NamingServerWrapper(theServer);
- theServer = wrapper;
- }
- log.debug("Using NamingServer: "+theServer);
- if( InstallGlobalService == true )
- {
- // Set local server reference
- NamingContext.setLocal(theServer);
- log.debug("Installed global NamingServer: "+theServer);
- }
- }
-
- /* Create a default InitialContext and dump out its env to show what properties
- were used in its creation. If we find a Context.PROVIDER_URL property
- issue a warning as this means JNDI lookups are going through RMI.
- */
- InitialContext iniCtx = new InitialContext();
- Hashtable<?,?> env = iniCtx.getEnvironment();
- log.debug("InitialContext Environment: ");
- Object providerURL = null;
- for (Object key : env.keySet())
- {
- Object value = env.get(key);
- String type = value == null ? "" : value.getClass().getName();
- log.debug("key="+key+", value("+type+")="+value);
- if( key.equals(Context.PROVIDER_URL) )
- providerURL = value;
- }
- // Warn if there was a Context.PROVIDER_URL
- if( providerURL != null )
- log.warn("Context.PROVIDER_URL in server jndi.properties, url="+providerURL);
-
- /* Bind an ObjectFactory to "java:comp" so that "java:comp/env" lookups
- produce a unique context for each thread contexxt ClassLoader that
- performs the lookup.
- */
- ClassLoader topLoader = Thread.currentThread().getContextClassLoader();
- ENCFactory.setTopClassLoader(topLoader);
- RefAddr refAddr = new StringRefAddr("nns", "ENC");
- Reference envRef = new Reference("javax.namingMain.Context", refAddr, ENCFactory.class.getName(), null);
- Context ctx = (Context)iniCtx.lookup("java:");
- ctx.rebind("comp", envRef);
- ctx.close();
- iniCtx.close();
- }
-
- /**
- * Clear the NamingContext local server if its our theSever value
- */
- public void stop()
- {
- if(NamingContext.getLocal() == theServer)
- NamingContext.setLocal(null);
- }
-}
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingBeanImpl.java (from rev 80561, projects/naming/trunk/jnpserver/src/main/java/org/jnp/server/NamingBeanImpl.java)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingBeanImpl.java (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingBeanImpl.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,197 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jnp.server;
+
+import java.util.Hashtable;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.RefAddr;
+import javax.naming.Reference;
+import javax.naming.StringRefAddr;
+
+import org.jboss.logging.Logger;
+import org.jboss.naming.ENCFactory;
+import org.jnp.interfaces.Naming;
+import org.jnp.interfaces.NamingContext;
+
+/**
+ * A naming pojo that wraps the Naming server implementation. This is
+ * a refactoring of the legacy org.jnp.server.Main into a
+ *
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public class NamingBeanImpl
+ implements NamingBean
+{
+ private static Logger log = Logger.getLogger(NamingBeanImpl.class);
+ // Attributes ----------------------------------------------------
+ /** The Naming interface server implementation */
+ protected Naming theServer;
+ /** A flag indicating if theServer will be set as the NamingContext.setLocal value */
+ protected boolean InstallGlobalService = true;
+ /** A flag indicating if theServer will try to use the NamingContext.setLocal value */
+ protected boolean UseGlobalService = true;
+ /** The plugin for the manager which dispatches EventContext events to listeners */
+ private EventMgr eventMgr;
+ /** The SecurityManager */
+ private SecurityManager securityMgr;
+
+ // Static --------------------------------------------------------
+ public static void main(String[] args)
+ throws Exception
+ {
+ new Main().start();
+ }
+
+ // Constructors --------------------------------------------------
+ public NamingBeanImpl()
+ {
+ }
+
+ // Public --------------------------------------------------------
+ public Naming getNamingInstance()
+ {
+ return theServer;
+ }
+
+ public boolean getInstallGlobalService()
+ {
+ return InstallGlobalService;
+ }
+ public void setInstallGlobalService(boolean flag)
+ {
+ this.InstallGlobalService = flag;
+ }
+ public boolean getUseGlobalService()
+ {
+ return UseGlobalService;
+ }
+ public void setUseGlobalService(boolean flag)
+ {
+ this.UseGlobalService = flag;
+ }
+
+ public EventMgr getEventMgr()
+ {
+ return eventMgr;
+ }
+ public void setEventMgr(EventMgr eventMgr)
+ {
+ this.eventMgr = eventMgr;
+ }
+
+ public SecurityManager getSecurityMgr()
+ {
+ return securityMgr;
+ }
+ public void setSecurityMgr(SecurityManager securityMgr)
+ {
+ this.securityMgr = securityMgr;
+ }
+
+ /**
+ * Util method for possible override.
+ *
+ * @return new naming instance
+ * @throws Exception for any error
+ */
+ protected Naming createServer() throws Exception
+ {
+ return new NamingServer(null, null, eventMgr, securityMgr);
+ }
+
+ /**
+ *
+ * @throws Exception
+ */
+ public void start()
+ throws Exception
+ {
+ // Create the local naming service instance if it does not exist
+ if( theServer == null )
+ {
+ // See if we should try to reuse the current local server
+ if( UseGlobalService == true )
+ theServer = NamingContext.getLocal();
+ // If not, or there is no server create one
+ if( theServer == null )
+ theServer = createServer();
+ else
+ {
+ // We need to wrap the server to allow exporting it
+ NamingServerWrapper wrapper = new NamingServerWrapper(theServer);
+ theServer = wrapper;
+ }
+ log.debug("Using NamingServer: "+theServer);
+ if( InstallGlobalService == true )
+ {
+ // Set local server reference
+ NamingContext.setLocal(theServer);
+ log.debug("Installed global NamingServer: "+theServer);
+ }
+ }
+
+ /* Create a default InitialContext and dump out its env to show what properties
+ were used in its creation. If we find a Context.PROVIDER_URL property
+ issue a warning as this means JNDI lookups are going through RMI.
+ */
+ InitialContext iniCtx = new InitialContext();
+ Hashtable<?,?> env = iniCtx.getEnvironment();
+ log.debug("InitialContext Environment: ");
+ Object providerURL = null;
+ for (Object key : env.keySet())
+ {
+ Object value = env.get(key);
+ String type = value == null ? "" : value.getClass().getName();
+ log.debug("key="+key+", value("+type+")="+value);
+ if( key.equals(Context.PROVIDER_URL) )
+ providerURL = value;
+ }
+ // Warn if there was a Context.PROVIDER_URL
+ if( providerURL != null )
+ log.warn("Context.PROVIDER_URL in server jndi.properties, url="+providerURL);
+
+ /* Bind an ObjectFactory to "java:comp" so that "java:comp/env" lookups
+ produce a unique context for each thread contexxt ClassLoader that
+ performs the lookup.
+ */
+ ClassLoader topLoader = Thread.currentThread().getContextClassLoader();
+ ENCFactory.setTopClassLoader(topLoader);
+ RefAddr refAddr = new StringRefAddr("nns", "ENC");
+ Reference envRef = new Reference("javax.namingMain.Context", refAddr, ENCFactory.class.getName(), null);
+ Context ctx = (Context)iniCtx.lookup("java:");
+ ctx.rebind("comp", envRef);
+ ctx.close();
+ iniCtx.close();
+ }
+
+ /**
+ * Clear the NamingContext local server if its our theSever value
+ */
+ public void stop()
+ {
+ if(NamingContext.getLocal() == theServer)
+ NamingContext.setLocal(null);
+ }
+}
Deleted: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingServer.java
===================================================================
--- projects/naming/trunk/jnpserver/src/main/java/org/jnp/server/NamingServer.java 2008-11-05 04:14:24 UTC (rev 80546)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingServer.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -1,786 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jnp.server;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import javax.naming.Binding;
-import javax.naming.CannotProceedException;
-import javax.naming.Context;
-import javax.naming.InvalidNameException;
-import javax.naming.Name;
-import javax.naming.NameAlreadyBoundException;
-import javax.naming.NameClassPair;
-import javax.naming.NameNotFoundException;
-import javax.naming.NamingException;
-import javax.naming.NotContextException;
-import javax.naming.Reference;
-import javax.naming.event.EventContext;
-import javax.naming.event.NamingEvent;
-import javax.naming.event.NamingListener;
-import javax.naming.spi.ResolveResult;
-
-import org.jboss.logging.Logger;
-import org.jboss.naming.JndiPermission;
-import org.jnp.interfaces.Naming;
-import org.jnp.interfaces.NamingContext;
-import org.jnp.interfaces.NamingEvents;
-import org.jnp.interfaces.NamingParser;
-
-/**
- * The in memory JNDI naming server implementation class.
- *
- * @author Rickard Oberg
- * @author patriot1burke
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-public class NamingServer
- implements Naming, NamingEvents, java.io.Serializable
-{
- private static Logger log = Logger.getLogger(NamingServer.class);
-
- /** @since 1.12 at least */
- private static final long serialVersionUID = 4183855539507934373L;
- // Constants -----------------------------------------------------
-
- // Attributes ----------------------------------------------------
- /** */
- protected Map<String, Binding> table = createTable();
- protected Name prefix;
- protected NamingParser parser = new NamingParser();
- protected NamingServer parent;
- /** The NamingListeners registered with this context */
- private transient EventListeners listeners;
- /** The manager for EventContext listeners */
- private transient EventMgr eventMgr;
- private transient boolean trace;
-
- // Static --------------------------------------------------------
-
- // Constructors --------------------------------------------------
-
- public NamingServer()
- throws NamingException
- {
- this(null, null);
- }
-
- public NamingServer(Name prefix, NamingServer parent)
- throws NamingException
- {
- this(null, null, null);
- }
- public NamingServer(Name prefix, NamingServer parent, EventMgr eventMgr)
- throws NamingException
- {
- if (prefix == null)
- prefix = parser.parse("");
- this.prefix = prefix;
- this.parent = parent;
- this.eventMgr = eventMgr;
- this.trace = log.isTraceEnabled();
- }
-
-
- // Public --------------------------------------------------------
-
- // NamingListener registration
- public synchronized void addNamingListener(EventContext context, Name target, int scope, NamingListener l)
- throws NamingException
- {
- if(listeners == null)
- listeners = new EventListeners(context);
- if(trace)
- log.trace("addNamingListener, target: "+target+", scope: "+scope);
- listeners.addNamingListener(context, target, scope, l);
- }
-
- public void removeNamingListener(NamingListener l) throws NamingException
- {
- if(listeners != null)
- {
- listeners.removeNamingListener(l);
- }
- }
-
- /**
- * We don't need targets to exist?
- * @return false
- * @throws NamingException
- */
- public boolean targetMustExist() throws NamingException
- {
- return false;
- }
-
- // Naming implementation -----------------------------------------
- public synchronized void bind(Name name, Object obj, String className)
- throws NamingException
- {
- if (name.isEmpty())
- {
- // Empty names are not allowed
- throw new InvalidNameException("An empty name cannot be passed to bind");
- }
- else if (name.size() > 1)
- {
- // Recurse to find correct context
-// System.out.println("bind#"+name+"#");
-
- Object ctx = getObject(name);
- if (ctx != null)
- {
- if (ctx instanceof NamingServer)
- {
- NamingServer ns = (NamingServer) ctx;
- ns.bind(name.getSuffix(1),obj, className);
- }
- else if (ctx instanceof Reference)
- {
- // Federation
- if (((Reference)ctx).get("nns") != null)
- {
- CannotProceedException cpe = new CannotProceedException();
- cpe.setResolvedObj(ctx);
- cpe.setRemainingName(name.getSuffix(1));
- throw cpe;
- }
- else
- {
- throw new NotContextException();
- }
- }
- else
- {
- throw new NotContextException();
- }
- }
- else
- {
- throw new NameNotFoundException(name.toString()+" in: "+prefix);
- }
- }
- else
- {
- // Bind object
- if (name.get(0).equals(""))
- {
- throw new InvalidNameException("An empty name cannot be passed to bind");
- }
- else
- {
- if(trace)
- log.trace("bind "+name+"="+obj+", "+className);
- try
- {
- getBinding(name);
- // Already bound
- throw new NameAlreadyBoundException(name.toString());
- }
- catch (NameNotFoundException e)
- {
- Name fullName = (Name) prefix.clone();
- fullName.addAll(name);
- SecurityManager sm = System.getSecurityManager();
- if(sm != null)
- {
- JndiPermission perm = new JndiPermission(fullName, JndiPermission.BIND);
- sm.checkPermission(perm);
- }
-
- Binding newb = setBinding(name,obj,className);
- // Notify event listeners
- Binding oldb = null;
- this.fireEvent(fullName, oldb, newb, NamingEvent.OBJECT_ADDED, "bind");
- }
- }
- }
- }
-
- public synchronized void rebind(Name name, Object obj, String className)
- throws NamingException
- {
- if (name.isEmpty())
- {
- // Empty names are not allowed
- throw new InvalidNameException("An empty name cannot be passed to rebind");
- }
- else if (name.size() > 1)
- {
- // Recurse to find correct context
-// System.out.println("rebind#"+name+"#");
-
- Object ctx = getObject(name);
- if (ctx instanceof NamingServer)
- {
- ((NamingServer)ctx).rebind(name.getSuffix(1),obj, className);
- }
- else if (ctx instanceof Reference)
- {
- // Federation
- if (((Reference)ctx).get("nns") != null)
- {
- CannotProceedException cpe = new CannotProceedException();
- cpe.setResolvedObj(ctx);
- cpe.setRemainingName(name.getSuffix(1));
- throw cpe;
- }
- else
- {
- throw new NotContextException();
- }
- }
- else
- {
- throw new NotContextException();
- }
- }
- else
- {
- // Bind object
- if (name.get(0).equals(""))
- {
- throw new InvalidNameException("An empty name cannot be passed to rebind");
- }
- else
- {
- SecurityManager sm = System.getSecurityManager();
- Name fullName = (Name) prefix.clone();
- String comp = name.get(0);
- fullName.add(comp);
- if(sm != null)
- {
- JndiPermission perm = new JndiPermission(fullName, JndiPermission.REBIND);
- sm.checkPermission(perm);
- }
-
- Binding oldb = table.get(comp);
- Binding newb = setBinding(name,obj,className);
- // Notify event listeners
- if(listeners != null)
- {
- int type = NamingEvent.OBJECT_CHANGED;
- if(oldb == null)
- type = NamingEvent.OBJECT_ADDED;
- this.fireEvent(fullName, oldb, newb, type, "rebind");
- }
- }
- }
- }
-
- public synchronized void unbind(Name name)
- throws NamingException
- {
- if (name.isEmpty())
- {
- // Empty names are not allowed
- throw new InvalidNameException();
- }
- else if (name.size() > 1)
- {
- // Recurse to find correct context
-// System.out.println("unbind#"+name+"#");
-
- Object ctx = getObject(name);
- if (ctx instanceof NamingServer)
- {
- ((NamingServer)ctx).unbind(name.getSuffix(1));
- }
- else if (ctx instanceof Reference)
- {
- // Federation
- if (((Reference)ctx).get("nns") != null)
- {
- CannotProceedException cpe = new CannotProceedException();
- cpe.setResolvedObj(ctx);
- cpe.setRemainingName(name.getSuffix(1));
- throw cpe;
- }
- else
- {
- throw new NotContextException();
- }
- }
- else
- {
- throw new NotContextException();
- }
- } else
- {
- // Unbind object
- if (name.get(0).equals(""))
- {
- throw new InvalidNameException();
- }
- else
- {
-// System.out.println("unbind "+name+"="+getBinding(name));
- if (getBinding(name) != null)
- {
- SecurityManager sm = System.getSecurityManager();
- Name fullName = (Name) prefix.clone();
- fullName.addAll(name);
- if(sm != null)
- {
- JndiPermission perm = new JndiPermission(fullName, JndiPermission.UNBIND);
- sm.checkPermission(perm);
- }
-
- Binding newb = null;
- Binding oldb = removeBinding(name);
- // Notify event listeners
- int type = NamingEvent.OBJECT_REMOVED;
- this.fireEvent(fullName, oldb, newb, type, "unbind");
- }
- else
- {
- throw new NameNotFoundException();
- }
- }
- }
- }
-
-// public synchronized Object lookup(Name name)
- public Object lookup(Name name)
- throws NamingException
- {
- Object result;
- if (name.isEmpty())
- {
- SecurityManager sm = System.getSecurityManager();
- if(sm != null)
- {
- JndiPermission perm = new JndiPermission(prefix, JndiPermission.LOOKUP);
- sm.checkPermission(perm);
- }
-
- // Return this
- result = new NamingContext(null, (Name)(prefix.clone()), getRoot());
- }
- else if (name.size() > 1)
- {
- // Recurse to find correct context
-// System.out.println("lookup#"+name+"#");
-
- Object ctx = getObject(name);
- if (ctx instanceof NamingServer)
- {
- result = ((NamingServer)ctx).lookup(name.getSuffix(1));
- }
- else if (ctx instanceof Reference)
- {
- // Federation
- if (((Reference)ctx).get("nns") != null)
- {
- CannotProceedException cpe = new CannotProceedException();
- cpe.setResolvedObj(ctx);
- cpe.setRemainingName(name.getSuffix(1));
- throw cpe;
- }
-
- result = new ResolveResult(ctx, name.getSuffix(1));
- } else
- {
- throw new NotContextException();
- }
- }
- else
- {
- // Get object to return
- if (name.get(0).equals(""))
- {
- SecurityManager sm = System.getSecurityManager();
- if(sm != null)
- {
- JndiPermission perm = new JndiPermission(prefix, JndiPermission.LOOKUP);
- sm.checkPermission(perm);
- }
- result = new NamingContext(null, (Name)(prefix.clone()), getRoot());
- }
- else
- {
-// System.out.println("lookup "+name);
- SecurityManager sm = System.getSecurityManager();
- Name fullName = (Name)(prefix.clone());
- fullName.addAll(name);
- if(sm != null)
- {
- JndiPermission perm = new JndiPermission(fullName, JndiPermission.LOOKUP);
- sm.checkPermission(perm);
- }
-
- Object res = getObject(name);
-
- if (res instanceof NamingServer)
- {
- result = new NamingContext(null, fullName, getRoot());
- }
- else
- result = res;
- }
- }
-
- return result;
- }
-
- public Collection<NameClassPair> list(Name name)
- throws NamingException
- {
- if (name.isEmpty())
- {
- SecurityManager sm = System.getSecurityManager();
- if(sm != null)
- {
- JndiPermission perm = new JndiPermission(prefix, JndiPermission.LIST);
- sm.checkPermission(perm);
- }
-
- ArrayList<NameClassPair> list = new ArrayList<NameClassPair>();
- for(Binding b : table.values())
- {
- NameClassPair ncp = new NameClassPair(b.getName(),b.getClassName(), true);
- list.add(ncp);
- }
- return list;
- }
- else
- {
- Object ctx = getObject(name);
- if (ctx instanceof NamingServer)
- {
- return ((NamingServer)ctx).list(name.getSuffix(1));
- }
- else if (ctx instanceof Reference)
- {
- // Federation
- if (((Reference)ctx).get("nns") != null)
- {
- CannotProceedException cpe = new CannotProceedException();
- cpe.setResolvedObj(ctx);
- cpe.setRemainingName(name.getSuffix(1));
- throw cpe;
- }
- else
- {
- throw new NotContextException();
- }
- }
- else
- {
- throw new NotContextException();
- }
- }
- }
-
- public Collection<Binding> listBindings(Name name)
- throws NamingException
- {
- if (name.isEmpty())
- {
- SecurityManager sm = System.getSecurityManager();
- if(sm != null)
- {
- JndiPermission perm = new JndiPermission(prefix, JndiPermission.LIST_BINDINGS);
- sm.checkPermission(perm);
- }
-
- Collection<Binding> bindings = table.values();
- Collection<Binding> newBindings = new ArrayList<Binding>(bindings.size());
- for(Binding b : bindings)
- {
- if (b.getObject() instanceof NamingServer)
- {
- Name n = (Name)prefix.clone();
- n.add(b.getName());
- newBindings.add(new Binding(b.getName(),
- b.getClassName(),
- new NamingContext(null, n, getRoot())));
- }
- else
- {
- newBindings.add(b);
- }
- }
-
- return newBindings;
- } else
- {
- Object ctx = getObject(name);
- if (ctx instanceof NamingServer)
- {
- return ((NamingServer)ctx).listBindings(name.getSuffix(1));
- } else if (ctx instanceof Reference)
- {
- // Federation
- if (((Reference)ctx).get("nns") != null)
- {
- CannotProceedException cpe = new CannotProceedException();
- cpe.setResolvedObj(ctx);
- cpe.setRemainingName(name.getSuffix(1));
- throw cpe;
- } else
- {
- throw new NotContextException();
- }
- } else
- {
- throw new NotContextException();
- }
- }
- }
-
- public Context createSubcontext(Name name)
- throws NamingException
- {
- if( name.size() == 0 )
- throw new InvalidNameException("Cannot pass an empty name to createSubcontext");
-
- NamingException ex = null;
- Context subCtx = null;
- if (name.size() > 1)
- {
- Object ctx = getObject(name);
- if (ctx != null)
- {
- Name subCtxName = name.getSuffix(1);
- if (ctx instanceof NamingServer)
- {
- subCtx = ((NamingServer)ctx).createSubcontext(subCtxName);
- }
- else if (ctx instanceof Reference)
- {
- // Federation
- if (((Reference)ctx).get("nns") != null)
- {
- CannotProceedException cpe = new CannotProceedException();
- cpe.setResolvedObj(ctx);
- cpe.setRemainingName(subCtxName);
- throw cpe;
- }
- else
- {
- ex = new NotContextException();
- ex.setResolvedName(name.getPrefix(0));
- ex.setRemainingName(subCtxName);
- throw ex;
- }
- }
- else
- {
- ex = new NotContextException();
- ex.setResolvedName(name.getPrefix(0));
- ex.setRemainingName(subCtxName);
- throw ex;
- }
- }
- else
- {
- ex = new NameNotFoundException();
- ex.setRemainingName(name);
- throw ex;
- }
- }
- else
- {
- Object binding = table.get(name.get(0));
- if( binding != null )
- {
- ex = new NameAlreadyBoundException();
- ex.setResolvedName(prefix);
- ex.setRemainingName(name);
- throw ex;
- }
- else
- {
- Name fullName = (Name) prefix.clone();
- fullName.addAll(name);
- SecurityManager sm = System.getSecurityManager();
- if(sm != null)
- {
- JndiPermission perm = new JndiPermission(fullName, JndiPermission.CREATE_SUBCONTEXT);
- sm.checkPermission(perm);
- }
- NamingServer subContext = createNamingServer(fullName, this);
- subCtx = new NamingContext(null, fullName, getRoot());
- setBinding(name, subContext, NamingContext.class.getName());
- // Return the NamingContext as the binding value
- Binding newb = new Binding(name.toString(), NamingContext.class.getName(), subCtx, true);
- // Notify event listeners
- if(listeners != null)
- {
- Binding oldb = null;
- this.fireEvent(fullName, oldb, newb, NamingEvent.OBJECT_ADDED, "createSubcontext");
- }
- }
- }
- return subCtx;
- }
-
- public Naming getRoot()
- {
- if (parent == null)
- return this;
- else
- return parent.getRoot();
- }
-
- // Y overrides ---------------------------------------------------
-
- // Package protected ---------------------------------------------
-
- // Protected -----------------------------------------------------
-
- protected Map<String, Binding> createTable()
- {
- return new ConcurrentHashMap<String, Binding>();
- }
-
- /**
- * Create sub naming.
- *
- * @param prefix the prefix
- * @param parent the parent naming server
- * @return new sub instance
- * @throws NamingException for any error
- */
- protected NamingServer createNamingServer(Name prefix, NamingServer parent)
- throws NamingException
- {
- return new NamingServer(prefix, parent, eventMgr);
- }
-
- protected void fireEvent(Name fullName, Binding oldb, Binding newb, int type,
- String changeInfo)
- throws NamingException
- {
- if(eventMgr == null)
- {
- if(trace)
- log.trace("Skipping event dispatch because there is no EventMgr");
- return;
- }
-
- if(listeners != null)
- {
- if(trace)
- log.trace("fireEvent, type: "+type+", fullName: "+fullName);
- HashSet<Integer> scopes = new HashSet<Integer>();
- scopes.add(EventContext.OBJECT_SCOPE);
- scopes.add(EventContext.ONELEVEL_SCOPE);
- scopes.add(EventContext.SUBTREE_SCOPE);
- eventMgr.fireEvent(fullName, oldb, newb, type, changeInfo, listeners, scopes);
- }
- else if(trace)
- {
- log.trace("fireEvent, type: "+type+", fullName: "+fullName);
- }
- // Traverse to parent for SUBTREE_SCOPE
- HashSet<Integer> scopes = new HashSet<Integer>();
- scopes.add(EventContext.SUBTREE_SCOPE);
- NamingServer nsparent = parent;
- while(nsparent != null)
- {
- if(nsparent.listeners != null)
- {
- eventMgr.fireEvent(fullName, oldb, newb, type, changeInfo, nsparent.listeners, scopes);
- }
- nsparent = nsparent.parent;
- }
- }
-
- // Private -------------------------------------------------------
-
- private Binding setBinding(Name name, Object obj, String className)
- {
- String n = name.toString();
- Binding b = new Binding(n, className, obj, true);
- table.put(n, b);
- if( trace )
- {
- StringBuffer tmp = new StringBuffer(super.toString());
- tmp.append(", setBinding: name=");
- tmp.append(name);
- tmp.append(", obj=");
- tmp.append(obj);
- tmp.append(", className=");
- tmp.append(className);
- log.trace(tmp.toString());
- }
- return b;
- }
-
- private Binding getBinding(String key)
- throws NameNotFoundException
- {
- Binding b = table.get(key);
- if (b == null)
- {
- if( log.isTraceEnabled() )
- {
- StringBuffer tmp = new StringBuffer(super.toString());
- tmp.append(", No binding for: ");
- tmp.append(key);
- tmp.append(" in context ");
- tmp.append(this.prefix);
- tmp.append(", bindings:\n");
- Iterator<Binding> bindings = table.values().iterator();
- while( bindings.hasNext() )
- {
- Binding value = bindings.next();
- tmp.append(value.getName());
- tmp.append('=');
- if( value.getObject() != null )
- tmp.append(value.getObject().toString());
- else
- tmp.append("null");
- tmp.append('\n');
- }
- log.trace(tmp.toString());
- }
- throw new NameNotFoundException(key + " not bound");
- }
- return b;
- }
-
- private Binding getBinding(Name key)
- throws NameNotFoundException
- {
- return getBinding(key.get(0));
- }
-
- private Object getObject(Name key)
- throws NameNotFoundException
- {
- return getBinding(key).getObject();
- }
-
- private Binding removeBinding(Name name)
- {
- return table.remove(name.get(0));
- }
-
-}
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingServer.java (from rev 80561, projects/naming/trunk/jnpserver/src/main/java/org/jnp/server/NamingServer.java)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingServer.java (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/main/java/org/jnp/server/NamingServer.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,799 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jnp.server;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.naming.Binding;
+import javax.naming.CannotProceedException;
+import javax.naming.Context;
+import javax.naming.InvalidNameException;
+import javax.naming.Name;
+import javax.naming.NameAlreadyBoundException;
+import javax.naming.NameClassPair;
+import javax.naming.NameNotFoundException;
+import javax.naming.NamingException;
+import javax.naming.NotContextException;
+import javax.naming.Reference;
+import javax.naming.event.EventContext;
+import javax.naming.event.NamingEvent;
+import javax.naming.event.NamingListener;
+import javax.naming.spi.ResolveResult;
+
+import org.jboss.logging.Logger;
+import org.jboss.naming.JndiPermission;
+import org.jnp.interfaces.Naming;
+import org.jnp.interfaces.NamingContext;
+import org.jnp.interfaces.NamingEvents;
+import org.jnp.interfaces.NamingParser;
+
+/**
+ * The in memory JNDI naming server implementation class.
+ *
+ * @author Rickard Oberg
+ * @author patriot1burke
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public class NamingServer
+ implements Naming, NamingEvents, java.io.Serializable
+{
+ private static Logger log = Logger.getLogger(NamingServer.class);
+
+ /** @since 1.12 at least */
+ private static final long serialVersionUID = 4183855539507934373L;
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+ /** */
+ protected Map<String, Binding> table = createTable();
+ protected Name prefix;
+ protected NamingParser parser = new NamingParser();
+ protected NamingServer parent;
+ /** The NamingListeners registered with this context */
+ private transient EventListeners listeners;
+ /** The manager for EventContext listeners */
+ private transient EventMgr eventMgr;
+ private transient SecurityManager secMgr;
+ private transient boolean trace;
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ public NamingServer()
+ throws NamingException
+ {
+ this(null, null);
+ }
+
+ public NamingServer(Name prefix, NamingServer parent)
+ throws NamingException
+ {
+ this(prefix, parent, null);
+ }
+ public NamingServer(Name prefix, NamingServer parent, EventMgr eventMgr)
+ throws NamingException
+ {
+ this(prefix, parent, eventMgr, null);
+ }
+ public NamingServer(Name prefix, NamingServer parent, EventMgr eventMgr,
+ SecurityManager secMgr)
+ throws NamingException
+ {
+ if (prefix == null)
+ prefix = parser.parse("");
+ this.prefix = prefix;
+ this.parent = parent;
+ this.eventMgr = eventMgr;
+ this.secMgr = secMgr;
+ this.trace = log.isTraceEnabled();
+ }
+
+ // Public --------------------------------------------------------
+
+ // NamingListener registration
+ public synchronized void addNamingListener(EventContext context, Name target, int scope, NamingListener l)
+ throws NamingException
+ {
+ if(listeners == null)
+ listeners = new EventListeners(context);
+ if(trace)
+ log.trace("addNamingListener, target: "+target+", scope: "+scope);
+ listeners.addNamingListener(context, target, scope, l);
+ }
+
+ public void removeNamingListener(NamingListener l) throws NamingException
+ {
+ if(listeners != null)
+ {
+ listeners.removeNamingListener(l);
+ }
+ }
+
+ /**
+ * We don't need targets to exist?
+ * @return false
+ * @throws NamingException
+ */
+ public boolean targetMustExist() throws NamingException
+ {
+ return false;
+ }
+
+ // Naming implementation -----------------------------------------
+ public synchronized void bind(Name name, Object obj, String className)
+ throws NamingException
+ {
+ if (name.isEmpty())
+ {
+ // Empty names are not allowed
+ throw new InvalidNameException("An empty name cannot be passed to bind");
+ }
+ else if (name.size() > 1)
+ {
+ // Recurse to find correct context
+// System.out.println("bind#"+name+"#");
+
+ Object ctx = getObject(name);
+ if (ctx != null)
+ {
+ if (ctx instanceof NamingServer)
+ {
+ NamingServer ns = (NamingServer) ctx;
+ ns.bind(name.getSuffix(1),obj, className);
+ }
+ else if (ctx instanceof Reference)
+ {
+ // Federation
+ if (((Reference)ctx).get("nns") != null)
+ {
+ CannotProceedException cpe = new CannotProceedException();
+ cpe.setResolvedObj(ctx);
+ cpe.setRemainingName(name.getSuffix(1));
+ throw cpe;
+ }
+ else
+ {
+ throw new NotContextException();
+ }
+ }
+ else
+ {
+ throw new NotContextException();
+ }
+ }
+ else
+ {
+ throw new NameNotFoundException(name.toString()+" in: "+prefix);
+ }
+ }
+ else
+ {
+ // Bind object
+ if (name.get(0).equals(""))
+ {
+ throw new InvalidNameException("An empty name cannot be passed to bind");
+ }
+ else
+ {
+ if(trace)
+ log.trace("bind "+name+"="+obj+", "+className);
+ try
+ {
+ getBinding(name);
+ // Already bound
+ throw new NameAlreadyBoundException(name.toString());
+ }
+ catch (NameNotFoundException e)
+ {
+ Name fullName = (Name) prefix.clone();
+ fullName.addAll(name);
+ SecurityManager sm = getSecurityManager();
+ if(sm != null)
+ {
+ JndiPermission perm = new JndiPermission(fullName, JndiPermission.BIND);
+ sm.checkPermission(perm);
+ }
+
+ Binding newb = setBinding(name,obj,className);
+ // Notify event listeners
+ Binding oldb = null;
+ this.fireEvent(fullName, oldb, newb, NamingEvent.OBJECT_ADDED, "bind");
+ }
+ }
+ }
+ }
+
+ public synchronized void rebind(Name name, Object obj, String className)
+ throws NamingException
+ {
+ if (name.isEmpty())
+ {
+ // Empty names are not allowed
+ throw new InvalidNameException("An empty name cannot be passed to rebind");
+ }
+ else if (name.size() > 1)
+ {
+ // Recurse to find correct context
+// System.out.println("rebind#"+name+"#");
+
+ Object ctx = getObject(name);
+ if (ctx instanceof NamingServer)
+ {
+ ((NamingServer)ctx).rebind(name.getSuffix(1),obj, className);
+ }
+ else if (ctx instanceof Reference)
+ {
+ // Federation
+ if (((Reference)ctx).get("nns") != null)
+ {
+ CannotProceedException cpe = new CannotProceedException();
+ cpe.setResolvedObj(ctx);
+ cpe.setRemainingName(name.getSuffix(1));
+ throw cpe;
+ }
+ else
+ {
+ throw new NotContextException();
+ }
+ }
+ else
+ {
+ throw new NotContextException();
+ }
+ }
+ else
+ {
+ // Bind object
+ if (name.get(0).equals(""))
+ {
+ throw new InvalidNameException("An empty name cannot be passed to rebind");
+ }
+ else
+ {
+ SecurityManager sm = getSecurityManager();
+ Name fullName = (Name) prefix.clone();
+ String comp = name.get(0);
+ fullName.add(comp);
+ if(sm != null)
+ {
+ JndiPermission perm = new JndiPermission(fullName, JndiPermission.REBIND);
+ sm.checkPermission(perm);
+ }
+
+ Binding oldb = table.get(comp);
+ Binding newb = setBinding(name,obj,className);
+ // Notify event listeners
+ if(listeners != null)
+ {
+ int type = NamingEvent.OBJECT_CHANGED;
+ if(oldb == null)
+ type = NamingEvent.OBJECT_ADDED;
+ this.fireEvent(fullName, oldb, newb, type, "rebind");
+ }
+ }
+ }
+ }
+
+ public synchronized void unbind(Name name)
+ throws NamingException
+ {
+ if (name.isEmpty())
+ {
+ // Empty names are not allowed
+ throw new InvalidNameException();
+ }
+ else if (name.size() > 1)
+ {
+ // Recurse to find correct context
+// System.out.println("unbind#"+name+"#");
+
+ Object ctx = getObject(name);
+ if (ctx instanceof NamingServer)
+ {
+ ((NamingServer)ctx).unbind(name.getSuffix(1));
+ }
+ else if (ctx instanceof Reference)
+ {
+ // Federation
+ if (((Reference)ctx).get("nns") != null)
+ {
+ CannotProceedException cpe = new CannotProceedException();
+ cpe.setResolvedObj(ctx);
+ cpe.setRemainingName(name.getSuffix(1));
+ throw cpe;
+ }
+ else
+ {
+ throw new NotContextException();
+ }
+ }
+ else
+ {
+ throw new NotContextException();
+ }
+ } else
+ {
+ // Unbind object
+ if (name.get(0).equals(""))
+ {
+ throw new InvalidNameException();
+ }
+ else
+ {
+// System.out.println("unbind "+name+"="+getBinding(name));
+ if (getBinding(name) != null)
+ {
+ SecurityManager sm = getSecurityManager();
+ Name fullName = (Name) prefix.clone();
+ fullName.addAll(name);
+ if(sm != null)
+ {
+ JndiPermission perm = new JndiPermission(fullName, JndiPermission.UNBIND);
+ sm.checkPermission(perm);
+ }
+
+ Binding newb = null;
+ Binding oldb = removeBinding(name);
+ // Notify event listeners
+ int type = NamingEvent.OBJECT_REMOVED;
+ this.fireEvent(fullName, oldb, newb, type, "unbind");
+ }
+ else
+ {
+ throw new NameNotFoundException();
+ }
+ }
+ }
+ }
+
+// public synchronized Object lookup(Name name)
+ public Object lookup(Name name)
+ throws NamingException
+ {
+ Object result;
+ if (name.isEmpty())
+ {
+ SecurityManager sm = getSecurityManager();
+ if(sm != null)
+ {
+ JndiPermission perm = new JndiPermission(prefix, JndiPermission.LOOKUP);
+ sm.checkPermission(perm);
+ }
+
+ // Return this
+ result = new NamingContext(null, (Name)(prefix.clone()), getRoot());
+ }
+ else if (name.size() > 1)
+ {
+ // Recurse to find correct context
+// System.out.println("lookup#"+name+"#");
+
+ Object ctx = getObject(name);
+ if (ctx instanceof NamingServer)
+ {
+ result = ((NamingServer)ctx).lookup(name.getSuffix(1));
+ }
+ else if (ctx instanceof Reference)
+ {
+ // Federation
+ if (((Reference)ctx).get("nns") != null)
+ {
+ CannotProceedException cpe = new CannotProceedException();
+ cpe.setResolvedObj(ctx);
+ cpe.setRemainingName(name.getSuffix(1));
+ throw cpe;
+ }
+
+ result = new ResolveResult(ctx, name.getSuffix(1));
+ } else
+ {
+ throw new NotContextException();
+ }
+ }
+ else
+ {
+ // Get object to return
+ if (name.get(0).equals(""))
+ {
+ SecurityManager sm = getSecurityManager();
+ if(sm != null)
+ {
+ JndiPermission perm = new JndiPermission(prefix, JndiPermission.LOOKUP);
+ sm.checkPermission(perm);
+ }
+ result = new NamingContext(null, (Name)(prefix.clone()), getRoot());
+ }
+ else
+ {
+// System.out.println("lookup "+name);
+ SecurityManager sm = getSecurityManager();
+ Name fullName = (Name)(prefix.clone());
+ fullName.addAll(name);
+ if(sm != null)
+ {
+ JndiPermission perm = new JndiPermission(fullName, JndiPermission.LOOKUP);
+ sm.checkPermission(perm);
+ }
+
+ Object res = getObject(name);
+
+ if (res instanceof NamingServer)
+ {
+ result = new NamingContext(null, fullName, getRoot());
+ }
+ else
+ result = res;
+ }
+ }
+
+ return result;
+ }
+
+ public Collection<NameClassPair> list(Name name)
+ throws NamingException
+ {
+ if (name.isEmpty())
+ {
+ SecurityManager sm = getSecurityManager();
+ if(sm != null)
+ {
+ JndiPermission perm = new JndiPermission(prefix, JndiPermission.LIST);
+ sm.checkPermission(perm);
+ }
+
+ ArrayList<NameClassPair> list = new ArrayList<NameClassPair>();
+ for(Binding b : table.values())
+ {
+ NameClassPair ncp = new NameClassPair(b.getName(),b.getClassName(), true);
+ list.add(ncp);
+ }
+ return list;
+ }
+ else
+ {
+ Object ctx = getObject(name);
+ if (ctx instanceof NamingServer)
+ {
+ return ((NamingServer)ctx).list(name.getSuffix(1));
+ }
+ else if (ctx instanceof Reference)
+ {
+ // Federation
+ if (((Reference)ctx).get("nns") != null)
+ {
+ CannotProceedException cpe = new CannotProceedException();
+ cpe.setResolvedObj(ctx);
+ cpe.setRemainingName(name.getSuffix(1));
+ throw cpe;
+ }
+ else
+ {
+ throw new NotContextException();
+ }
+ }
+ else
+ {
+ throw new NotContextException();
+ }
+ }
+ }
+
+ public Collection<Binding> listBindings(Name name)
+ throws NamingException
+ {
+ if (name.isEmpty())
+ {
+ SecurityManager sm = getSecurityManager();
+ if(sm != null)
+ {
+ JndiPermission perm = new JndiPermission(prefix, JndiPermission.LIST_BINDINGS);
+ sm.checkPermission(perm);
+ }
+
+ Collection<Binding> bindings = table.values();
+ Collection<Binding> newBindings = new ArrayList<Binding>(bindings.size());
+ for(Binding b : bindings)
+ {
+ if (b.getObject() instanceof NamingServer)
+ {
+ Name n = (Name)prefix.clone();
+ n.add(b.getName());
+ newBindings.add(new Binding(b.getName(),
+ b.getClassName(),
+ new NamingContext(null, n, getRoot())));
+ }
+ else
+ {
+ newBindings.add(b);
+ }
+ }
+
+ return newBindings;
+ } else
+ {
+ Object ctx = getObject(name);
+ if (ctx instanceof NamingServer)
+ {
+ return ((NamingServer)ctx).listBindings(name.getSuffix(1));
+ } else if (ctx instanceof Reference)
+ {
+ // Federation
+ if (((Reference)ctx).get("nns") != null)
+ {
+ CannotProceedException cpe = new CannotProceedException();
+ cpe.setResolvedObj(ctx);
+ cpe.setRemainingName(name.getSuffix(1));
+ throw cpe;
+ } else
+ {
+ throw new NotContextException();
+ }
+ } else
+ {
+ throw new NotContextException();
+ }
+ }
+ }
+
+ public Context createSubcontext(Name name)
+ throws NamingException
+ {
+ if( name.size() == 0 )
+ throw new InvalidNameException("Cannot pass an empty name to createSubcontext");
+
+ NamingException ex = null;
+ Context subCtx = null;
+ if (name.size() > 1)
+ {
+ Object ctx = getObject(name);
+ if (ctx != null)
+ {
+ Name subCtxName = name.getSuffix(1);
+ if (ctx instanceof NamingServer)
+ {
+ subCtx = ((NamingServer)ctx).createSubcontext(subCtxName);
+ }
+ else if (ctx instanceof Reference)
+ {
+ // Federation
+ if (((Reference)ctx).get("nns") != null)
+ {
+ CannotProceedException cpe = new CannotProceedException();
+ cpe.setResolvedObj(ctx);
+ cpe.setRemainingName(subCtxName);
+ throw cpe;
+ }
+ else
+ {
+ ex = new NotContextException();
+ ex.setResolvedName(name.getPrefix(0));
+ ex.setRemainingName(subCtxName);
+ throw ex;
+ }
+ }
+ else
+ {
+ ex = new NotContextException();
+ ex.setResolvedName(name.getPrefix(0));
+ ex.setRemainingName(subCtxName);
+ throw ex;
+ }
+ }
+ else
+ {
+ ex = new NameNotFoundException();
+ ex.setRemainingName(name);
+ throw ex;
+ }
+ }
+ else
+ {
+ Object binding = table.get(name.get(0));
+ if( binding != null )
+ {
+ ex = new NameAlreadyBoundException();
+ ex.setResolvedName(prefix);
+ ex.setRemainingName(name);
+ throw ex;
+ }
+ else
+ {
+ Name fullName = (Name) prefix.clone();
+ fullName.addAll(name);
+ SecurityManager sm = getSecurityManager();
+ if(sm != null)
+ {
+ JndiPermission perm = new JndiPermission(fullName, JndiPermission.CREATE_SUBCONTEXT);
+ sm.checkPermission(perm);
+ }
+ NamingServer subContext = createNamingServer(fullName, this);
+ subCtx = new NamingContext(null, fullName, getRoot());
+ setBinding(name, subContext, NamingContext.class.getName());
+ // Return the NamingContext as the binding value
+ Binding newb = new Binding(name.toString(), NamingContext.class.getName(), subCtx, true);
+ // Notify event listeners
+ if(listeners != null)
+ {
+ Binding oldb = null;
+ this.fireEvent(fullName, oldb, newb, NamingEvent.OBJECT_ADDED, "createSubcontext");
+ }
+ }
+ }
+ return subCtx;
+ }
+
+ public Naming getRoot()
+ {
+ if (parent == null)
+ return this;
+ else
+ return parent.getRoot();
+ }
+
+ // Y overrides ---------------------------------------------------
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ protected Map<String, Binding> createTable()
+ {
+ return new ConcurrentHashMap<String, Binding>();
+ }
+
+ /**
+ * Create sub naming.
+ *
+ * @param prefix the prefix
+ * @param parent the parent naming server
+ * @return new sub instance
+ * @throws NamingException for any error
+ */
+ protected NamingServer createNamingServer(Name prefix, NamingServer parent)
+ throws NamingException
+ {
+ return new NamingServer(prefix, parent, eventMgr);
+ }
+
+ protected void fireEvent(Name fullName, Binding oldb, Binding newb, int type,
+ String changeInfo)
+ throws NamingException
+ {
+ if(eventMgr == null)
+ {
+ if(trace)
+ log.trace("Skipping event dispatch because there is no EventMgr");
+ return;
+ }
+
+ if(listeners != null)
+ {
+ if(trace)
+ log.trace("fireEvent, type: "+type+", fullName: "+fullName);
+ HashSet<Integer> scopes = new HashSet<Integer>();
+ scopes.add(EventContext.OBJECT_SCOPE);
+ scopes.add(EventContext.ONELEVEL_SCOPE);
+ scopes.add(EventContext.SUBTREE_SCOPE);
+ eventMgr.fireEvent(fullName, oldb, newb, type, changeInfo, listeners, scopes);
+ }
+ else if(trace)
+ {
+ log.trace("fireEvent, type: "+type+", fullName: "+fullName);
+ }
+ // Traverse to parent for SUBTREE_SCOPE
+ HashSet<Integer> scopes = new HashSet<Integer>();
+ scopes.add(EventContext.SUBTREE_SCOPE);
+ NamingServer nsparent = parent;
+ while(nsparent != null)
+ {
+ if(nsparent.listeners != null)
+ {
+ eventMgr.fireEvent(fullName, oldb, newb, type, changeInfo, nsparent.listeners, scopes);
+ }
+ nsparent = nsparent.parent;
+ }
+ }
+
+ // Private -------------------------------------------------------
+
+ private Binding setBinding(Name name, Object obj, String className)
+ {
+ String n = name.toString();
+ Binding b = new Binding(n, className, obj, true);
+ table.put(n, b);
+ if( trace )
+ {
+ StringBuffer tmp = new StringBuffer(super.toString());
+ tmp.append(", setBinding: name=");
+ tmp.append(name);
+ tmp.append(", obj=");
+ tmp.append(obj);
+ tmp.append(", className=");
+ tmp.append(className);
+ log.trace(tmp.toString());
+ }
+ return b;
+ }
+
+ private Binding getBinding(String key)
+ throws NameNotFoundException
+ {
+ Binding b = table.get(key);
+ if (b == null)
+ {
+ if( log.isTraceEnabled() )
+ {
+ StringBuffer tmp = new StringBuffer(super.toString());
+ tmp.append(", No binding for: ");
+ tmp.append(key);
+ tmp.append(" in context ");
+ tmp.append(this.prefix);
+ tmp.append(", bindings:\n");
+ Iterator<Binding> bindings = table.values().iterator();
+ while( bindings.hasNext() )
+ {
+ Binding value = bindings.next();
+ tmp.append(value.getName());
+ tmp.append('=');
+ if( value.getObject() != null )
+ tmp.append(value.getObject().toString());
+ else
+ tmp.append("null");
+ tmp.append('\n');
+ }
+ log.trace(tmp.toString());
+ }
+ throw new NameNotFoundException(key + " not bound");
+ }
+ return b;
+ }
+
+ private Binding getBinding(Name key)
+ throws NameNotFoundException
+ {
+ return getBinding(key.get(0));
+ }
+
+ private Object getObject(Name key)
+ throws NameNotFoundException
+ {
+ return getBinding(key).getObject();
+ }
+
+ private Binding removeBinding(Name name)
+ {
+ return table.remove(name.get(0));
+ }
+
+ private SecurityManager getSecurityManager()
+ {
+ if(secMgr == null)
+ secMgr = System.getSecurityManager();
+ return secMgr;
+ }
+}
Deleted: projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingMCUnitTest.java
===================================================================
--- projects/naming/trunk/jnpserver/src/test/java/org/jnp/test/NamingMCUnitTest.java 2008-11-05 04:14:24 UTC (rev 80546)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingMCUnitTest.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -1,172 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jnp.test;
-
-import java.math.BigInteger;
-import java.net.InetAddress;
-import java.util.Properties;
-
-import javax.naming.InitialContext;
-
-import junit.framework.Test;
-
-import org.jboss.beans.metadata.api.annotations.Inject;
-import org.jboss.test.kernel.junit.MicrocontainerTest;
-import org.jnp.interfaces.TimedSocketFactory;
-
-/**
- * Test bootstraping the naming service using the mc
- *
- * @author Scott.Stark at jboss.org
- * @version $Revision:$
- */
-public class NamingMCUnitTest extends MicrocontainerTest
-{
- public static Test suite()
- {
- return suite(NamingMCUnitTest.class);
- }
- /** */
- private InitialContext ctx;
-
- /**
- *
- * @param name
- */
- public NamingMCUnitTest(String name)
- {
- super(name, true);
- }
-
- /**
- * Obtain the InitialContext from the InitialContextFactory bean ctx property.
- * Each test expects an InitialContextFactory bean
- * @see org.jboss.naming.InitialContextFactory
- *
- * @param ctx
- */
- @Inject(bean="InitialContextFactory", property="ctx")
- public void setInitialContext(InitialContext ctx)
- {
- this.ctx = ctx;
- }
-
- /**
- * Validate that a NamingBeanImpl mc bean is accessible via the
- * LocalOnlyContextFactory
- *
- * @throws Exception
- */
- public void testLocaNamingBeanImpl()
- throws Exception
- {
- assertNotNull(ctx);
- validateCtx(ctx);
- }
- /**
- * Validate that the NamingBeanImpl mc bean is accessible via the
- * InitialContext(env) using the LocalOnlyContextFactory
- * @throws Exception
- */
- public void testLocaNamingBeanImplViaInitialContextFactory()
- throws Exception
- {
- Properties env = new Properties();
- env.setProperty("java.naming.factory.initial", "org.jnp.interfaces.LocalOnlyContextFactory");
- env.setProperty("java.naming.factory.url", "org.jboss.naming:org.jnp.interfaces");
- InitialContext ic = new InitialContext(env);
- validateCtx(ic);
- }
-
- /**
- * Validate that a SingletonNamingServer mc bean is accessible via the
- * LocalOnlyContextFactory
- *
- * @throws Exception
- */
- public void testSingletonNamingServer()
- throws Exception
- {
- assertNotNull(ctx);
- validateCtx(ctx);
- }
-
- /**
- * Test the org.jnp.server.Main bean that wraps a NamingBean with remote
- * access via an rmi proxy
- *
- * @throws Exception
- */
- public void testMainBean()
- throws Exception
- {
- Properties env = new Properties();
- env.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
- env.setProperty("java.naming.provider.url", "localhost:1099");
- env.setProperty("java.naming.factory.url", "org.jboss.naming:org.jnp.interfaces");
- env.setProperty(TimedSocketFactory.JNP_TIMEOUT, "10000");
- env.setProperty(TimedSocketFactory.JNP_SO_TIMEOUT, "10000");
- InitialContext ic = new InitialContext(env);
- validateCtx(ic);
- }
- /**
- * Test the org.jnp.server.Main bean that wraps a NamingBean with remote
- * access via an rmi proxy using custom socket factories
- *
- * @throws Exception
- */
- public void testMainBeanSFs()
- throws Exception
- {
- InetAddress localAddr = InetAddress.getLocalHost();
- getLog().debug("InetAddress.getLocalHost(): "+localAddr);
- Properties env = new Properties();
- env.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
- env.setProperty("java.naming.provider.url", "localhost:2099");
- env.setProperty("java.naming.factory.url", "org.jboss.naming:org.jnp.interfaces");
- env.setProperty(TimedSocketFactory.JNP_TIMEOUT, "1000");
- env.setProperty(TimedSocketFactory.JNP_SO_TIMEOUT, "1000");
- InitialContext ic = new InitialContext(env);
- validateCtx(ic);
- }
-
- /**
- *
- * @param ic
- * @throws Exception
- */
- protected void validateCtx(InitialContext ic)
- throws Exception
- {
- Integer i1 = (Integer) ic.lookup("ints/1");
- assertEquals("ints/1", new Integer(1), i1);
- String s1 = (String) ic.lookup("strings/1");
- assertEquals("strings/1", "String1", s1);
- BigInteger bi1 = (BigInteger) ic.lookup("bigint/1");
- assertEquals("bigint/1", new BigInteger("123456789"), bi1);
- Properties env = (Properties) ic.lookup("env-props");
- Properties expected = new Properties();
- expected.setProperty("java.naming.factory.initial", "org.jnp.interfaces.LocalOnlyContextFactory");
- expected.setProperty("java.naming.factory.url", "org.jboss.naming:org.jnp.interfaces");
- assertEquals("env-props", expected, env);
- }
-}
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingMCUnitTest.java (from rev 80561, projects/naming/trunk/jnpserver/src/test/java/org/jnp/test/NamingMCUnitTest.java)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingMCUnitTest.java (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingMCUnitTest.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,282 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jnp.test;
+
+import java.math.BigInteger;
+import java.net.InetAddress;
+import java.security.Permission;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Properties;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.spi.InitialContextFactory;
+
+import junit.framework.Test;
+
+import org.jboss.beans.metadata.api.annotations.Inject;
+import org.jboss.beans.metadata.api.model.InjectOption;
+import org.jboss.naming.JndiPermission;
+import org.jboss.test.kernel.junit.MicrocontainerTest;
+import org.jnp.interfaces.NamingContext;
+import org.jnp.interfaces.TimedSocketFactory;
+import org.jnp.test.support.QueueSecurityManager;
+
+/**
+ * Test bootstraping the naming service using the mc
+ *
+ * @author Scott.Stark at jboss.org
+ * @version $Revision:$
+ */
+public class NamingMCUnitTest extends MicrocontainerTest
+{
+ public static Test suite()
+ {
+ return suite(NamingMCUnitTest.class);
+ }
+ /** */
+ private InitialContext ctx;
+ private QueueSecurityManager qsm;
+ private InitialContextFactory ctxFactory;
+
+ /**
+ *
+ * @param name
+ */
+ public NamingMCUnitTest(String name)
+ {
+ super(name, true);
+ }
+
+ /**
+ * Obtain the InitialContext from the InitialContextFactory bean ctx property.
+ * Each test expects an InitialContextFactory bean
+ * @see org.jboss.naming.InitialContextFactory
+ *
+ * @param ctx
+ */
+ @Inject(bean="InitialContextFactory", property="ctx")
+ public void setInitialContext(InitialContext ctx)
+ {
+ this.ctx = ctx;
+ }
+ @Inject(bean="QueueSecurityManager", option=InjectOption.OPTIONAL)
+ public void setQueueSecurityManager(QueueSecurityManager qsm)
+ {
+ this.qsm = qsm;
+ }
+ @Inject(bean="InitialContextFactory#3", option=InjectOption.OPTIONAL)
+ public void setCtxFactory(InitialContextFactory ctxFactory)
+ {
+ this.ctxFactory = ctxFactory;
+ }
+
+ /**
+ * Validate that a NamingBeanImpl mc bean is accessible via the
+ * LocalOnlyContextFactory
+ *
+ * @throws Exception
+ */
+ public void testLocaNamingBeanImpl()
+ throws Exception
+ {
+ assertNotNull(ctx);
+ validateCtx(ctx);
+ }
+ /**
+ * Validate that the NamingBeanImpl mc bean is accessible via the
+ * InitialContext(env) using the LocalOnlyContextFactory
+ * @throws Exception
+ */
+ public void testLocaNamingBeanImplViaInitialContextFactory()
+ throws Exception
+ {
+ Properties env = new Properties();
+ env.setProperty("java.naming.factory.initial", "org.jnp.interfaces.LocalOnlyContextFactory");
+ env.setProperty("java.naming.factory.url", "org.jboss.naming:org.jnp.interfaces");
+ InitialContext ic = new InitialContext(env);
+ validateCtx(ic);
+ }
+
+ /**
+ * Validate that a SingletonNamingServer mc bean is accessible via the
+ * LocalOnlyContextFactory
+ *
+ * @throws Exception
+ */
+ public void testSingletonNamingServer()
+ throws Exception
+ {
+ assertNotNull(ctx);
+ validateCtx(ctx);
+ }
+
+ /**
+ * Test the org.jnp.server.Main bean that wraps a NamingBean with remote
+ * access via an rmi proxy
+ *
+ * @throws Exception
+ */
+ public void testMainBean()
+ throws Exception
+ {
+ Properties env = new Properties();
+ env.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
+ env.setProperty("java.naming.provider.url", "localhost:1099");
+ env.setProperty("java.naming.factory.url", "org.jboss.naming:org.jnp.interfaces");
+ env.setProperty(TimedSocketFactory.JNP_TIMEOUT, "10000");
+ env.setProperty(TimedSocketFactory.JNP_SO_TIMEOUT, "10000");
+ InitialContext ic = new InitialContext(env);
+ validateCtx(ic);
+ }
+ /**
+ * Test the org.jnp.server.Main bean that wraps a NamingBean with remote
+ * access via an rmi proxy using custom socket factories
+ *
+ * @throws Exception
+ */
+ public void testMainBeanSFs()
+ throws Exception
+ {
+ InetAddress localAddr = InetAddress.getLocalHost();
+ getLog().debug("InetAddress.getLocalHost(): "+localAddr);
+ Properties env = new Properties();
+ env.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
+ env.setProperty("java.naming.provider.url", "localhost:2099");
+ env.setProperty("java.naming.factory.url", "org.jboss.naming:org.jnp.interfaces");
+ env.setProperty(TimedSocketFactory.JNP_TIMEOUT, "1000");
+ env.setProperty(TimedSocketFactory.JNP_SO_TIMEOUT, "1000");
+ InitialContext ic = new InitialContext(env);
+ validateCtx(ic);
+ }
+
+ /**
+ * Test two Naming instances with one LocalOnlyContextFactory using
+ * the NamingContext.local instance, and the other using the non-global
+ * Naming instance that was injected.
+ * @throws Exception
+ */
+ public void testMultipleLocalOnlyContextFactory()
+ throws Exception
+ {
+ // The InitialContextFactory
+ assertNotNull(ctx);
+ validateCtx(ctx);
+
+ // The InitialContextFactory#2
+ Properties env = new Properties();
+ env.setProperty("java.naming.factory.initial", "org.jnp.interfaces.LocalOnlyContextFactory");
+ env.setProperty("java.naming.factory.url", "org.jboss.naming:org.jnp.interfaces");
+ env.setProperty(NamingContext.JNP_NAMING_INSTANCE_NAME, "testLocaNamingBeanImpl#2");
+ InitialContext ic = new InitialContext(env);
+
+ // Validate the second naming context bindings created by JndiBindings#2
+ Integer i2 = (Integer) ic.lookup("ints/2");
+ assertEquals("ints/1", new Integer(2), i2);
+ String s2 = (String) ic.lookup("strings/2");
+ assertEquals("strings/2", "String2", s2);
+ BigInteger bi2 = (BigInteger) ic.lookup("bigint/2");
+ assertEquals("bigint/2", new BigInteger("987654321"), bi2);
+ Properties envp = (Properties) ic.lookup("env-props");
+ Properties expected = new Properties();
+ expected.setProperty("java.naming.factory.initial", "org.jnp.interfaces.LocalOnlyContextFactory#2");
+ expected.setProperty("java.naming.factory.url", "factory#2");
+ assertEquals("env-props", expected, envp);
+
+ // The InitialContextFactory#3
+ assertNotNull(ctxFactory);
+ // Validate the third naming context bindings created by JndiBindings#3
+ Context ctx3 = ctxFactory.getInitialContext(null);
+ Integer i3 = (Integer) ctx3.lookup("ints/3");
+ assertEquals("ints/1", new Integer(3), i3);
+ String s3 = (String) ctx3.lookup("strings/3");
+ assertEquals("strings/3", "String3", s3);
+ BigInteger bi3 = (BigInteger) ctx3.lookup("bigint/3");
+ assertEquals("bigint/2", new BigInteger("333333333"), bi3);
+ Properties envp3 = (Properties) ctx3.lookup("env-props");
+ Properties expected3 = new Properties();
+ expected3.setProperty("java.naming.factory.initial", "org.jnp.interfaces.LocalOnlyContextFactory#3");
+ expected3.setProperty("java.naming.factory.url", "factory#3");
+ assertEquals("env-props", expected3, envp3);
+ }
+
+ public void testInjectedSecurityManager()
+ throws Exception
+ {
+ qsm.clearPerms();
+
+ HashSet<JndiPermission> expectedPerms = new HashSet<JndiPermission>();
+ // expected doOps() permissions
+ expectedPerms.add(new JndiPermission("path1", "createSubcontext"));
+ expectedPerms.add(new JndiPermission("path1", "lookup"));
+ expectedPerms.add(new JndiPermission("path1", "list"));
+ expectedPerms.add(new JndiPermission("path1", "listBindings"));
+ expectedPerms.add(new JndiPermission("path1/x", "bind"));
+ expectedPerms.add(new JndiPermission("path1/x", "rebind"));
+ expectedPerms.add(new JndiPermission("path1/x", "unbind"));
+ expectedPerms.add(new JndiPermission("path1", "unbind"));
+ SecurityUtil.doOps(ctx);
+ // expected doBadOps() permissions
+ expectedPerms.add(new JndiPermission("path2", "createSubcontext"));
+ expectedPerms.add(new JndiPermission("path1x", "createSubcontext"));
+ expectedPerms.add(new JndiPermission("path1x", "rebind"));
+ expectedPerms.add(new JndiPermission("path1x", "lookup"));
+ expectedPerms.add(new JndiPermission("path1x", "list"));
+ expectedPerms.add(new JndiPermission("path1x", "listBindings"));
+ expectedPerms.add(new JndiPermission("path1x/x", "bind"));
+ expectedPerms.add(new JndiPermission("path1x/x", "rebind"));
+ expectedPerms.add(new JndiPermission("path1x", "unbind"));
+ SecurityUtil.doBadOps(ctx, false);
+
+ List<Permission> perms = qsm.getPerms();
+ for(Permission p : perms)
+ {
+ if(p instanceof JndiPermission)
+ {
+ System.out.println(p);
+ assertTrue(p+" is in expectedPerms", expectedPerms.contains(p));
+ }
+ }
+ }
+
+ /**
+ *
+ * @param ic
+ * @throws Exception
+ */
+ protected void validateCtx(InitialContext ic)
+ throws Exception
+ {
+ Integer i1 = (Integer) ic.lookup("ints/1");
+ assertEquals("ints/1", new Integer(1), i1);
+ String s1 = (String) ic.lookup("strings/1");
+ assertEquals("strings/1", "String1", s1);
+ BigInteger bi1 = (BigInteger) ic.lookup("bigint/1");
+ assertEquals("bigint/1", new BigInteger("123456789"), bi1);
+ Properties env = (Properties) ic.lookup("env-props");
+ Properties expected = new Properties();
+ expected.setProperty("java.naming.factory.initial", "org.jnp.interfaces.LocalOnlyContextFactory");
+ expected.setProperty("java.naming.factory.url", "org.jboss.naming:org.jnp.interfaces");
+ assertEquals("env-props", expected, env);
+ }
+}
Deleted: projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingServerSecurityManagerUnitTest.java
===================================================================
--- projects/naming/trunk/jnpserver/src/test/java/org/jnp/test/NamingServerSecurityManagerUnitTest.java 2008-11-05 04:14:24 UTC (rev 80546)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingServerSecurityManagerUnitTest.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -1,274 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jnp.test;
-
-import java.io.FilePermission;
-import java.io.SerializablePermission;
-import java.lang.reflect.ReflectPermission;
-import java.security.AccessControlException;
-import java.security.Permission;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Properties;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-
-import junit.framework.TestCase;
-
-import org.jboss.naming.JndiPermission;
-import org.jnp.server.ExecutorEventMgr;
-import org.jnp.server.NamingBeanImpl;
-import org.jnp.test.support.QueueSecurityManager;
-import org.jnp.test.support.TestSecurityManager;
-
-/**
- * Test using the NamingServer with a SecurityManager
- *
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-public class NamingServerSecurityManagerUnitTest extends TestCase
-{
- /** The actual namingMain service impl bean */
- private NamingBeanImpl namingBean;
- private InitialContext ic;
-
- @Override
- protected void setUp() throws Exception
- {
- System.out.println("+++ setUp, creating NamingBean");
- namingBean = new NamingBeanImpl();
- namingBean.setInstallGlobalService(true);
- namingBean.setUseGlobalService(false);
- namingBean.setEventMgr(new ExecutorEventMgr());
- namingBean.start();
-
-
- Properties env = new Properties();
- env.setProperty("java.naming.factory.initial", "org.jnp.interfaces.LocalOnlyContextFactory");
- env.setProperty("java.naming.factory.url.pkgs", "org.jnp.interfaces");
- ic = new InitialContext(env);
- }
- protected void tearDown()
- {
- System.setSecurityManager(null);
- }
-
- /**
- * Test that the expected JndiPermission are passed to the SecurityManager
- * @throws Exception
- */
- public void testOpPermissions()
- throws Exception
- {
- QueueSecurityManager qsm = new QueueSecurityManager();
- qsm.clearPerms();
- System.setSecurityManager(qsm);
-
- HashSet<JndiPermission> expectedPerms = new HashSet<JndiPermission>();
- // expected doOps() permissions
- expectedPerms.add(new JndiPermission("path1", "createSubcontext"));
- expectedPerms.add(new JndiPermission("path1", "lookup"));
- expectedPerms.add(new JndiPermission("path1", "list"));
- expectedPerms.add(new JndiPermission("path1", "listBindings"));
- expectedPerms.add(new JndiPermission("path1/x", "bind"));
- expectedPerms.add(new JndiPermission("path1/x", "rebind"));
- expectedPerms.add(new JndiPermission("path1/x", "unbind"));
- expectedPerms.add(new JndiPermission("path1", "unbind"));
- doOps();
- // expected doBadOps() permissions
- expectedPerms.add(new JndiPermission("path2", "createSubcontext"));
- expectedPerms.add(new JndiPermission("path1x", "createSubcontext"));
- expectedPerms.add(new JndiPermission("path1x", "rebind"));
- expectedPerms.add(new JndiPermission("path1x", "lookup"));
- expectedPerms.add(new JndiPermission("path1x", "list"));
- expectedPerms.add(new JndiPermission("path1x", "listBindings"));
- expectedPerms.add(new JndiPermission("path1x/x", "bind"));
- expectedPerms.add(new JndiPermission("path1x/x", "rebind"));
- expectedPerms.add(new JndiPermission("path1x", "unbind"));
- doBadOps(false);
-
- List<Permission> perms = qsm.getPerms();
- for(Permission p : perms)
- {
- if(p instanceof JndiPermission)
- {
- System.out.println(p);
- assertTrue(p+" is in expectedPerms", expectedPerms.contains(p));
- }
- }
- }
-
- /**
- * Run with a TestSecurityManager that has a fixed set of allowed permissions
- * @throws Exception
- */
- public void testSecurityManager()
- throws Exception
- {
- TestSecurityManager tsm = new TestSecurityManager();
- /*
- The permissions that should be needed
- */
- tsm.addPermission(new JndiPermission("path1", "createSubcontext,lookup,list,listBindings,unbind"));
- tsm.addPermission(new JndiPermission("path1x", "createSubcontext,unbind"));
- tsm.addPermission(new JndiPermission("path1/*", "list,listBindings,lookup"));
- tsm.addPermission(new JndiPermission("path1/x", "bind,rebind,unbind"));
- tsm.addPermission(new RuntimePermission("setSecurityManager"));
- tsm.addPermission(new FilePermission("<<ALL FILES>>", "read"));
- tsm.addPermission(new RuntimePermission("createClassLoader"));
- tsm.addPermission(new ReflectPermission("suppressAccessChecks"));
- tsm.addPermission(new SerializablePermission("enableSubstitution"));
- System.setSecurityManager(tsm);
-
- doOps();
- doBadOps(true);
- }
-
- /**
- * Validate that the JndiPermission("<<ALL BINDINGS>>", "*") allows all
- * naming operations.
- *
- * @throws Exception
- */
- public void testAllPermission()
- throws Exception
- {
- TestSecurityManager tsm = new TestSecurityManager();
- tsm.addPermission(new JndiPermission("<<ALL BINDINGS>>", "*"));
- tsm.addPermission(new RuntimePermission("setSecurityManager"));
- tsm.addPermission(new FilePermission("<<ALL FILES>>", "read"));
- tsm.addPermission(new RuntimePermission("createClassLoader"));
- tsm.addPermission(new ReflectPermission("suppressAccessChecks"));
- tsm.addPermission(new SerializablePermission("enableSubstitution"));
- System.setSecurityManager(tsm);
-
- doOps();
- doBadOps(false);
- }
-
- /**
- * Naming ops that should succeed.
- * @throws Exception
- */
- protected void doOps()
- throws Exception
- {
- ic.createSubcontext("path1");
- Object p1 = ic.lookup("path1");
- ic.list("path1");
- ic.listBindings("path1");
- ic.bind("path1/x", "x.bind");
- ic.rebind("path1/x", "x.rebind");
- ic.unbind("path1/x");
- ic.unbind("path1");
- }
- /**
- * Naming ops that should fail.
- * @throws Exception
- */
- protected void doBadOps(boolean expectFailure)
- throws Exception
- {
- try
- {
- ic.createSubcontext("path2");
- if(expectFailure)
- fail("Was able to create path2 subcontext");
- }
- catch(AccessControlException e)
- {
- System.out.println(e);
- }
- Context path1x = ic.createSubcontext("path1x");
- try
- {
- if(expectFailure)
- {
- ic.rebind("path1x", "path1x.rebind");
- fail("Was able to rebind path1x subcontext");
- }
- }
- catch(AccessControlException e)
- {
- System.out.println(e);
- }
-
- try
- {
- ic.lookup("path1x");
- if(expectFailure)
- fail("Was able to lookup path1x subcontext");
- }
- catch(AccessControlException e)
- {
- System.out.println(e);
- }
-
- try
- {
- ic.list("path1x");
- if(expectFailure)
- fail("Was able to list path1x subcontext");
- }
- catch(AccessControlException e)
- {
- System.out.println(e);
- }
-
- try
- {
- ic.listBindings("path1x");
- if(expectFailure)
- fail("Was able to listBindings path1x subcontext");
- }
- catch(AccessControlException e)
- {
- System.out.println(e);
- }
-
- try
- {
- ic.bind("path1x/x", "x.bind");
- if(expectFailure)
- fail("Was able to bind path1x/x");
- }
- catch(AccessControlException e)
- {
- System.out.println(e);
- }
-
- try
- {
- ic.rebind("path1x/x", "x.rebind");
- if(expectFailure)
- fail("Was able to rebind path1x/x");
- }
- catch(AccessControlException e)
- {
- System.out.println(e);
- }
-
- ic.unbind("path1x");
- }
-}
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingServerSecurityManagerUnitTest.java (from rev 80561, projects/naming/trunk/jnpserver/src/test/java/org/jnp/test/NamingServerSecurityManagerUnitTest.java)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingServerSecurityManagerUnitTest.java (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/NamingServerSecurityManagerUnitTest.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,178 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jnp.test;
+
+import java.io.FilePermission;
+import java.io.SerializablePermission;
+import java.lang.reflect.ReflectPermission;
+import java.security.Permission;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Properties;
+
+import javax.naming.InitialContext;
+
+import junit.framework.TestCase;
+
+import org.jboss.naming.JndiPermission;
+import org.jnp.server.ExecutorEventMgr;
+import org.jnp.server.NamingBeanImpl;
+import org.jnp.test.support.QueueSecurityManager;
+import org.jnp.test.support.TestSecurityManager;
+
+/**
+ * Test using the NamingServer with a SecurityManager
+ *
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public class NamingServerSecurityManagerUnitTest extends TestCase
+{
+ /** The actual namingMain service impl bean */
+ private NamingBeanImpl namingBean;
+ private InitialContext ic;
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ System.out.println("+++ setUp, creating NamingBean");
+ namingBean = new NamingBeanImpl();
+ namingBean.setInstallGlobalService(true);
+ namingBean.setUseGlobalService(false);
+ namingBean.setEventMgr(new ExecutorEventMgr());
+ namingBean.start();
+
+
+ Properties env = new Properties();
+ env.setProperty("java.naming.factory.initial", "org.jnp.interfaces.LocalOnlyContextFactory");
+ env.setProperty("java.naming.factory.url.pkgs", "org.jnp.interfaces");
+ ic = new InitialContext(env);
+ }
+ protected void tearDown()
+ {
+ System.setSecurityManager(null);
+ }
+
+ /**
+ * Test that the expected JndiPermission are passed to the SecurityManager
+ * @throws Exception
+ */
+ public void testOpPermissions()
+ throws Exception
+ {
+ QueueSecurityManager qsm = new QueueSecurityManager();
+ qsm.clearPerms();
+ System.setSecurityManager(qsm);
+
+ HashSet<JndiPermission> expectedPerms = new HashSet<JndiPermission>();
+ // expected doOps() permissions
+ expectedPerms.add(new JndiPermission("path1", "createSubcontext"));
+ expectedPerms.add(new JndiPermission("path1", "lookup"));
+ expectedPerms.add(new JndiPermission("path1", "list"));
+ expectedPerms.add(new JndiPermission("path1", "listBindings"));
+ expectedPerms.add(new JndiPermission("path1/x", "bind"));
+ expectedPerms.add(new JndiPermission("path1/x", "rebind"));
+ expectedPerms.add(new JndiPermission("path1/x", "unbind"));
+ expectedPerms.add(new JndiPermission("path1", "unbind"));
+ doOps();
+ // expected doBadOps() permissions
+ expectedPerms.add(new JndiPermission("path2", "createSubcontext"));
+ expectedPerms.add(new JndiPermission("path1x", "createSubcontext"));
+ expectedPerms.add(new JndiPermission("path1x", "rebind"));
+ expectedPerms.add(new JndiPermission("path1x", "lookup"));
+ expectedPerms.add(new JndiPermission("path1x", "list"));
+ expectedPerms.add(new JndiPermission("path1x", "listBindings"));
+ expectedPerms.add(new JndiPermission("path1x/x", "bind"));
+ expectedPerms.add(new JndiPermission("path1x/x", "rebind"));
+ expectedPerms.add(new JndiPermission("path1x", "unbind"));
+ doBadOps(false);
+
+ List<Permission> perms = qsm.getPerms();
+ for(Permission p : perms)
+ {
+ if(p instanceof JndiPermission)
+ {
+ System.out.println(p);
+ assertTrue(p+" is in expectedPerms", expectedPerms.contains(p));
+ }
+ }
+ }
+
+ /**
+ * Run with a TestSecurityManager that has a fixed set of allowed permissions
+ * @throws Exception
+ */
+ public void testSecurityManager()
+ throws Exception
+ {
+ TestSecurityManager tsm = new TestSecurityManager();
+ /*
+ The permissions that should be needed
+ */
+ tsm.addPermission(new JndiPermission("path1", "createSubcontext,lookup,list,listBindings,unbind"));
+ tsm.addPermission(new JndiPermission("path1x", "createSubcontext,unbind"));
+ tsm.addPermission(new JndiPermission("path1/*", "list,listBindings,lookup"));
+ tsm.addPermission(new JndiPermission("path1/x", "bind,rebind,unbind"));
+ tsm.addPermission(new RuntimePermission("setSecurityManager"));
+ tsm.addPermission(new FilePermission("<<ALL FILES>>", "read"));
+ tsm.addPermission(new RuntimePermission("createClassLoader"));
+ tsm.addPermission(new ReflectPermission("suppressAccessChecks"));
+ tsm.addPermission(new SerializablePermission("enableSubstitution"));
+ System.setSecurityManager(tsm);
+
+ doOps();
+ doBadOps(true);
+ }
+
+ /**
+ * Validate that the JndiPermission("<<ALL BINDINGS>>", "*") allows all
+ * naming operations.
+ *
+ * @throws Exception
+ */
+ public void testAllPermission()
+ throws Exception
+ {
+ TestSecurityManager tsm = new TestSecurityManager();
+ tsm.addPermission(new JndiPermission("<<ALL BINDINGS>>", "*"));
+ tsm.addPermission(new RuntimePermission("setSecurityManager"));
+ tsm.addPermission(new FilePermission("<<ALL FILES>>", "read"));
+ tsm.addPermission(new RuntimePermission("createClassLoader"));
+ tsm.addPermission(new ReflectPermission("suppressAccessChecks"));
+ tsm.addPermission(new SerializablePermission("enableSubstitution"));
+ System.setSecurityManager(tsm);
+
+ doOps();
+ doBadOps(false);
+ }
+
+ protected void doOps()
+ throws Exception
+ {
+ SecurityUtil.doOps(ic);
+ }
+ protected void doBadOps(boolean expectFailure)
+ throws Exception
+ {
+ SecurityUtil.doBadOps(ic, expectFailure);
+ }
+}
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/SecurityUtil.java (from rev 80561, projects/naming/trunk/jnpserver/src/test/java/org/jnp/test/SecurityUtil.java)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/SecurityUtil.java (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/test/java/org/jnp/test/SecurityUtil.java 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,146 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jnp.test;
+
+import java.security.AccessControlException;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+
+import junit.framework.AssertionFailedError;
+
+/**
+ * @author Scott.Stark at jboss.org
+ * @version $Revision:$
+ */
+public class SecurityUtil
+{
+ /**
+ * Naming ops that should succeed.
+ * @throws Exception
+ */
+ static void doOps(InitialContext ic)
+ throws Exception
+ {
+ ic.createSubcontext("path1");
+ Object p1 = ic.lookup("path1");
+ ic.list("path1");
+ ic.listBindings("path1");
+ ic.bind("path1/x", "x.bind");
+ ic.rebind("path1/x", "x.rebind");
+ ic.unbind("path1/x");
+ ic.unbind("path1");
+ }
+ /**
+ * Naming ops that should fail.
+ * @throws Exception
+ */
+ static void doBadOps(InitialContext ic, boolean expectFailure)
+ throws Exception
+ {
+ try
+ {
+ ic.createSubcontext("path2");
+ if(expectFailure)
+ fail("Was able to create path2 subcontext");
+ }
+ catch(AccessControlException e)
+ {
+ System.out.println(e);
+ }
+ Context path1x = ic.createSubcontext("path1x");
+ try
+ {
+ if(expectFailure)
+ {
+ ic.rebind("path1x", "path1x.rebind");
+ fail("Was able to rebind path1x subcontext");
+ }
+ }
+ catch(AccessControlException e)
+ {
+ System.out.println(e);
+ }
+
+ try
+ {
+ ic.lookup("path1x");
+ if(expectFailure)
+ fail("Was able to lookup path1x subcontext");
+ }
+ catch(AccessControlException e)
+ {
+ System.out.println(e);
+ }
+
+ try
+ {
+ ic.list("path1x");
+ if(expectFailure)
+ fail("Was able to list path1x subcontext");
+ }
+ catch(AccessControlException e)
+ {
+ System.out.println(e);
+ }
+
+ try
+ {
+ ic.listBindings("path1x");
+ if(expectFailure)
+ fail("Was able to listBindings path1x subcontext");
+ }
+ catch(AccessControlException e)
+ {
+ System.out.println(e);
+ }
+
+ try
+ {
+ ic.bind("path1x/x", "x.bind");
+ if(expectFailure)
+ fail("Was able to bind path1x/x");
+ }
+ catch(AccessControlException e)
+ {
+ System.out.println(e);
+ }
+
+ try
+ {
+ ic.rebind("path1x/x", "x.rebind");
+ if(expectFailure)
+ fail("Was able to rebind path1x/x");
+ }
+ catch(AccessControlException e)
+ {
+ System.out.println(e);
+ }
+
+ ic.unbind("path1x");
+ }
+
+ static void fail(String message)
+ {
+ throw new AssertionFailedError(message);
+ }
+}
Deleted: projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/log4j.xml
===================================================================
--- projects/naming/trunk/jnpserver/src/test/resources/log4j.xml 2008-11-05 04:14:24 UTC (rev 80546)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/log4j.xml 2008-11-06 00:53:21 UTC (rev 80569)
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
-
-<!-- $Id$ -->
-
-<!--
- | For more configuration infromation and examples see the Jakarta Log4j
- | owebsite: http://jakarta.apache.org/log4j
--->
-
-<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
-
- <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
- <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
- <param name="Target" value="System.out"/>
-
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%-5p %d{dd-MM HH:mm:ss,SSS} (%F:%M:%L) -%m%n"/>
- </layout>
- </appender>
-
- <category name="org.jnp.server">
- <priority value="TRACE"/>
- </category>
-
- <root>
- <appender-ref ref="CONSOLE"/>
- </root>
-
-</log4j:configuration>
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/log4j.xml (from rev 80561, projects/naming/trunk/jnpserver/src/test/resources/log4j.xml)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/log4j.xml (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/log4j.xml 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
+
+<!-- $Id$ -->
+
+<!--
+ | For more configuration infromation and examples see the Jakarta Log4j
+ | owebsite: http://jakarta.apache.org/log4j
+-->
+
+<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
+
+ <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
+ <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
+ <param name="Target" value="System.out"/>
+
+ <layout class="org.apache.log4j.PatternLayout">
+ <param name="ConversionPattern" value="%-5p %d{dd-MM HH:mm:ss,SSS} (%F:%M:%L) -%m%n"/>
+ </layout>
+ </appender>
+
+ <category name="org.jnp">
+ <priority value="TRACE"/>
+ </category>
+
+ <root>
+ <appender-ref ref="CONSOLE"/>
+ </root>
+
+</log4j:configuration>
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/org/jnp/test/NamingMCUnitTest#testInjectedSecurityManager.xml (from rev 80561, projects/naming/trunk/jnpserver/src/test/resources/org/jnp/test/NamingMCUnitTest#testInjectedSecurityManager.xml)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/org/jnp/test/NamingMCUnitTest#testInjectedSecurityManager.xml (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/org/jnp/test/NamingMCUnitTest#testInjectedSecurityManager.xml 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,70 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<deployment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="urn:jboss:bean-deployer bean-deployer_2_0.xsd"
+ xmlns="urn:jboss:bean-deployer:2.0">
+
+ <bean name="InitialContextFactory" class="org.jboss.naming.InitialContextFactoryBean">
+ <property name="env">
+ <map class="java.util.Properties" keyClass="java.lang.String" valueClass="java.lang.String">
+ <entry>
+ <key>java.naming.factory.initial</key>
+ <value>org.jnp.interfaces.LocalOnlyContextFactory</value>
+ </entry>
+ <entry>
+ <key>java.naming.factory.url</key>
+ <value>org.jboss.naming:org.jnp.interfaces</value>
+ </entry>
+ </map>
+ </property>
+ <depends>testInjectedSecurityManager</depends>
+ </bean>
+ <bean name="JndiBindings" class="org.jboss.naming.BindingsInitializer">
+ <property name="ctx">
+ <inject bean="InitialContextFactory" property="ctx"/>
+ </property>
+ <property name="bindings">
+ <map keyClass="java.lang.String">
+ <entry>
+ <key>ints/1</key>
+ <value class="java.lang.Integer">1</value>
+ </entry>
+ <entry>
+ <key>strings/1</key>
+ <value class="java.lang.String">String1</value>
+ </entry>
+ <entry>
+ <key>bigint/1</key>
+ <value class="java.math.BigInteger">123456789</value>
+ </entry>
+ <entry>
+ <key>env-props</key>
+ <value>
+ <map class="java.util.Properties" keyClass="java.lang.String" valueClass="java.lang.String">
+ <entry>
+ <key>java.naming.factory.initial</key>
+ <value>org.jnp.interfaces.LocalOnlyContextFactory</value>
+ </entry>
+ <entry>
+ <key>java.naming.factory.url</key>
+ <value>org.jboss.naming:org.jnp.interfaces</value>
+ </entry>
+ </map>
+ </value>
+ </entry>
+ </map>
+ </property>
+ </bean>
+
+ <bean name="QueueSecurityManager" class="org.jnp.test.support.QueueSecurityManager">
+
+ </bean>
+
+ <bean name="testInjectedSecurityManager" class="org.jnp.server.NamingBeanImpl">
+ <!-- Install this bean as the global JVM NamingServer -->
+ <property name="installGlobalService">true</property>
+ <property name="useGlobalService">false</property>
+ <!-- Set the SecurityManager to use -->
+ <property name="securityMgr"><inject bean="QueueSecurityManager"/></property>
+ </bean>
+</deployment>
Copied: projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/org/jnp/test/NamingMCUnitTest#testMultipleLocalOnlyContextFactory.xml (from rev 80558, projects/naming/trunk/jnpserver/src/test/resources/org/jnp/test/NamingMCUnitTest#testMultipleLocalOnlyContextFactory.xml)
===================================================================
--- projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/org/jnp/test/NamingMCUnitTest#testMultipleLocalOnlyContextFactory.xml (rev 0)
+++ projects/naming/branches/Branch_5_0/jnpserver/src/test/resources/org/jnp/test/NamingMCUnitTest#testMultipleLocalOnlyContextFactory.xml 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,183 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<deployment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="urn:jboss:bean-deployer bean-deployer_2_0.xsd"
+ xmlns="urn:jboss:bean-deployer:2.0">
+
+ <!-- An InitialContextFactory that uses the NamingContext.getLocal() Naming -->
+ <bean name="InitialContextFactory#1" class="org.jboss.naming.InitialContextFactoryBean">
+ <alias>InitialContextFactory</alias>
+ <property name="env">
+ <map class="java.util.Properties" keyClass="java.lang.String" valueClass="java.lang.String">
+ <entry>
+ <key>java.naming.factory.initial</key>
+ <value>org.jnp.interfaces.LocalOnlyContextFactory</value>
+ </entry>
+ <entry>
+ <key>java.naming.factory.url</key>
+ <value>org.jboss.naming:org.jnp.interfaces</value>
+ </entry>
+ </map>
+ </property>
+ <depends>testLocaNamingBeanImpl#1</depends>
+ </bean>
+ <!-- An InitialContextFactory that uses the env jnp.namingInstanceName Naming -->
+ <bean name="InitialContextFactory#2" class="org.jboss.naming.InitialContextFactoryBean">
+ <property name="env">
+ <map class="java.util.Properties" keyClass="java.lang.String" valueClass="java.lang.String">
+ <entry>
+ <key>java.naming.factory.initial</key>
+ <value>org.jnp.interfaces.LocalOnlyContextFactory</value>
+ </entry>
+ <entry>
+ <key>java.naming.factory.url</key>
+ <value>org.jboss.naming:org.jnp.interfaces</value>
+ </entry>
+ <entry>
+ <key>jnp.namingInstance</key>
+ <value><inject bean="testLocaNamingBeanImpl#2" property="namingInstance"/></value>
+ </entry>
+ <entry>
+ <key>jnp.namingInstanceName</key>
+ <value>testLocaNamingBeanImpl#2</value>
+ </entry>
+ </map>
+ </property>
+ <depends>testLocaNamingBeanImpl#2</depends>
+ </bean>
+ <!-- An InitialContextFactory that uses the testLocaNamingBeanImpl#2 Naming bean -->
+ <bean name="InitialContextFactory#3" class="org.jnp.interfaces.LocalOnlyContextFactory">
+ <property name="naming"><inject bean="testLocaNamingBeanImpl#3" property="namingInstance"/></property>
+ </bean>
+ <bean name="InitialContext#3" class="javax.naming.InitialContext">
+ <constructor factoryMethod="getInitialContext">
+ <factory bean="InitialContextFactory#3"/>
+ <parameter><null/></parameter>
+ </constructor>
+ </bean>
+
+ <bean name="JndiBindings#1" class="org.jboss.naming.BindingsInitializer">
+ <property name="ctx">
+ <inject bean="InitialContextFactory#1" property="ctx"/>
+ </property>
+ <property name="bindings">
+ <map keyClass="java.lang.String">
+ <entry>
+ <key>ints/1</key>
+ <value class="java.lang.Integer">1</value>
+ </entry>
+ <entry>
+ <key>strings/1</key>
+ <value class="java.lang.String">String1</value>
+ </entry>
+ <entry>
+ <key>bigint/1</key>
+ <value class="java.math.BigInteger">123456789</value>
+ </entry>
+ <entry>
+ <key>env-props</key>
+ <value>
+ <map class="java.util.Properties" keyClass="java.lang.String" valueClass="java.lang.String">
+ <entry>
+ <key>java.naming.factory.initial</key>
+ <value>org.jnp.interfaces.LocalOnlyContextFactory</value>
+ </entry>
+ <entry>
+ <key>java.naming.factory.url</key>
+ <value>org.jboss.naming:org.jnp.interfaces</value>
+ </entry>
+ </map>
+ </value>
+ </entry>
+ </map>
+ </property>
+ </bean>
+ <bean name="JndiBindings#2" class="org.jboss.naming.BindingsInitializer">
+ <property name="ctx">
+ <inject bean="InitialContextFactory#2" property="ctx"/>
+ </property>
+ <property name="bindings">
+ <map keyClass="java.lang.String">
+ <entry>
+ <key>ints/2</key>
+ <value class="java.lang.Integer">2</value>
+ </entry>
+ <entry>
+ <key>strings/2</key>
+ <value class="java.lang.String">String2</value>
+ </entry>
+ <entry>
+ <key>bigint/2</key>
+ <value class="java.math.BigInteger">987654321</value>
+ </entry>
+ <entry>
+ <key>env-props</key>
+ <value>
+ <map class="java.util.Properties" keyClass="java.lang.String" valueClass="java.lang.String">
+ <entry>
+ <key>java.naming.factory.initial</key>
+ <value>org.jnp.interfaces.LocalOnlyContextFactory#2</value>
+ </entry>
+ <entry>
+ <key>java.naming.factory.url</key>
+ <value>factory#2</value>
+ </entry>
+ </map>
+ </value>
+ </entry>
+ </map>
+ </property>
+ </bean>
+ <bean name="JndiBindings#3" class="org.jboss.naming.BindingsInitializer">
+ <property name="ctx">
+ <inject bean="InitialContext#3" />
+ </property>
+ <property name="bindings">
+ <map keyClass="java.lang.String">
+ <entry>
+ <key>ints/3</key>
+ <value class="java.lang.Integer">3</value>
+ </entry>
+ <entry>
+ <key>strings/3</key>
+ <value class="java.lang.String">String3</value>
+ </entry>
+ <entry>
+ <key>bigint/3</key>
+ <value class="java.math.BigInteger">333333333</value>
+ </entry>
+ <entry>
+ <key>env-props</key>
+ <value>
+ <map class="java.util.Properties" keyClass="java.lang.String" valueClass="java.lang.String">
+ <entry>
+ <key>java.naming.factory.initial</key>
+ <value>org.jnp.interfaces.LocalOnlyContextFactory#3</value>
+ </entry>
+ <entry>
+ <key>java.naming.factory.url</key>
+ <value>factory#3</value>
+ </entry>
+ </map>
+ </value>
+ </entry>
+ </map>
+ </property>
+ </bean>
+
+ <bean name="testLocaNamingBeanImpl#1" class="org.jnp.server.NamingBeanImpl">
+ <!-- Install this bean as the global JVM NamingServer -->
+ <property name="installGlobalService">true</property>
+ <property name="useGlobalService">false</property>
+ </bean>
+ <bean name="testLocaNamingBeanImpl#2" class="org.jnp.server.NamingBeanImpl">
+ <!-- Do not install this bean as the global JVM NamingServer -->
+ <property name="installGlobalService">false</property>
+ <property name="useGlobalService">false</property>
+ </bean>
+ <bean name="testLocaNamingBeanImpl#3" class="org.jnp.server.NamingBeanImpl">
+ <!-- Do not install this bean as the global JVM NamingServer -->
+ <property name="installGlobalService">false</property>
+ <property name="useGlobalService">false</property>
+ </bean>
+</deployment>
Deleted: projects/naming/branches/Branch_5_0/pom.xml
===================================================================
--- projects/naming/trunk/pom.xml 2008-11-05 04:14:24 UTC (rev 80546)
+++ projects/naming/branches/Branch_5_0/pom.xml 2008-11-06 00:53:21 UTC (rev 80569)
@@ -1,51 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- The parent maven for the jndi naming server project
-
- This pom aggregates the subproject pom
-
- To build this project maven 2 should be installed and in the system path. From the command line
- run "mvn" from the build directory and "install" will be used as the default goal. In order to use
- the "deploy" goal, the mvn.cvs.root should be specified in settings.xml.
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.jboss</groupId>
- <artifactId>jboss-parent</artifactId>
- <version>3</version>
- </parent>
- <groupId>org.jboss.naming</groupId>
- <artifactId>jboss-naming-build</artifactId>
- <version>5.0.0-SNAPSHOT</version>
- <packaging>pom</packaging>
- <name>JBoss Naming Build</name>
- <url>http://www.jboss.com/products/jbossmc</url>
- <description>
- The JBoss JNDI name server implementation.
- </description>
- <scm>
- <connection>scm:svn:https://svn.jboss.org/repos/jbossas/projects/naming/trunk</connection>
- </scm>
-
- <modules>
- <module>jnpserver</module>
- <module>jnpclient</module>
- </modules>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-release-plugin</artifactId>
- <version>2.0-beta-7</version>
- <configuration>
- <tagBase>https://svn.jboss.org/repos/jbossas/projects/naming/tags</tagBase>
- <autoVersionSubmodules>true</autoVersionSubmodules>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
-</project>
-
Copied: projects/naming/branches/Branch_5_0/pom.xml (from rev 80567, projects/naming/trunk/pom.xml)
===================================================================
--- projects/naming/branches/Branch_5_0/pom.xml (rev 0)
+++ projects/naming/branches/Branch_5_0/pom.xml 2008-11-06 00:53:21 UTC (rev 80569)
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ The parent maven for the jndi naming server project
+
+ This pom aggregates the subproject pom
+
+ To build this project maven 2 should be installed and in the system path. From the command line
+ run "mvn" from the build directory and "install" will be used as the default goal. In order to use
+ the "deploy" goal, the mvn.cvs.root should be specified in settings.xml.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.jboss</groupId>
+ <artifactId>jboss-parent</artifactId>
+ <version>3</version>
+ </parent>
+ <groupId>org.jboss.naming</groupId>
+ <artifactId>jboss-naming-build</artifactId>
+ <version>5.0.0-SNAPSHOT</version>
+ <packaging>pom</packaging>
+ <name>JBoss Naming Build</name>
+ <url>http://www.jboss.com/products/jbossmc</url>
+ <description>
+ The JBoss JNDI name server implementation.
+ </description>
+ <scm>
+ <connection>scm:svn:https://svn.jboss.org/repos/jbossas/projects/naming/branches/Branch_5_0</connection>
+ </scm>
+
+ <modules>
+ <module>jnpserver</module>
+ <module>jnpclient</module>
+ </modules>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-release-plugin</artifactId>
+ <version>2.0-beta-7</version>
+ <configuration>
+ <tagBase>https://svn.jboss.org/repos/jbossas/projects/naming/tags</tagBase>
+ <autoVersionSubmodules>true</autoVersionSubmodules>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
+
More information about the jboss-cvs-commits
mailing list