JBoss Remoting SVN: r4704 - in remoting3/trunk: core/src/main/java/org/jboss/remoting/core and 3 other directories.
by jboss-remoting-commits@lists.jboss.org
Author: david.lloyd(a)jboss.com
Date: 2008-11-19 10:47:10 -0500 (Wed, 19 Nov 2008)
New Revision: 4704
Added:
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/AtomicMap.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/CollectionUtil.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/ConcurrentReferenceHashMap.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/NamingThreadFactory.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/OrderedExecutor.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/OrderedExecutorFactory.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedCollection.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedIterator.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedMap.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedQueue.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedSet.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/WeakHashSet.java
Removed:
remoting3/trunk/util/
Modified:
remoting3/trunk/build.xml
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/AbstractContextImpl.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/EndpointImpl.java
remoting3/trunk/core/src/main/java/org/jboss/remoting/core/RequestListenerExecutor.java
remoting3/trunk/mc-deployers/src/main/java/org/jboss/remoting/metadata/EndpointMetaData.java
remoting3/trunk/mc-deployers/src/main/java/org/jboss/remoting/metadata/RemotingMetaData.java
remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/IntegerBiMap.java
remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/IntegerResourceBiMap.java
Log:
Remove util module
Modified: remoting3/trunk/build.xml
===================================================================
--- remoting3/trunk/build.xml 2008-11-19 15:28:09 UTC (rev 4703)
+++ remoting3/trunk/build.xml 2008-11-19 15:47:10 UTC (rev 4704)
@@ -365,7 +365,6 @@
<compilerarg value="-Xlint:unchecked"/>
<classpath>
<path refid="api.classpath"/>
- <path refid="util.classpath"/>
</classpath>
</javac>
<path id="compat.classpath">
@@ -378,7 +377,7 @@
<delete dir="compat/target"/>
</target>
- <target name="compat" description="Build the compat module" depends="api,util,compat.compile"/>
+ <target name="compat" description="Build the compat module" depends="api,compat.compile"/>
<!-- core module -->
@@ -404,7 +403,6 @@
<compilerarg value="-Xlint:unchecked"/>
<classpath>
<path refid="api.classpath"/>
- <path refid="util.classpath"/>
<path refid="version.classpath"/>
<pathelement location="${lib.marshalling-api.local}"/>
<pathelement location="${lib.xnio-api.local}"/>
@@ -436,7 +434,6 @@
<classpath>
<path refid="api.classpath"/>
<path refid="core.classpath"/>
- <path refid="util.classpath"/>
<path refid="testing-support.classpath"/>
<pathelement location="${lib.marshalling-api.local}"/>
<pathelement location="${lib.junit.local}"/>
@@ -463,7 +460,6 @@
<path refid="api.classpath"/>
<path refid="core.classpath"/>
<path refid="testing-support.classpath"/>
- <path refid="util.classpath"/>
<pathelement location="core/target/test/classes"/>
<pathelement location="${lib.junit.local}"/>
<pathelement location="${lib.marshalling-api.local}"/>
@@ -478,7 +474,7 @@
</junit>
</target>
- <target name="core.test" depends="api,core,testing-support,util,core.test.compile">
+ <target name="core.test" depends="api,core,testing-support,core.test.compile">
<antcall inheritall="true" inheritrefs="true" target="core.test.pseudotarget">
<param name="extension" value=".txt"/>
<param name="message" value="Running with no security manager"/>
@@ -495,7 +491,7 @@
<delete dir="core/target"/>
</target>
- <target name="core" description="Build the core module" depends="api,util,version,core.compile">
+ <target name="core" description="Build the core module" depends="api,version,core.compile">
<path id="core.classpath">
<pathelement location="core/target/main/classes"/>
</path>
@@ -526,7 +522,6 @@
<classpath>
<path refid="api.classpath"/>
<path refid="core.classpath"/>
- <path refid="util.classpath"/>
<pathelement location="${lib.jaxb-api.local}"/>
<pathelement location="${lib.jboss-common-logging-spi.local}"/>
<pathelement location="${lib.jboss-common-core.local}"/>
@@ -546,7 +541,7 @@
<delete dir="mc-deployers/target"/>
</target>
- <target name="mc-deployers" description="Build the mc-deployers module" depends="lib.jaxb-api,lib.jboss-common-core,lib.jboss-common-logging-spi,lib.jboss-deployers-core-spi,lib.jboss-deployers-spi,lib.jboss-deployers-structure-spi,lib.jbossmc-kernel,lib.jbossmc-dependency,lib.jboss-managed,lib.jbossxb,api,core,util,mc-deployers.compile">
+ <target name="mc-deployers" description="Build the mc-deployers module" depends="lib.jaxb-api,lib.jboss-common-core,lib.jboss-common-logging-spi,lib.jboss-deployers-core-spi,lib.jboss-deployers-spi,lib.jboss-deployers-structure-spi,lib.jbossmc-kernel,lib.jbossmc-dependency,lib.jboss-managed,lib.jbossxb,api,core,mc-deployers.compile">
<path id="mc-deployers.classpath">
<pathelement location="mc-deployers/target/main/classes"/>
</path>
@@ -577,7 +572,6 @@
<classpath>
<path refid="api.classpath"/>
<path refid="core.classpath"/>
- <path refid="util.classpath"/>
<pathelement location="${lib.marshalling-api.local}"/>
<pathelement location="${lib.xnio-api.local}"/>
</classpath>
@@ -609,7 +603,6 @@
<path refid="api.classpath"/>
<path refid="core.classpath"/>
<path refid="protocol.multiplex.classpath"/>
- <path refid="util.classpath"/>
<path refid="testing-support.classpath"/>
<pathelement location="${lib.junit.local}"/>
<pathelement location="${lib.marshalling-api.local}"/>
@@ -641,7 +634,6 @@
<path refid="core.classpath"/>
<path refid="protocol.multiplex.classpath"/>
<path refid="testing-support.classpath"/>
- <path refid="util.classpath"/>
<pathelement location="protocol/multiplex/target/test/classes"/>
<pathelement location="${lib.junit.local}"/>
<pathelement location="${lib.marshalling-api.local}"/>
@@ -658,7 +650,7 @@
</junit>
</target>
- <target name="protocol.multiplex.test" depends="lib.xnio-nio,api,core,protocol.multiplex,testing-support,util,protocol.multiplex.test.compile">
+ <target name="protocol.multiplex.test" depends="lib.xnio-nio,api,core,protocol.multiplex,testing-support,protocol.multiplex.test.compile">
<antcall inheritall="true" inheritrefs="true" target="protocol.multiplex.test.pseudotarget">
<param name="extension" value=".txt"/>
<param name="message" value="Running with no security manager"/>
@@ -675,7 +667,7 @@
<delete dir="protocol/multiplex/target"/>
</target>
- <target name="protocol.multiplex" description="Build the protocol.multiplex module" depends="lib.xnio-api,api,core,util,protocol.multiplex.compile">
+ <target name="protocol.multiplex" description="Build the protocol.multiplex module" depends="lib.xnio-api,api,core,protocol.multiplex.compile">
<path id="protocol.multiplex.classpath">
<pathelement location="protocol/multiplex/target/main/classes"/>
</path>
@@ -706,7 +698,6 @@
<classpath>
<path refid="api.classpath"/>
<path refid="core.classpath"/>
- <path refid="util.classpath"/>
<pathelement location="${lib.marshalling-api.local}"/>
<pathelement location="${lib.xnio-api.local}"/>
</classpath>
@@ -739,7 +730,6 @@
<path refid="core.classpath"/>
<path refid="protocol.basic.classpath"/>
<path refid="standalone.classpath"/>
- <path refid="util.classpath"/>
<path refid="testing-support.classpath"/>
<pathelement location="${lib.junit.local}"/>
<pathelement location="${lib.marshalling-api.local}"/>
@@ -772,7 +762,6 @@
<path refid="protocol.basic.classpath"/>
<path refid="standalone.classpath"/>
<path refid="testing-support.classpath"/>
- <path refid="util.classpath"/>
<pathelement location="protocol/basic/target/test/classes"/>
<pathelement location="${lib.junit.local}"/>
<pathelement location="${lib.marshalling-api.local}"/>
@@ -789,7 +778,7 @@
</junit>
</target>
- <target name="protocol.basic.test" depends="lib.river,lib.xnio-nio,api,core,protocol.basic,standalone,testing-support,util,protocol.basic.test.compile">
+ <target name="protocol.basic.test" depends="lib.river,lib.xnio-nio,api,core,protocol.basic,standalone,testing-support,protocol.basic.test.compile">
<antcall inheritall="true" inheritrefs="true" target="protocol.basic.test.pseudotarget">
<param name="extension" value=".txt"/>
<param name="message" value="Running with no security manager"/>
@@ -806,7 +795,7 @@
<delete dir="protocol/basic/target"/>
</target>
- <target name="protocol.basic" description="Build the protocol.basic module" depends="lib.xnio-api,api,core,util,protocol.basic.compile">
+ <target name="protocol.basic" description="Build the protocol.basic module" depends="lib.xnio-api,api,core,protocol.basic.compile">
<path id="protocol.basic.classpath">
<pathelement location="protocol/basic/target/main/classes"/>
</path>
@@ -837,7 +826,6 @@
<classpath>
<path refid="api.classpath"/>
<path refid="standalone.classpath"/>
- <path refid="util.classpath"/>
<pathelement location="${lib.xnio-api.local}"/>
</classpath>
</javac>
@@ -848,7 +836,7 @@
<delete dir="samples/target"/>
</target>
- <target name="samples" description="Build the samples module" depends="api,standalone,util,samples.compile">
+ <target name="samples" description="Build the samples module" depends="api,standalone,samples.compile">
<path id="samples.classpath">
<pathelement location="samples/target/main/classes"/>
</path>
@@ -879,7 +867,6 @@
<classpath>
<path refid="api.classpath"/>
<path refid="core.classpath"/>
- <path refid="util.classpath"/>
<pathelement location="${lib.xnio-api.local}"/>
</classpath>
</javac>
@@ -890,7 +877,7 @@
<delete dir="standalone/target"/>
</target>
- <target name="standalone" description="Build the standalone module" depends="lib.xnio-api,api,core,util,standalone.compile">
+ <target name="standalone" description="Build the standalone module" depends="lib.xnio-api,api,core,standalone.compile">
<path id="standalone.classpath">
<pathelement location="standalone/target/main/classes"/>
</path>
@@ -976,45 +963,6 @@
</path>
</target>
- <!-- Utility module -->
-
- <target name="util.compile.depcheck">
- <mkdir dir="util/target/main"/>
- <uptodate property="util.compile.uptodate" targetfile="util/target/main/.lastcompile">
- <srcfiles dir="util/src/main/java">
- <include name="**/"/>
- <include name="**/*.java"/>
- <exclude name="**/.*"/>
- </srcfiles>
- </uptodate>
- </target>
-
- <target name="util.compile" depends="util.compile.depcheck" unless="util.compile.uptodate">
- <mkdir dir="util/target/main/classes"/>
- <javac
- source="${javac.source}"
- target="${javac.target}"
- srcdir="util/src/main/java"
- destdir="util/target/main/classes"
- debug="true">
- <compilerarg value="-Xlint:unchecked"/>
- <classpath>
- <pathelement location="${lib.xnio-api.local}"/>
- </classpath>
- </javac>
- <touch file="util/target/main/.lastcompile" verbose="false"/>
- </target>
-
- <target name="util.clean">
- <delete dir="util/target"/>
- </target>
-
- <target name="util" description="Build the utilities module" depends="lib.xnio-api,util.compile">
- <path id="util.classpath">
- <pathelement location="util/target/main/classes"/>
- </path>
- </target>
-
<!-- version module -->
<target name="version.compile.depcheck">
@@ -1057,7 +1005,7 @@
<!-- JARS - Keep in alpha order by jar name -->
<!-- ============================================== -->
- <target name="api-jar" description="Build the API JAR" depends="api,transporter,util,version">
+ <target name="api-jar" description="Build the API JAR" depends="api,transporter,version">
<delete file="jboss-remoting-api.jar"/>
<jar jarfile="jboss-remoting-api.jar">
<manifest>
@@ -1103,7 +1051,7 @@
</jar>
</target>
- <target name="standalone-jar" description="Build the standalone JAR" depends="api,core,standalone,transporter,util,version">
+ <target name="standalone-jar" description="Build the standalone JAR" depends="api,core,standalone,transporter,version">
<delete file="jboss-remoting-standalone.jar"/>
<jar jarfile="jboss-remoting-standalone.jar">
<manifest>
@@ -1129,9 +1077,6 @@
<zipfileset dir="transporter/target/main/classes">
<include name="**/*.class"/>
</zipfileset>
- <zipfileset dir="util/target/main/classes">
- <include name="**/*.class"/>
- </zipfileset>
</jar>
</target>
@@ -1139,7 +1084,7 @@
<!-- JAVADOCS -->
<!-- ============================================== -->
- <target name="api-javadoc" depends="api,core,standalone,transporter,util,lib.apiviz,lib.marshalling-api,lib.xnio-api">
+ <target name="api-javadoc" depends="api,core,standalone,transporter,lib.apiviz,lib.marshalling-api,lib.xnio-api">
<delete dir="api/target/main/docs"/>
<mkdir dir="api/target/main/docs"/>
<javadoc destdir="api/target/main/docs" author="false" version="false" use="false" windowtitle="JBoss Remoting API">
@@ -1147,7 +1092,6 @@
<packageset dir="api/src/main/java"/>
<packageset dir="standalone/src/main/java"/>
<packageset dir="transporter/src/main/java"/>
- <packageset dir="util/src/main/java"/>
<doctitle><![CDATA[<h1>JBoss Remoting 3</h1>]]></doctitle>
<bottom><![CDATA[<i>Copyright © 2008 JBoss, a division of Red Hat, Inc.</i>]]></bottom>
<link href="http://java.sun.com/j2se/1.5.0/docs/api/"/>
@@ -1158,7 +1102,6 @@
<path refid="api.classpath"/>
<path refid="standalone.classpath"/>
<path refid="transporter.classpath"/>
- <path refid="util.classpath"/>
<pathelement location="${lib.xnio-api.local}"/>
<pathelement location="${lib.marshalling-api.local}"/>
</classpath>
@@ -1170,9 +1113,9 @@
<!-- core -->
- <target name="all-core" description="Build all core targets" depends="api,compat,core,mc-deployers,protocol.basic,protocol.multiplex,samples,standalone,testing-support,transporter,util"/>
+ <target name="all-core" description="Build all core targets" depends="api,compat,core,mc-deployers,protocol.basic,protocol.multiplex,samples,standalone,testing-support,transporter"/>
- <target name="clean-core" description="Clean all core targets" depends="api.clean,compat.clean,core.clean,mc-deployers.clean,protocol.basic.clean,protocol.multiplex.clean,samples.clean,standalone.clean,testing-support.clean,transporter.clean,util.clean"/>
+ <target name="clean-core" description="Clean all core targets" depends="api.clean,compat.clean,core.clean,mc-deployers.clean,protocol.basic.clean,protocol.multiplex.clean,samples.clean,standalone.clean,testing-support.clean,transporter.clean"/>
<!-- JARs: These should be the third-to-last targets in the file -->
Modified: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/AbstractContextImpl.java
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/AbstractContextImpl.java 2008-11-19 15:28:09 UTC (rev 4703)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/AbstractContextImpl.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -25,7 +25,7 @@
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import org.jboss.remoting.spi.AbstractHandleableCloseable;
-import org.jboss.remoting.util.CollectionUtil;
+import org.jboss.remoting.core.util.CollectionUtil;
/**
*
Modified: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/EndpointImpl.java
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/EndpointImpl.java 2008-11-19 15:28:09 UTC (rev 4703)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/EndpointImpl.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -22,13 +22,13 @@
import org.jboss.remoting.EndpointPermission;
import org.jboss.remoting.RemoteServiceConfiguration;
import org.jboss.remoting.ServiceURI;
+import org.jboss.remoting.core.util.OrderedExecutorFactory;
+import org.jboss.remoting.core.util.CollectionUtil;
+import org.jboss.remoting.core.util.NamingThreadFactory;
import org.jboss.remoting.spi.AbstractSimpleCloseable;
import org.jboss.remoting.spi.Handle;
import org.jboss.remoting.spi.RequestHandler;
import org.jboss.remoting.spi.RequestHandlerSource;
-import org.jboss.remoting.util.CollectionUtil;
-import org.jboss.remoting.util.NamingThreadFactory;
-import org.jboss.remoting.util.OrderedExecutorFactory;
import org.jboss.remoting.version.Version;
import org.jboss.xnio.FailedIoFuture;
import org.jboss.xnio.FinishedIoFuture;
Modified: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/RequestListenerExecutor.java
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/RequestListenerExecutor.java 2008-11-19 15:28:09 UTC (rev 4703)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/RequestListenerExecutor.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -24,7 +24,7 @@
import java.util.Set;
import java.util.concurrent.Executor;
-import org.jboss.remoting.util.CollectionUtil;
+import org.jboss.remoting.core.util.CollectionUtil;
/**
*
Copied: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/AtomicMap.java (from rev 4696, remoting3/trunk/util/src/main/java/org/jboss/remoting/util/AtomicMap.java)
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/AtomicMap.java (rev 0)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/AtomicMap.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -0,0 +1,108 @@
+package org.jboss.remoting.core.util;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * A delegating map implementation that accepts a standard {@code Map}, but conforms to the contract
+ * for {@code ConcurrentMap}. No synchronization is done on the delegate.
+ */
+public class AtomicMap<K, V> implements ConcurrentMap<K, V> {
+ private final Map<K, V> delegate;
+
+ public AtomicMap(final Map<K, V> delegate) {
+ this.delegate = delegate;
+ }
+
+ public int size() {
+ return delegate.size();
+ }
+
+ public boolean isEmpty() {
+ return delegate.isEmpty();
+ }
+
+ public boolean containsKey(final Object key) {
+ return delegate.containsKey(key);
+ }
+
+ public boolean containsValue(final Object value) {
+ return delegate.containsValue(value);
+ }
+
+ public V get(final Object key) {
+ return delegate.get(key);
+ }
+
+ public V put(final K key, final V value) {
+ return delegate.put(key, value);
+ }
+
+ public V remove(final Object key) {
+ return delegate.remove(key);
+ }
+
+ public void putAll(final Map<? extends K, ? extends V> t) {
+ delegate.putAll(t);
+ }
+
+ public void clear() {
+ delegate.clear();
+ }
+
+ public Set<K> keySet() {
+ return delegate.keySet();
+ }
+
+ public Collection<V> values() {
+ return delegate.values();
+ }
+
+ public Set<Entry<K, V>> entrySet() {
+ return delegate.entrySet();
+ }
+
+ public boolean equals(final Object o) {
+ return delegate.equals(o);
+ }
+
+ public int hashCode() {
+ return delegate.hashCode();
+ }
+
+ public V putIfAbsent(final K key, final V value) {
+ if (delegate.containsKey(key)) {
+ return delegate.get(key);
+ } else {
+ return delegate.put(key, value);
+ }
+ }
+
+ public boolean remove(final Object key, final Object value) {
+ if (delegate.containsKey(key) && (value == null && delegate.get(key) == null || delegate.get(key).equals(value))) {
+ delegate.remove(key);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean replace(final K key, final V oldValue, final V newValue) {
+ if (delegate.containsKey(key) && (oldValue == null ? delegate.get(key) == null : delegate.get(key).equals(oldValue))) {
+ delegate.put(key, newValue);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public V replace(final K key, final V value) {
+ if (delegate.containsKey(key)) {
+ return delegate.put(key, value);
+ } else {
+ return null;
+ }
+ }
+}
Copied: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/CollectionUtil.java (from rev 4696, remoting3/trunk/util/src/main/java/org/jboss/remoting/util/CollectionUtil.java)
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/CollectionUtil.java (rev 0)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/CollectionUtil.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -0,0 +1,722 @@
+package org.jboss.remoting.core.util;
+
+import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Queue;
+import java.util.Set;
+import java.util.WeakHashMap;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import static org.jboss.remoting.core.util.ConcurrentReferenceHashMap.ReferenceType.STRONG;
+import static org.jboss.remoting.core.util.ConcurrentReferenceHashMap.ReferenceType.WEAK;
+
+/**
+ * A set of helpful utility functions for collections.
+ */
+public final class CollectionUtil {
+ private CollectionUtil() {
+ }
+
+ /**
+ * Create an enum map for the given key type.
+ *
+ * @param keyType the key type
+ * @return the new map
+ */
+ public static <K extends Enum<K>, V> EnumMap<K, V> enumMap(Class<K> keyType) {
+ return new EnumMap<K, V>(keyType);
+ }
+
+ /**
+ * Create a concurrent map instance.
+ *
+ * @return a new concurrent map
+ */
+ public static <K, V> ConcurrentMap<K, V> concurrentMap() {
+ return new ConcurrentHashMap<K, V>();
+ }
+
+ /**
+ * Create a concurrent map with weak keys.
+ *
+ * @return a new concurrent map with weak keys
+ */
+ public static <K, V> ConcurrentMap<K, V> concurrentWeakMap() {
+ return new ConcurrentReferenceHashMap<K, V>(16, WEAK, STRONG);
+ }
+
+ /**
+ * Create a concurrent map with weak values.
+ *
+ * @return a new concurrent map with weak values
+ */
+ public static <K, V> ConcurrentMap<K, V> concurrentWeakValueMap() {
+ return new ConcurrentReferenceHashMap<K, V>(16, STRONG, WEAK);
+ }
+
+ /**
+ * Create a synchronized map that obeys the contract for {@code ConcurrentMap}.
+ *
+ * @param original the map to be wrapped
+ * @return a synchronized map
+ */
+ public static <K, V> ConcurrentMap<K, V> synchronizedMap(Map<K, V> original) {
+ return new SynchronizedMap<K, V>(original);
+ }
+
+ /**
+ * Create a synchronized hash map that obeys the contract for {@code ConcurrentMap}.
+ *
+ * @return a synchronized hash map
+ */
+ public static <K, V> ConcurrentMap<K, V> synchronizedHashMap() {
+ return synchronizedMap(CollectionUtil.<K, V>hashMap());
+ }
+
+ /**
+ * Create an array-backed list.
+ *
+ * @return an array-backed list
+ */
+ public static <T> List<T> arrayList() {
+ return new ArrayList<T>();
+ }
+
+ /**
+ * Create a linked list.
+ *
+ * @return a linked list
+ */
+ public static <T> LinkedList<T> linkedList() {
+ return new LinkedList<T>();
+ }
+
+ /**
+ * Create a synchronized array-backed list.
+ *
+ * @return a synchronized array-backed list
+ */
+ public static <T> List<T> synchronizedArrayList() {
+ return Collections.synchronizedList(CollectionUtil.<T>arrayList());
+ }
+
+ /**
+ * Create an array-backed list whose contents are a copy of the given list.
+ *
+ * @param orig the original list
+ * @return an array backed list
+ */
+ public static <T> List<T> arrayList(List<T> orig) {
+ return new ArrayList<T>(orig);
+ }
+
+ /**
+ * Create a synchronized wrapper for the given set.
+ *
+ * @param nested the nested set
+ * @return a synchronized version of the nested set
+ */
+ public static <T> Set<T> synchronizedSet(Set<T> nested) {
+ return new SynchronizedSet<T>(nested);
+ }
+
+ /**
+ * Create a synchronized hash set.
+ *
+ * @return a synchronized hash set
+ */
+ public static <T> Set<T> synchronizedHashSet() {
+ return synchronizedSet(CollectionUtil.<T>hashSet());
+ }
+
+ /**
+ * Create a synchronized weak hash set.
+ *
+ * @return a synchronized weak hash set
+ */
+ public static <T> Set<T> synchronizedWeakHashSet() {
+ return synchronizedSet(CollectionUtil.<T>weakHashSet());
+ }
+
+ /**
+ * Create a synchronized version of the nested queue that obeys the contract for {@code BlockingQueue}.
+ *
+ * @param nested the nested queue
+ * @return the blocking queue
+ */
+ public static <T> BlockingQueue<T> synchronizedQueue(Queue<T> nested) {
+ return new SynchronizedQueue<T>(nested);
+ }
+
+ /**
+ * Create a weak hash set.
+ *
+ * @return a weak hash set
+ */
+ public static <T> Set<T> weakHashSet() {
+ return new WeakHashSet<T>();
+ }
+
+ /**
+ * Create a fixed-capacity blocking queue.
+ *
+ * @param size the fixed size
+ * @return a fixed-capacity blocking queue
+ */
+ public static <T> BlockingQueue<T> blockingQueue(int size) {
+ return new ArrayBlockingQueue<T>(size);
+ }
+
+ /**
+ * Create a hash set.
+ *
+ * @return a hash set
+ */
+ public static <T> Set<T> hashSet() {
+ return new HashSet<T>();
+ }
+
+ /**
+ * Create a hash map with weak keys. See {@link java.util.WeakHashMap}.
+ *
+ * @return a hash map with weak keys
+ */
+ public static <K, V> Map<K, V> weakHashMap() {
+ return new WeakHashMap<K, V>();
+ }
+
+ /**
+ * Create a synchronized hash map with weak keys, which obeys the {@code ConcurrentMap} contract.
+ *
+ * @return a synchronized weak hash map
+ */
+ public static <K, V> ConcurrentMap<K, V> synchronizedWeakHashMap() {
+ return CollectionUtil.<K,V>synchronizedMap(CollectionUtil.<K,V>weakHashMap());
+ }
+
+ /**
+ * Create an unmodifiable list view of an array.
+ *
+ * @param entries the array
+ * @return an unmodifiable list
+ */
+ public static <T> List<T> unmodifiableList(final T... entries) {
+ return Collections.unmodifiableList(Arrays.asList(entries));
+ }
+
+ /**
+ * Create a hash map.
+ *
+ * @return a hash map
+ */
+ public static <K, V> Map<K, V> hashMap() {
+ return new HashMap<K, V>();
+ }
+
+ /**
+ * Create an immutable map entry.
+ *
+ * @param key the key
+ * @param value the value
+ * @return the entry
+ */
+ public static <K, V> Map.Entry<K, V> entry(final K key, final V value) {
+ return new Map.Entry<K, V>() {
+ public K getKey() {
+ return key;
+ }
+
+ public V getValue() {
+ return value;
+ }
+
+ public V setValue(final V value) {
+ throw new UnsupportedOperationException("setValue");
+ }
+ };
+ }
+
+ /**
+ * Create a prepopulated hash map. The map will be sized for the number of elements given.
+ *
+ * @param entries the map entries
+ * @return the prepopulated hash map
+ */
+ public static <K, V> Map<K, V> hashMap(Map.Entry<K, V>... entries) {
+ final Map<K, V> map = new HashMap<K, V>(entries.length);
+ for (Map.Entry<K,V> e : entries) {
+ map.put(e.getKey(), e.getValue());
+ }
+ return map;
+ }
+
+ /**
+ * Create an unmodifiable prepopulated hash map.
+ *
+ * @param entries the map entries
+ * @return the unmodifiable prepopulated hash map
+ */
+ public static <K, V> Map<K, V> unmodifiableHashMap(Map.Entry<K, V>... entries) {
+ return Collections.unmodifiableMap(hashMap(entries));
+ }
+
+ /**
+ * Create an {@code Iterable} view of another {@code Iterable} that exposes no other methods.
+ *
+ * @param original the wrapped instance
+ * @return a new {@code Iterable}
+ */
+ public static <T> Iterable<T> protectedIterable(Iterable<T> original) {
+ return new DelegateIterable<T>(original);
+ }
+
+ /**
+ * Create an {@code Iterable} view of an {@code Enumeration}. The view can be used only once.
+ *
+ * @param enumeration the enumeration
+ * @return the {@code Iterable} view
+ */
+ public static <T> Iterable<T> loop(final Enumeration<T> enumeration) {
+ return new Iterable<T>() {
+ public Iterator<T> iterator() {
+ return CollectionUtil.iterator(enumeration);
+ }
+ };
+ }
+
+ /**
+ * Create an {@code Iterable} view of an {@code Iterator}. The view can be used only once.
+ *
+ * @param iterator the iterator
+ * @return the {@code Iterable} view
+ */
+ public static <T> Iterable<T> loop(final Iterator<T> iterator) {
+ return new Iterable<T>() {
+ public Iterator<T> iterator() {
+ return iterator;
+ }
+ };
+ }
+
+ /**
+ * Create an {@code Iterator} view of an {@code Enumeration}.
+ *
+ * @param enumeration the enumeration
+ * @return the {@code Iterator} view
+ */
+ public static <T> Iterator<T> iterator(final Enumeration<T> enumeration) {
+ return new Iterator<T>() {
+ public boolean hasNext() {
+ return enumeration.hasMoreElements();
+ }
+
+ public T next() {
+ return enumeration.nextElement();
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException("remove()");
+ }
+ };
+ }
+
+ /**
+ * Create an iterable view of a string split by a given delimiter.
+ *
+ * @param delimiter the delimiter
+ * @param subject the original string
+ * @return the iterable split view
+ */
+ public static Iterable<String> split(final String delimiter, final String subject) {
+ return new Iterable<String>() {
+ public Iterator<String> iterator() {
+ return new Iterator<String>(){
+ private int position = 0;
+
+ public boolean hasNext() {
+ return position != -1;
+ }
+
+ public String next() {
+ if (position == -1) {
+ throw new NoSuchElementException("next() past end of iterator");
+ }
+ final int nextDelim = subject.indexOf(delimiter, position);
+ try {
+ if (nextDelim == -1) {
+ return subject.substring(position);
+ } else {
+ return subject.substring(position, nextDelim);
+ }
+ } finally {
+ position = nextDelim == -1 ? -1 : nextDelim + 1;
+ }
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException("remove() not supported");
+ }
+ };
+ }
+ };
+ }
+
+ /**
+ * Join a series of character sequences using a delimiter.
+ *
+ * @param delimiter the delimiter
+ * @param strings the strings
+ * @return a joined string
+ */
+ public static String join(final CharSequence delimiter, final Iterable<? extends CharSequence> strings) {
+ StringBuilder builder = new StringBuilder();
+ Iterator<? extends CharSequence> it = strings.iterator();
+ while (it.hasNext()) {
+ CharSequence s = it.next();
+ builder.append(s);
+ if (it.hasNext()) {
+ builder.append(delimiter);
+ }
+ }
+ return builder.toString();
+ }
+
+ @SuppressWarnings({ "unchecked" })
+ private static <T> T[] unroll(final Iterator<? extends T> iterator, final Class<T> type, final int c) {
+ if (iterator.hasNext()) {
+ final T t = iterator.next();
+ T[] array = unroll(iterator, type, c + 1);
+ array[c] = t;
+ return array;
+ } else {
+ return (T[]) Array.newInstance(type, c);
+ }
+ }
+
+ @SuppressWarnings({ "unchecked" })
+ private static <T> T[] unrollReversed(final Iterator<? extends T> iterator, final Class<T> type, final int c) {
+ if (iterator.hasNext()) {
+ final T t = iterator.next();
+ T[] array = unroll(iterator, type, c + 1);
+ array[array.length - c - 1] = t;
+ return array;
+ } else {
+ return (T[]) Array.newInstance(type, c);
+ }
+ }
+
+ /**
+ * Convert an iterator to an array. The iterator should be relatively short to avoid blowing out the
+ * stack.
+ *
+ * @param iterator the iterator
+ * @param type the array element type
+ * @return the array
+ */
+ public static <T> T[] toArray(final Iterator<? extends T> iterator, final Class<T> type) {
+ return unroll(iterator, type, 0);
+ }
+
+ /**
+ * Convert an iterator to an array in reverse order. The iterator should be relatively short to avoid blowing out the
+ * stack.
+ *
+ * @param iterator the iterator
+ * @param type the array element type
+ * @return the array
+ */
+ public static <T> T[] toArrayReversed(final Iterator<? extends T> iterator, final Class<T> type) {
+ return unrollReversed(iterator, type, 0);
+ }
+
+ /**
+ * Determine if one array begins with another. If {@code prefix} is empty (has a length of zero), then this method
+ * always returns {@code true}. If {@code prefix} is longer than {@code theArray}, this method returns {@code false}.
+ * Otherwise {@code true} is returned if the first {@code N} elements of {@code theArray} are equal to the corresponding
+ * element in {@code prefix}, where {@code N} is equal to the length of {@code prefix}. "Equal" in this context means
+ * that either both elements being compared are {@code null}, or they are equal by way of {@code Object.equals()}.
+ *
+ * @param theArray the array to test
+ * @param prefix the prefix to test against
+ * @return {@code true} if {@code theArray} starts with {@code prefix}
+ */
+ public static boolean arrayStartsWith(Object[] theArray, Object[] prefix) {
+ if (prefix.length > theArray.length) {
+ return false;
+ }
+ for (int i = 0; i < prefix.length; i ++) {
+ final Object prefixObject = prefix[i];
+ final Object testObject = theArray[i];
+ if (testObject == null) {
+ if (prefixObject != null) {
+ return false;
+ }
+ } else {
+ if (prefixObject == null || ! prefixObject.equals(testObject)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Get the empty iterable.
+ *
+ * @return the empty iterable
+ */
+ @SuppressWarnings ({"unchecked"})
+ public static <T> Iterable<T> emptyIterable() {
+ return (Iterable<T>) EMPTY_ITERABLE;
+ }
+
+ private static final Iterable<?> EMPTY_ITERABLE = new EmptyIterable();
+
+ private static class EmptyIterable implements Iterable<Object> {
+ public Iterator<Object> iterator() {
+ return emptyIterator();
+ }
+ }
+
+ /**
+ * Get the empty iterator.
+ *
+ * @return the empty iterator
+ */
+ @SuppressWarnings ({"unchecked"})
+ public static <T> Iterator<T> emptyIterator() {
+ return (Iterator<T>) EMPTY_ITERATOR;
+ }
+
+ private static final Iterator<?> EMPTY_ITERATOR = new EmptyIterator();
+
+ private static final class EmptyIterator implements Iterator<Object> {
+
+ public boolean hasNext() {
+ return false;
+ }
+
+ public Object next() {
+ throw new NoSuchElementException("next() past end of iterator");
+ }
+
+ public void remove() {
+ throw new IllegalStateException("next() has not yet been called");
+ }
+
+ }
+
+ /**
+ * Get a reversed view of a list iterator.
+ *
+ * @param original the original iterator
+ * @return the reversed view
+ */
+ public static <T> ListIterator<T> reverse(ListIterator<T> original) {
+ if (original instanceof ReverseListIterator) {
+ return ((ReverseListIterator<T>)original).original;
+ } else {
+ return new ReverseListIterator<T>(original);
+ }
+ }
+
+ /**
+ * Get an iterable reversed view of a list.
+ *
+ * @param list the list
+ * @return the reversed view
+ */
+ public static <T> Iterable<T> reverse(final List<T> list) {
+ return new Iterable<T>() {
+ public Iterator<T> iterator() {
+ return reverse(list.listIterator(list.size()));
+ }
+ };
+ }
+
+ private static final class ReverseListIterator<T> implements ListIterator<T> {
+
+ private final ListIterator<T> original;
+
+ private ReverseListIterator(final ListIterator<T> original) {
+ this.original = original;
+ }
+
+ public boolean hasNext() {
+ return original.hasPrevious();
+ }
+
+ public T next() {
+ return original.previous();
+ }
+
+ public boolean hasPrevious() {
+ return original.hasNext();
+ }
+
+ public T previous() {
+ return original.next();
+ }
+
+ public int nextIndex() {
+ return original.previousIndex();
+ }
+
+ public int previousIndex() {
+ return original.nextIndex();
+ }
+
+ public void remove() {
+ original.remove();
+ }
+
+ public void set(final T o) {
+ original.set(o);
+ }
+
+ public void add(final T o) {
+ original.add(o);
+ original.previous();
+ }
+ }
+
+ /**
+ * Combine two {@code Iterator}s into one.
+ *
+ * @param first the first {@code Iterator}
+ * @param second the second {@code Iterator}
+ * @return a combined {@code Iterator}
+ */
+ public static <T> Iterator<T> combine(final Iterator<? extends T> first, final Iterator<? extends T> second) {
+ if (first == null) {
+ throw new NullPointerException("first is null");
+ }
+ if (second == null) {
+ throw new NullPointerException("second is null");
+ }
+ return new Iterator<T>() {
+ private Iterator<? extends T> current = first;
+ private Iterator<? extends T> next = second;
+
+ public boolean hasNext() {
+ if (current == null) {
+ return false;
+ }
+ if (! current.hasNext()) {
+ current = next;
+ next = null;
+ }
+ return current != null && current.hasNext();
+ }
+
+ public T next() {
+ if (current == null) {
+ throw new NoSuchElementException("next() past end of iterator");
+ }
+ return current.next();
+ }
+
+ public void remove() {
+ current.remove();
+ }
+ };
+ }
+
+ /**
+ * Combine three {@code Iterator}s into one.
+ *
+ * @param first the first {@code Iterator}
+ * @param second the second {@code Iterator}
+ * @param third the third {@code Iterator}
+ * @return a new combined {@code Iterator}
+ */
+ public static <T> Iterator<T> combine(final Iterator<? extends T> first, final Iterator<? extends T> second, final Iterator<? extends T> third) {
+ return combine(combine(first, second), third);
+ }
+
+ /**
+ * Combine four {@code Iterator}s into one.
+ *
+ * @param first the first {@code Iterator}
+ * @param second the second {@code Iterator}
+ * @param third the third {@code Iterator}
+ * @param fourth the fourth {@code Iterator}
+ * @return a new combined {@code Iterator}
+ */
+ public static <T> Iterator<T> combine(final Iterator<? extends T> first, final Iterator<? extends T> second, final Iterator<? extends T> third, final Iterator<? extends T> fourth) {
+ return combine(combine(first, second), combine(third, fourth));
+ }
+
+ /**
+ * Combine two {@code Iterable}s into one.
+ *
+ * @param first the first {@code Iterable}
+ * @param second the second {@code Iterable}
+ * @return a new combined {@code Iterable}
+ */
+ public static <T> Iterable<T> combine(final Iterable<? extends T> first, final Iterable<? extends T> second) {
+ if (first == null) {
+ throw new NullPointerException("first is null");
+ }
+ if (second == null) {
+ throw new NullPointerException("second is null");
+ }
+ return new Iterable<T>() {
+ public Iterator<T> iterator() {
+ return combine(first.iterator(), second.iterator());
+ }
+ };
+ }
+
+ /**
+ * Combine three {@code Iterable}s into one.
+ *
+ * @param first the first {@code Iterable}
+ * @param second the second {@code Iterable}
+ * @param third the third {@code Iterable}
+ * @return a new combined {@code Iterable}
+ */
+ public static <T> Iterable<T> combine(final Iterable<? extends T> first, final Iterable<? extends T> second, final Iterable<? extends T> third) {
+ return combine(combine(first, second), third);
+ }
+
+ /**
+ * Combine four {@code Iterable}s into one.
+ *
+ * @param first the first {@code Iterable}
+ * @param second the second {@code Iterable}
+ * @param third the third {@code Iterable}
+ * @param fourth the fourth {@code Iterable}
+ * @return a new combined {@code Iterable}
+ */
+ public static <T> Iterable<T> combine(final Iterable<? extends T> first, final Iterable<? extends T> second, final Iterable<? extends T> third, final Iterable<? extends T> fourth) {
+ return combine(combine(first, second), combine(third, fourth));
+ }
+
+ private static final class DelegateIterable<T> implements Iterable<T> {
+
+ private final Iterable<T> delegate;
+
+ public DelegateIterable(final Iterable<T> delegate) {
+ this.delegate = delegate;
+ }
+
+ public Iterator<T> iterator() {
+ return delegate.iterator();
+ }
+ }
+}
Copied: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/ConcurrentReferenceHashMap.java (from rev 4696, remoting3/trunk/util/src/main/java/org/jboss/remoting/util/ConcurrentReferenceHashMap.java)
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/ConcurrentReferenceHashMap.java (rev 0)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/ConcurrentReferenceHashMap.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -0,0 +1,1709 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package org.jboss.remoting.core.util;
+import java.io.IOException;
+import java.io.Serializable;
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.SoftReference;
+import java.lang.ref.WeakReference;
+import java.util.AbstractCollection;
+import java.util.AbstractMap;
+import java.util.AbstractSet;
+import java.util.Collection;
+import java.util.ConcurrentModificationException;
+import java.util.EnumSet;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.IdentityHashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * An advanced hash table supporting configurable garbage collection semantics
+ * of keys and values, optional referential-equality, full concurrency of
+ * retrievals, and adjustable expected concurrency for updates.
+ *
+ * This table is designed around specific advanced use-cases. If there is any
+ * doubt whether this table is for you, you most likely should be using
+ * {@link java.util.concurrent.ConcurrentHashMap} instead.
+ *
+ * This table supports strong, weak, and soft keys and values. By default keys
+ * are weak, and values are strong. Such a configuration offers similar behavior
+ * to {@link java.util.WeakHashMap}, entries of this table are periodically
+ * removed once their corresponding keys are no longer referenced outside of
+ * this table. In other words, this table will not prevent a key from being
+ * discarded by the garbage collector. Once a key has been discarded by the
+ * collector, the corresponding entry is no longer visible to this table;
+ * however, the entry may occupy space until a future table operation decides to
+ * reclaim it. For this reason, summary functions such as <tt>size</tt> and
+ * <tt>isEmpty</tt> might return a value greater than the observed number of
+ * entries. In order to support a high level of concurrency, stale entries are
+ * only reclaimed during blocking (usually mutating) operations.
+ *
+ * Enabling soft keys allows entries in this table to remain until their space
+ * is absolutely needed by the garbage collector. This is unlike weak keys which
+ * can be reclaimed as soon as they are no longer referenced by a normal strong
+ * reference. The primary use case for soft keys is a cache, which ideally
+ * occupies memory that is not in use for as long as possible.
+ *
+ * By default, values are held using a normal strong reference. This provides
+ * the commonly desired guarantee that a value will always have at least the
+ * same life-span as it's key. For this reason, care should be taken to ensure
+ * that a value never refers, either directly or indirectly, to its key, thereby
+ * preventing reclamation. If this is unavoidable, then it is recommended to use
+ * the same reference type in use for the key. However, it should be noted that
+ * non-strong values may disappear before their corresponding key.
+ *
+ * While this table does allow the use of both strong keys and values, it is
+ * recommended to use {@link java.util.concurrent.ConcurrentHashMap} for such a
+ * configuration, since it is optimized for that case.
+ *
+ * Just like {@link java.util.concurrent.ConcurrentHashMap}, this class obeys
+ * the same functional specification as {@link java.util.Hashtable}, and
+ * includes versions of methods corresponding to each method of
+ * <tt>Hashtable</tt>. However, even though all operations are thread-safe,
+ * retrieval operations do <em>not</em> entail locking, and there is
+ * <em>not</em> any support for locking the entire table in a way that
+ * prevents all access. This class is fully interoperable with
+ * <tt>Hashtable</tt> in programs that rely on its thread safety but not on
+ * its synchronization details.
+ *
+ * <p>
+ * Retrieval operations (including <tt>get</tt>) generally do not block, so
+ * may overlap with update operations (including <tt>put</tt> and
+ * <tt>remove</tt>). Retrievals reflect the results of the most recently
+ * <em>completed</em> update operations holding upon their onset. For
+ * aggregate operations such as <tt>putAll</tt> and <tt>clear</tt>,
+ * concurrent retrievals may reflect insertion or removal of only some entries.
+ * Similarly, Iterators and Enumerations return elements reflecting the state of
+ * the hash table at some point at or since the creation of the
+ * iterator/enumeration. They do <em>not</em> throw
+ * {@link ConcurrentModificationException}. However, iterators are designed to
+ * be used by only one thread at a time.
+ *
+ * <p>
+ * The allowed concurrency among update operations is guided by the optional
+ * <tt>concurrencyLevel</tt> constructor argument (default <tt>16</tt>),
+ * which is used as a hint for internal sizing. The table is internally
+ * partitioned to try to permit the indicated number of concurrent updates
+ * without contention. Because placement in hash tables is essentially random,
+ * the actual concurrency will vary. Ideally, you should choose a value to
+ * accommodate as many threads as will ever concurrently modify the table. Using
+ * a significantly higher value than you need can waste space and time, and a
+ * significantly lower value can lead to thread contention. But overestimates
+ * and underestimates within an order of magnitude do not usually have much
+ * noticeable impact. A value of one is appropriate when it is known that only
+ * one thread will modify and all others will only read. Also, resizing this or
+ * any other kind of hash table is a relatively slow operation, so, when
+ * possible, it is a good idea to provide estimates of expected table sizes in
+ * constructors.
+ *
+ * <p>
+ * This class and its views and iterators implement all of the <em>optional</em>
+ * methods of the {@link Map} and {@link Iterator} interfaces.
+ *
+ * <p>
+ * Like {@link Hashtable} but unlike {@link HashMap}, this class does
+ * <em>not</em> allow <tt>null</tt> to be used as a key or value.
+ *
+ * <p>
+ * This class is a member of the <a href="{@docRoot}/../technotes/guides/collections/index.html">
+ * Java Collections Framework</a>.
+ *
+ * @author Doug Lea
+ * @author Jason T. Greene
+ * @param <K> the type of keys maintained by this map
+ * @param <V> the type of mapped values
+ */
+public class ConcurrentReferenceHashMap<K, V> extends AbstractMap<K, V>
+ implements java.util.concurrent.ConcurrentMap<K, V>, Serializable {
+ private static final long serialVersionUID = 7249069246763182397L;
+
+ /*
+ * The basic strategy is to subdivide the table among Segments,
+ * each of which itself is a concurrently readable hash table.
+ */
+
+ /**
+ * An option specifying which Java reference type should be used to refer
+ * to a key and/or value.
+ */
+ public static enum ReferenceType {
+ /** Indicates a normal Java strong reference should be used */
+ STRONG,
+ /** Indicates a {@link WeakReference} should be used */
+ WEAK,
+ /** Indicates a {@link SoftReference} should be used */
+ SOFT
+ };
+
+
+ public static enum Option {
+ /** Indicates that referential-equality (== instead of .equals()) should
+ * be used when locating keys. This offers similar behavior to {@link IdentityHashMap} */
+ IDENTITY_COMPARISONS
+ };
+
+ /* ---------------- Constants -------------- */
+
+ static final ReferenceType DEFAULT_KEY_TYPE = ReferenceType.WEAK;
+
+ static final ReferenceType DEFAULT_VALUE_TYPE = ReferenceType.STRONG;
+
+
+ /**
+ * The default initial capacity for this table,
+ * used when not otherwise specified in a constructor.
+ */
+ static final int DEFAULT_INITIAL_CAPACITY = 16;
+
+ /**
+ * The default load factor for this table, used when not
+ * otherwise specified in a constructor.
+ */
+ static final float DEFAULT_LOAD_FACTOR = 0.75f;
+
+ /**
+ * The default concurrency level for this table, used when not
+ * otherwise specified in a constructor.
+ */
+ static final int DEFAULT_CONCURRENCY_LEVEL = 16;
+
+ /**
+ * The maximum capacity, used if a higher value is implicitly
+ * specified by either of the constructors with arguments. MUST
+ * be a power of two <= 1<<30 to ensure that entries are indexable
+ * using ints.
+ */
+ static final int MAXIMUM_CAPACITY = 1 << 30;
+
+ /**
+ * The maximum number of segments to allow; used to bound
+ * constructor arguments.
+ */
+ static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
+
+ /**
+ * Number of unsynchronized retries in size and containsValue
+ * methods before resorting to locking. This is used to avoid
+ * unbounded retries if tables undergo continuous modification
+ * which would make it impossible to obtain an accurate result.
+ */
+ static final int RETRIES_BEFORE_LOCK = 2;
+
+ /* ---------------- Fields -------------- */
+
+ /**
+ * Mask value for indexing into segments. The upper bits of a
+ * key's hash code are used to choose the segment.
+ */
+ final int segmentMask;
+
+ /**
+ * Shift value for indexing within segments.
+ */
+ final int segmentShift;
+
+ /**
+ * The segments, each of which is a specialized hash table
+ */
+ final Segment<K,V>[] segments;
+
+ boolean identityComparisons;
+
+ transient Set<K> keySet;
+ transient Set<Map.Entry<K,V>> entrySet;
+ transient Collection<V> values;
+
+ /* ---------------- Small Utilities -------------- */
+
+ /**
+ * Applies a supplemental hash function to a given hashCode, which
+ * defends against poor quality hash functions. This is critical
+ * because ConcurrentReferenceHashMap uses power-of-two length hash tables,
+ * that otherwise encounter collisions for hashCodes that do not
+ * differ in lower or upper bits.
+ */
+ private static int hash(int h) {
+ // Spread bits to regularize both segment and index locations,
+ // using variant of single-word Wang/Jenkins hash.
+ h += (h << 15) ^ 0xffffcd7d;
+ h ^= (h >>> 10);
+ h += (h << 3);
+ h ^= (h >>> 6);
+ h += (h << 2) + (h << 14);
+ return h ^ (h >>> 16);
+ }
+
+ /**
+ * Returns the segment that should be used for key with given hash
+ * @param hash the hash code for the key
+ * @return the segment
+ */
+ final Segment<K,V> segmentFor(int hash) {
+ return segments[(hash >>> segmentShift) & segmentMask];
+ }
+
+ private int hashOf(Object key) {
+ return hash(identityComparisons ?
+ System.identityHashCode(key) : key.hashCode());
+ }
+
+ /* ---------------- Inner Classes -------------- */
+
+ static interface KeyReference {
+ int keyHash();
+ Object keyRef();
+ }
+
+ /**
+ * A weak-key reference which stores the key hash needed for reclamation.
+ */
+ static final class WeakKeyReference<K> extends WeakReference<K> implements KeyReference {
+ final int hash;
+ WeakKeyReference(K key, int hash, ReferenceQueue<Object> refQueue) {
+ super(key, refQueue);
+ this.hash = hash;
+ }
+ public final int keyHash() {
+ return hash;
+ }
+
+ public final Object keyRef() {
+ return this;
+ }
+ }
+
+ /**
+ * A soft-key reference which stores the key hash needed for reclamation.
+ */
+ static final class SoftKeyReference<K> extends SoftReference<K> implements KeyReference {
+ final int hash;
+ SoftKeyReference(K key, int hash, ReferenceQueue<Object> refQueue) {
+ super(key, refQueue);
+ this.hash = hash;
+ }
+ public final int keyHash() {
+ return hash;
+ }
+
+ public final Object keyRef() {
+ return this;
+ }
+ }
+
+ static final class WeakValueReference<V> extends WeakReference<V> implements KeyReference {
+ final Object keyRef;
+ final int hash;
+ WeakValueReference(V value, Object keyRef, int hash, ReferenceQueue<Object> refQueue) {
+ super(value, refQueue);
+ this.keyRef = keyRef;
+ this.hash = hash;
+ }
+
+ public final int keyHash() {
+ return hash;
+ }
+
+ public final Object keyRef() {
+ return keyRef;
+ }
+ }
+
+ static final class SoftValueReference<V> extends SoftReference<V> implements KeyReference {
+ final Object keyRef;
+ final int hash;
+ SoftValueReference(V value, Object keyRef, int hash, ReferenceQueue<Object> refQueue) {
+ super(value, refQueue);
+ this.keyRef = keyRef;
+ this.hash = hash;
+ }
+ public final int keyHash() {
+ return hash;
+ }
+
+ public final Object keyRef() {
+ return keyRef;
+ }
+ }
+
+ /**
+ * ConcurrentReferenceHashMap list entry. Note that this is never exported
+ * out as a user-visible Map.Entry.
+ *
+ * Because the value field is volatile, not final, it is legal wrt
+ * the Java Memory Model for an unsynchronized reader to see null
+ * instead of initial value when read via a data race. Although a
+ * reordering leading to this is not likely to ever actually
+ * occur, the Segment.readValueUnderLock method is used as a
+ * backup in case a null (pre-initialized) value is ever seen in
+ * an unsynchronized access method.
+ */
+ static final class HashEntry<K,V> {
+ final Object keyRef;
+ final int hash;
+ volatile Object valueRef;
+ final HashEntry<K,V> next;
+
+ HashEntry(K key, int hash, HashEntry<K,V> next, V value,
+ ReferenceType keyType, ReferenceType valueType,
+ ReferenceQueue<Object> refQueue) {
+ this.hash = hash;
+ this.next = next;
+ this.keyRef = newKeyReference(key, keyType, refQueue);
+ this.valueRef = newValueReference(value, valueType, refQueue);
+ }
+
+ final Object newKeyReference(K key, ReferenceType keyType,
+ ReferenceQueue<Object> refQueue) {
+ if (keyType == ReferenceType.WEAK)
+ return new WeakKeyReference<K>(key, hash, refQueue);
+ if (keyType == ReferenceType.SOFT)
+ return new SoftKeyReference<K>(key, hash, refQueue);
+
+ return key;
+ }
+
+ final Object newValueReference(V value, ReferenceType valueType,
+ ReferenceQueue<Object> refQueue) {
+ if (valueType == ReferenceType.WEAK)
+ return new WeakValueReference<V>(value, keyRef, hash, refQueue);
+ if (valueType == ReferenceType.SOFT)
+ return new SoftValueReference<V>(value, keyRef, hash, refQueue);
+
+ return value;
+ }
+
+ @SuppressWarnings("unchecked")
+ final K key() {
+ if (keyRef instanceof Reference)
+ return ((Reference<K>)keyRef).get();
+
+ return (K) keyRef;
+ }
+
+ final V value() {
+ return dereferenceValue(valueRef);
+ }
+
+ @SuppressWarnings("unchecked")
+ final V dereferenceValue(Object value) {
+ if (value instanceof Reference)
+ return ((Reference<V>)value).get();
+
+ return (V) value;
+ }
+
+ final void setValue(V value, ReferenceType valueType, ReferenceQueue<Object> refQueue) {
+ this.valueRef = newValueReference(value, valueType, refQueue);
+ }
+
+ @SuppressWarnings("unchecked")
+ static final <K,V> HashEntry<K,V>[] newArray(int i) {
+ return new HashEntry[i];
+ }
+ }
+
+ /**
+ * Segments are specialized versions of hash tables. This
+ * subclasses from ReentrantLock opportunistically, just to
+ * simplify some locking and avoid separate construction.
+ */
+ static final class Segment<K,V> extends ReentrantLock implements Serializable {
+ /*
+ * Segments maintain a table of entry lists that are ALWAYS
+ * kept in a consistent state, so can be read without locking.
+ * Next fields of nodes are immutable (final). All list
+ * additions are performed at the front of each bin. This
+ * makes it easy to check changes, and also fast to traverse.
+ * When nodes would otherwise be changed, new nodes are
+ * created to replace them. This works well for hash tables
+ * since the bin lists tend to be short. (The average length
+ * is less than two for the default load factor threshold.)
+ *
+ * Read operations can thus proceed without locking, but rely
+ * on selected uses of volatiles to ensure that completed
+ * write operations performed by other threads are
+ * noticed. For most purposes, the "count" field, tracking the
+ * number of elements, serves as that volatile variable
+ * ensuring visibility. This is convenient because this field
+ * needs to be read in many read operations anyway:
+ *
+ * - All (unsynchronized) read operations must first read the
+ * "count" field, and should not look at table entries if
+ * it is 0.
+ *
+ * - All (synchronized) write operations should write to
+ * the "count" field after structurally changing any bin.
+ * The operations must not take any action that could even
+ * momentarily cause a concurrent read operation to see
+ * inconsistent data. This is made easier by the nature of
+ * the read operations in Map. For example, no operation
+ * can reveal that the table has grown but the threshold
+ * has not yet been updated, so there are no atomicity
+ * requirements for this with respect to reads.
+ *
+ * As a guide, all critical volatile reads and writes to the
+ * count field are marked in code comments.
+ */
+
+ private static final long serialVersionUID = 2249069246763182397L;
+
+ /**
+ * The number of elements in this segment's region.
+ */
+ transient volatile int count;
+
+ /**
+ * Number of updates that alter the size of the table. This is
+ * used during bulk-read methods to make sure they see a
+ * consistent snapshot: If modCounts change during a traversal
+ * of segments computing size or checking containsValue, then
+ * we might have an inconsistent view of state so (usually)
+ * must retry.
+ */
+ transient int modCount;
+
+ /**
+ * The table is rehashed when its size exceeds this threshold.
+ * (The value of this field is always <tt>(int)(capacity *
+ * loadFactor)</tt>.)
+ */
+ transient int threshold;
+
+ /**
+ * The per-segment table.
+ */
+ transient volatile HashEntry<K,V>[] table;
+
+ /**
+ * The load factor for the hash table. Even though this value
+ * is same for all segments, it is replicated to avoid needing
+ * links to outer object.
+ * @serial
+ */
+ final float loadFactor;
+
+ /**
+ * The collected weak-key reference queue for this segment.
+ * This should be (re)initialized whenever table is assigned,
+ */
+ transient volatile ReferenceQueue<Object> refQueue;
+
+ final ReferenceType keyType;
+
+ final ReferenceType valueType;
+
+ final boolean identityComparisons;
+
+ Segment(int initialCapacity, float lf, ReferenceType keyType,
+ ReferenceType valueType, boolean identityComparisons) {
+ loadFactor = lf;
+ this.keyType = keyType;
+ this.valueType = valueType;
+ this.identityComparisons = identityComparisons;
+ setTable(HashEntry.<K,V>newArray(initialCapacity));
+ }
+
+ @SuppressWarnings("unchecked")
+ static final <K,V> Segment<K,V>[] newArray(int i) {
+ return new Segment[i];
+ }
+
+ private boolean keyEq(Object src, Object dest) {
+ return identityComparisons ? src == dest : src.equals(dest);
+ }
+
+ /**
+ * Sets table to new HashEntry array.
+ * Call only while holding lock or in constructor.
+ */
+ void setTable(HashEntry<K,V>[] newTable) {
+ threshold = (int)(newTable.length * loadFactor);
+ table = newTable;
+ refQueue = new ReferenceQueue<Object>();
+ }
+
+ /**
+ * Returns properly casted first entry of bin for given hash.
+ */
+ HashEntry<K,V> getFirst(int hash) {
+ HashEntry<K,V>[] tab = table;
+ return tab[hash & (tab.length - 1)];
+ }
+
+ HashEntry<K,V> newHashEntry(K key, int hash, HashEntry<K, V> next, V value) {
+ return new HashEntry<K,V>(key, hash, next, value, keyType, valueType, refQueue);
+ }
+
+ /**
+ * Reads value field of an entry under lock. Called if value
+ * field ever appears to be null. This is possible only if a
+ * compiler happens to reorder a HashEntry initialization with
+ * its table assignment, which is legal under memory model
+ * but is not known to ever occur.
+ */
+ V readValueUnderLock(HashEntry<K,V> e) {
+ lock();
+ try {
+ removeStale();
+ return e.value();
+ } finally {
+ unlock();
+ }
+ }
+
+ /* Specialized implementations of map methods */
+
+ V get(Object key, int hash) {
+ if (count != 0) { // read-volatile
+ HashEntry<K,V> e = getFirst(hash);
+ while (e != null) {
+ if (e.hash == hash && keyEq(key, e.key())) {
+ Object opaque = e.valueRef;
+ if (opaque != null)
+ return e.dereferenceValue(opaque);
+
+ return readValueUnderLock(e); // recheck
+ }
+ e = e.next;
+ }
+ }
+ return null;
+ }
+
+ boolean containsKey(Object key, int hash) {
+ if (count != 0) { // read-volatile
+ HashEntry<K,V> e = getFirst(hash);
+ while (e != null) {
+ if (e.hash == hash && keyEq(key, e.key()))
+ return true;
+ e = e.next;
+ }
+ }
+ return false;
+ }
+
+ boolean containsValue(Object value) {
+ if (count != 0) { // read-volatile
+ HashEntry<K,V>[] tab = table;
+ int len = tab.length;
+ for (int i = 0 ; i < len; i++) {
+ for (HashEntry<K,V> e = tab[i]; e != null; e = e.next) {
+ Object opaque = e.valueRef;
+ V v;
+
+ if (opaque == null)
+ v = readValueUnderLock(e); // recheck
+ else
+ v = e.dereferenceValue(opaque);
+
+ if (value.equals(v))
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ boolean replace(K key, int hash, V oldValue, V newValue) {
+ lock();
+ try {
+ removeStale();
+ HashEntry<K,V> e = getFirst(hash);
+ while (e != null && (e.hash != hash || !keyEq(key, e.key())))
+ e = e.next;
+
+ boolean replaced = false;
+ if (e != null && oldValue.equals(e.value())) {
+ replaced = true;
+ e.setValue(newValue, valueType, refQueue);
+ }
+ return replaced;
+ } finally {
+ unlock();
+ }
+ }
+
+ V replace(K key, int hash, V newValue) {
+ lock();
+ try {
+ removeStale();
+ HashEntry<K,V> e = getFirst(hash);
+ while (e != null && (e.hash != hash || !keyEq(key, e.key())))
+ e = e.next;
+
+ V oldValue = null;
+ if (e != null) {
+ oldValue = e.value();
+ e.setValue(newValue, valueType, refQueue);
+ }
+ return oldValue;
+ } finally {
+ unlock();
+ }
+ }
+
+
+ V put(K key, int hash, V value, boolean onlyIfAbsent) {
+ lock();
+ try {
+ removeStale();
+ int c = count;
+ if (c++ > threshold) {// ensure capacity
+ int reduced = rehash();
+ if (reduced > 0) // adjust from possible weak cleanups
+ count = (c -= reduced) - 1; // write-volatile
+ }
+
+ HashEntry<K,V>[] tab = table;
+ int index = hash & (tab.length - 1);
+ HashEntry<K,V> first = tab[index];
+ HashEntry<K,V> e = first;
+ while (e != null && (e.hash != hash || !keyEq(key, e.key())))
+ e = e.next;
+
+ V oldValue;
+ if (e != null) {
+ oldValue = e.value();
+ if (!onlyIfAbsent)
+ e.setValue(value, valueType, refQueue);
+ }
+ else {
+ oldValue = null;
+ ++modCount;
+ tab[index] = newHashEntry(key, hash, first, value);
+ count = c; // write-volatile
+ }
+ return oldValue;
+ } finally {
+ unlock();
+ }
+ }
+
+ int rehash() {
+ HashEntry<K,V>[] oldTable = table;
+ int oldCapacity = oldTable.length;
+ if (oldCapacity >= MAXIMUM_CAPACITY)
+ return 0;
+
+ /*
+ * Reclassify nodes in each list to new Map. Because we are
+ * using power-of-two expansion, the elements from each bin
+ * must either stay at same index, or move with a power of two
+ * offset. We eliminate unnecessary node creation by catching
+ * cases where old nodes can be reused because their next
+ * fields won't change. Statistically, at the default
+ * threshold, only about one-sixth of them need cloning when
+ * a table doubles. The nodes they replace will be garbage
+ * collectable as soon as they are no longer referenced by any
+ * reader thread that may be in the midst of traversing table
+ * right now.
+ */
+
+ HashEntry<K,V>[] newTable = HashEntry.newArray(oldCapacity<<1);
+ threshold = (int)(newTable.length * loadFactor);
+ int sizeMask = newTable.length - 1;
+ int reduce = 0;
+ for (int i = 0; i < oldCapacity ; i++) {
+ // We need to guarantee that any existing reads of old Map can
+ // proceed. So we cannot yet null out each bin.
+ HashEntry<K,V> e = oldTable[i];
+
+ if (e != null) {
+ HashEntry<K,V> next = e.next;
+ int idx = e.hash & sizeMask;
+
+ // Single node on list
+ if (next == null)
+ newTable[idx] = e;
+
+ else {
+ // Reuse trailing consecutive sequence at same slot
+ HashEntry<K,V> lastRun = e;
+ int lastIdx = idx;
+ for (HashEntry<K,V> last = next;
+ last != null;
+ last = last.next) {
+ int k = last.hash & sizeMask;
+ if (k != lastIdx) {
+ lastIdx = k;
+ lastRun = last;
+ }
+ }
+ newTable[lastIdx] = lastRun;
+ // Clone all remaining nodes
+ for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
+ // Skip GC'd weak refs
+ K key = p.key();
+ if (key == null) {
+ reduce++;
+ continue;
+ }
+ int k = p.hash & sizeMask;
+ HashEntry<K,V> n = newTable[k];
+ newTable[k] = newHashEntry(key, p.hash, n, p.value());
+ }
+ }
+ }
+ }
+ table = newTable;
+ return reduce;
+ }
+
+ /**
+ * Remove; match on key only if value null, else match both.
+ */
+ V remove(Object key, int hash, Object value, boolean refRemove) {
+ lock();
+ try {
+ if (!refRemove)
+ removeStale();
+ int c = count - 1;
+ HashEntry<K,V>[] tab = table;
+ int index = hash & (tab.length - 1);
+ HashEntry<K,V> first = tab[index];
+ HashEntry<K,V> e = first;
+ // a ref remove operation compares the Reference instance
+ while (e != null && key != e.keyRef
+ && (refRemove || hash != e.hash || !keyEq(key, e.key())))
+ e = e.next;
+
+ V oldValue = null;
+ if (e != null) {
+ V v = e.value();
+ if (value == null || value.equals(v)) {
+ oldValue = v;
+ // All entries following removed node can stay
+ // in list, but all preceding ones need to be
+ // cloned.
+ ++modCount;
+ HashEntry<K,V> newFirst = e.next;
+ for (HashEntry<K,V> p = first; p != e; p = p.next) {
+ K pKey = p.key();
+ if (pKey == null) { // Skip GC'd keys
+ c--;
+ continue;
+ }
+
+ newFirst = newHashEntry(pKey, p.hash, newFirst, p.value());
+ }
+ tab[index] = newFirst;
+ count = c; // write-volatile
+ }
+ }
+ return oldValue;
+ } finally {
+ unlock();
+ }
+ }
+
+ final void removeStale() {
+ KeyReference ref;
+ while ((ref = (KeyReference) refQueue.poll()) != null) {
+ remove(ref.keyRef(), ref.keyHash(), null, true);
+ }
+ }
+
+ void clear() {
+ if (count != 0) {
+ lock();
+ try {
+ HashEntry<K,V>[] tab = table;
+ for (int i = 0; i < tab.length ; i++)
+ tab[i] = null;
+ ++modCount;
+ // replace the reference queue to avoid unnecessary stale cleanups
+ refQueue = new ReferenceQueue<Object>();
+ count = 0; // write-volatile
+ } finally {
+ unlock();
+ }
+ }
+ }
+ }
+
+
+
+ /* ---------------- Public operations -------------- */
+
+ /**
+ * Creates a new, empty map with the specified initial
+ * capacity, reference types, load factor and concurrency level.
+ *
+ * Behavioral changing options such as {@link Option#IDENTITY_COMPARISONS}
+ * can also be specified.
+ *
+ * @param initialCapacity the initial capacity. The implementation
+ * performs internal sizing to accommodate this many elements.
+ * @param loadFactor the load factor threshold, used to control resizing.
+ * Resizing may be performed when the average number of elements per
+ * bin exceeds this threshold.
+ * @param concurrencyLevel the estimated number of concurrently
+ * updating threads. The implementation performs internal sizing
+ * to try to accommodate this many threads.
+ * @param keyType the reference type to use for keys
+ * @param valueType the reference type to use for values
+ * @param options the behavioral options
+ * @throws IllegalArgumentException if the initial capacity is
+ * negative or the load factor or concurrencyLevel are
+ * nonpositive.
+ */
+ public ConcurrentReferenceHashMap(int initialCapacity,
+ float loadFactor, int concurrencyLevel,
+ ReferenceType keyType, ReferenceType valueType,
+ EnumSet<Option> options) {
+ if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
+ throw new IllegalArgumentException();
+
+ if (concurrencyLevel > MAX_SEGMENTS)
+ concurrencyLevel = MAX_SEGMENTS;
+
+ // Find power-of-two sizes best matching arguments
+ int sshift = 0;
+ int ssize = 1;
+ while (ssize < concurrencyLevel) {
+ ++sshift;
+ ssize <<= 1;
+ }
+ segmentShift = 32 - sshift;
+ segmentMask = ssize - 1;
+ this.segments = Segment.newArray(ssize);
+
+ if (initialCapacity > MAXIMUM_CAPACITY)
+ initialCapacity = MAXIMUM_CAPACITY;
+ int c = initialCapacity / ssize;
+ if (c * ssize < initialCapacity)
+ ++c;
+ int cap = 1;
+ while (cap < c)
+ cap <<= 1;
+
+ identityComparisons = options != null && options.contains(Option.IDENTITY_COMPARISONS);
+
+ for (int i = 0; i < this.segments.length; ++i)
+ this.segments[i] = new Segment<K,V>(cap, loadFactor,
+ keyType, valueType, identityComparisons);
+ }
+
+ /**
+ * Creates a new, empty map with the specified initial
+ * capacity, load factor and concurrency level.
+ *
+ * @param initialCapacity the initial capacity. The implementation
+ * performs internal sizing to accommodate this many elements.
+ * @param loadFactor the load factor threshold, used to control resizing.
+ * Resizing may be performed when the average number of elements per
+ * bin exceeds this threshold.
+ * @param concurrencyLevel the estimated number of concurrently
+ * updating threads. The implementation performs internal sizing
+ * to try to accommodate this many threads.
+ * @throws IllegalArgumentException if the initial capacity is
+ * negative or the load factor or concurrencyLevel are
+ * nonpositive.
+ */
+ public ConcurrentReferenceHashMap(int initialCapacity,
+ float loadFactor, int concurrencyLevel) {
+ this(initialCapacity, loadFactor, concurrencyLevel,
+ DEFAULT_KEY_TYPE, DEFAULT_VALUE_TYPE, null);
+ }
+
+ /**
+ * Creates a new, empty map with the specified initial capacity
+ * and load factor and with the default reference types (weak keys,
+ * strong values), and concurrencyLevel (16).
+ *
+ * @param initialCapacity The implementation performs internal
+ * sizing to accommodate this many elements.
+ * @param loadFactor the load factor threshold, used to control resizing.
+ * Resizing may be performed when the average number of elements per
+ * bin exceeds this threshold.
+ * @throws IllegalArgumentException if the initial capacity of
+ * elements is negative or the load factor is nonpositive
+ *
+ * @since 1.6
+ */
+ public ConcurrentReferenceHashMap(int initialCapacity, float loadFactor) {
+ this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL);
+ }
+
+
+ /**
+ * Creates a new, empty map with the specified initial capacity,
+ * reference types and with default load factor (0.75) and concurrencyLevel (16).
+ *
+ * @param initialCapacity the initial capacity. The implementation
+ * performs internal sizing to accommodate this many elements.
+ * @param keyType the reference type to use for keys
+ * @param valueType the reference type to use for values
+ * @throws IllegalArgumentException if the initial capacity of
+ * elements is negative.
+ */
+ public ConcurrentReferenceHashMap(int initialCapacity,
+ ReferenceType keyType, ReferenceType valueType) {
+ this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL,
+ keyType, valueType, null);
+ }
+
+ /**
+ * Creates a new, empty map with the specified initial capacity,
+ * and with default reference types (weak keys, strong values),
+ * load factor (0.75) and concurrencyLevel (16).
+ *
+ * @param initialCapacity the initial capacity. The implementation
+ * performs internal sizing to accommodate this many elements.
+ * @throws IllegalArgumentException if the initial capacity of
+ * elements is negative.
+ */
+ public ConcurrentReferenceHashMap(int initialCapacity) {
+ this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
+ }
+
+ /**
+ * Creates a new, empty map with a default initial capacity (16),
+ * reference types (weak keys, strong values), default
+ * load factor (0.75) and concurrencyLevel (16).
+ */
+ public ConcurrentReferenceHashMap() {
+ this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
+ }
+
+ /**
+ * Creates a new map with the same mappings as the given map.
+ * The map is created with a capacity of 1.5 times the number
+ * of mappings in the given map or 16 (whichever is greater),
+ * and a default load factor (0.75) and concurrencyLevel (16).
+ *
+ * @param m the map
+ */
+ public ConcurrentReferenceHashMap(Map<? extends K, ? extends V> m) {
+ this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
+ DEFAULT_INITIAL_CAPACITY),
+ DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
+ putAll(m);
+ }
+
+ /**
+ * Returns <tt>true</tt> if this map contains no key-value mappings.
+ *
+ * @return <tt>true</tt> if this map contains no key-value mappings
+ */
+ public boolean isEmpty() {
+ final Segment<K,V>[] segments = this.segments;
+ /*
+ * We keep track of per-segment modCounts to avoid ABA
+ * problems in which an element in one segment was added and
+ * in another removed during traversal, in which case the
+ * table was never actually empty at any point. Note the
+ * similar use of modCounts in the size() and containsValue()
+ * methods, which are the only other methods also susceptible
+ * to ABA problems.
+ */
+ int[] mc = new int[segments.length];
+ int mcsum = 0;
+ for (int i = 0; i < segments.length; ++i) {
+ if (segments[i].count != 0)
+ return false;
+ else
+ mcsum += mc[i] = segments[i].modCount;
+ }
+ // If mcsum happens to be zero, then we know we got a snapshot
+ // before any modifications at all were made. This is
+ // probably common enough to bother tracking.
+ if (mcsum != 0) {
+ for (int i = 0; i < segments.length; ++i) {
+ if (segments[i].count != 0 ||
+ mc[i] != segments[i].modCount)
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Returns the number of key-value mappings in this map. If the
+ * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
+ * <tt>Integer.MAX_VALUE</tt>.
+ *
+ * @return the number of key-value mappings in this map
+ */
+ public int size() {
+ final Segment<K,V>[] segments = this.segments;
+ long sum = 0;
+ long check = 0;
+ int[] mc = new int[segments.length];
+ // Try a few times to get accurate count. On failure due to
+ // continuous async changes in table, resort to locking.
+ for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
+ check = 0;
+ sum = 0;
+ int mcsum = 0;
+ for (int i = 0; i < segments.length; ++i) {
+ sum += segments[i].count;
+ mcsum += mc[i] = segments[i].modCount;
+ }
+ if (mcsum != 0) {
+ for (int i = 0; i < segments.length; ++i) {
+ check += segments[i].count;
+ if (mc[i] != segments[i].modCount) {
+ check = -1; // force retry
+ break;
+ }
+ }
+ }
+ if (check == sum)
+ break;
+ }
+ if (check != sum) { // Resort to locking all segments
+ sum = 0;
+ for (int i = 0; i < segments.length; ++i)
+ segments[i].lock();
+ for (int i = 0; i < segments.length; ++i)
+ sum += segments[i].count;
+ for (int i = 0; i < segments.length; ++i)
+ segments[i].unlock();
+ }
+ if (sum > Integer.MAX_VALUE)
+ return Integer.MAX_VALUE;
+ else
+ return (int)sum;
+ }
+
+ /**
+ * Returns the value to which the specified key is mapped,
+ * or {@code null} if this map contains no mapping for the key.
+ *
+ * <p>More formally, if this map contains a mapping from a key
+ * {@code k} to a value {@code v} such that {@code key.equals(k)},
+ * then this method returns {@code v}; otherwise it returns
+ * {@code null}. (There can be at most one such mapping.)
+ *
+ * @throws NullPointerException if the specified key is null
+ */
+ public V get(Object key) {
+ int hash = hashOf(key);
+ return segmentFor(hash).get(key, hash);
+ }
+
+ /**
+ * Tests if the specified object is a key in this table.
+ *
+ * @param key possible key
+ * @return <tt>true</tt> if and only if the specified object
+ * is a key in this table, as determined by the
+ * <tt>equals</tt> method; <tt>false</tt> otherwise.
+ * @throws NullPointerException if the specified key is null
+ */
+ public boolean containsKey(Object key) {
+ int hash = hashOf(key);
+ return segmentFor(hash).containsKey(key, hash);
+ }
+
+ /**
+ * Returns <tt>true</tt> if this map maps one or more keys to the
+ * specified value. Note: This method requires a full internal
+ * traversal of the hash table, and so is much slower than
+ * method <tt>containsKey</tt>.
+ *
+ * @param value value whose presence in this map is to be tested
+ * @return <tt>true</tt> if this map maps one or more keys to the
+ * specified value
+ * @throws NullPointerException if the specified value is null
+ */
+ public boolean containsValue(Object value) {
+ if (value == null)
+ throw new NullPointerException();
+
+ // See explanation of modCount use above
+
+ final Segment<K,V>[] segments = this.segments;
+ int[] mc = new int[segments.length];
+
+ // Try a few times without locking
+ for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
+ int sum = 0;
+ int mcsum = 0;
+ for (int i = 0; i < segments.length; ++i) {
+ int c = segments[i].count;
+ mcsum += mc[i] = segments[i].modCount;
+ if (segments[i].containsValue(value))
+ return true;
+ }
+ boolean cleanSweep = true;
+ if (mcsum != 0) {
+ for (int i = 0; i < segments.length; ++i) {
+ int c = segments[i].count;
+ if (mc[i] != segments[i].modCount) {
+ cleanSweep = false;
+ break;
+ }
+ }
+ }
+ if (cleanSweep)
+ return false;
+ }
+ // Resort to locking all segments
+ for (int i = 0; i < segments.length; ++i)
+ segments[i].lock();
+ boolean found = false;
+ try {
+ for (int i = 0; i < segments.length; ++i) {
+ if (segments[i].containsValue(value)) {
+ found = true;
+ break;
+ }
+ }
+ } finally {
+ for (int i = 0; i < segments.length; ++i)
+ segments[i].unlock();
+ }
+ return found;
+ }
+
+ /**
+ * Legacy method testing if some key maps into the specified value
+ * in this table. This method is identical in functionality to
+ * {@link #containsValue}, and exists solely to ensure
+ * full compatibility with class {@link java.util.Hashtable},
+ * which supported this method prior to introduction of the
+ * Java Collections framework.
+
+ * @param value a value to search for
+ * @return <tt>true</tt> if and only if some key maps to the
+ * <tt>value</tt> argument in this table as
+ * determined by the <tt>equals</tt> method;
+ * <tt>false</tt> otherwise
+ * @throws NullPointerException if the specified value is null
+ */
+ public boolean contains(Object value) {
+ return containsValue(value);
+ }
+
+ /**
+ * Maps the specified key to the specified value in this table.
+ * Neither the key nor the value can be null.
+ *
+ * <p> The value can be retrieved by calling the <tt>get</tt> method
+ * with a key that is equal to the original key.
+ *
+ * @param key key with which the specified value is to be associated
+ * @param value value to be associated with the specified key
+ * @return the previous value associated with <tt>key</tt>, or
+ * <tt>null</tt> if there was no mapping for <tt>key</tt>
+ * @throws NullPointerException if the specified key or value is null
+ */
+ public V put(K key, V value) {
+ if (value == null)
+ throw new NullPointerException();
+ int hash = hashOf(key);
+ return segmentFor(hash).put(key, hash, value, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return the previous value associated with the specified key,
+ * or <tt>null</tt> if there was no mapping for the key
+ * @throws NullPointerException if the specified key or value is null
+ */
+ public V putIfAbsent(K key, V value) {
+ if (value == null)
+ throw new NullPointerException();
+ int hash = hashOf(key);
+ return segmentFor(hash).put(key, hash, value, true);
+ }
+
+ /**
+ * Copies all of the mappings from the specified map to this one.
+ * These mappings replace any mappings that this map had for any of the
+ * keys currently in the specified map.
+ *
+ * @param m mappings to be stored in this map
+ */
+ public void putAll(Map<? extends K, ? extends V> m) {
+ for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
+ put(e.getKey(), e.getValue());
+ }
+
+ /**
+ * Removes the key (and its corresponding value) from this map.
+ * This method does nothing if the key is not in the map.
+ *
+ * @param key the key that needs to be removed
+ * @return the previous value associated with <tt>key</tt>, or
+ * <tt>null</tt> if there was no mapping for <tt>key</tt>
+ * @throws NullPointerException if the specified key is null
+ */
+ public V remove(Object key) {
+ int hash = hashOf(key);
+ return segmentFor(hash).remove(key, hash, null, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws NullPointerException if the specified key is null
+ */
+ public boolean remove(Object key, Object value) {
+ int hash = hashOf(key);
+ if (value == null)
+ return false;
+ return segmentFor(hash).remove(key, hash, value, false) != null;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws NullPointerException if any of the arguments are null
+ */
+ public boolean replace(K key, V oldValue, V newValue) {
+ if (oldValue == null || newValue == null)
+ throw new NullPointerException();
+ int hash = hashOf(key);
+ return segmentFor(hash).replace(key, hash, oldValue, newValue);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return the previous value associated with the specified key,
+ * or <tt>null</tt> if there was no mapping for the key
+ * @throws NullPointerException if the specified key or value is null
+ */
+ public V replace(K key, V value) {
+ if (value == null)
+ throw new NullPointerException();
+ int hash = hashOf(key);
+ return segmentFor(hash).replace(key, hash, value);
+ }
+
+ /**
+ * Removes all of the mappings from this map.
+ */
+ public void clear() {
+ for (int i = 0; i < segments.length; ++i)
+ segments[i].clear();
+ }
+
+ /**
+ * Removes any stale entries whose keys have been finalized. Use of this
+ * method is normally not necessary since stale entries are automatically
+ * removed lazily, when blocking operations are required. However, there
+ * are some cases where this operation should be performed eagerly, such
+ * as cleaning up old references to a ClassLoader in a multi-classloader
+ * environment.
+ *
+ * Note: this method will acquire locks, one at a time, across all segments
+ * of this table, so if it is to be used, it should be used sparingly.
+ */
+ public void purgeStaleEntries() {
+ for (int i = 0; i < segments.length; ++i)
+ segments[i].removeStale();
+ }
+
+
+ /**
+ * Returns a {@link Set} view of the keys contained in this map.
+ * The set is backed by the map, so changes to the map are
+ * reflected in the set, and vice-versa. The set supports element
+ * removal, which removes the corresponding mapping from this map,
+ * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
+ * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
+ * operations. It does not support the <tt>add</tt> or
+ * <tt>addAll</tt> operations.
+ *
+ * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
+ * that will never throw {@link ConcurrentModificationException},
+ * and guarantees to traverse elements as they existed upon
+ * construction of the iterator, and may (but is not guaranteed to)
+ * reflect any modifications subsequent to construction.
+ */
+ public Set<K> keySet() {
+ Set<K> ks = keySet;
+ return (ks != null) ? ks : (keySet = new KeySet());
+ }
+
+ /**
+ * Returns a {@link Collection} view of the values contained in this map.
+ * The collection is backed by the map, so changes to the map are
+ * reflected in the collection, and vice-versa. The collection
+ * supports element removal, which removes the corresponding
+ * mapping from this map, via the <tt>Iterator.remove</tt>,
+ * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
+ * <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not
+ * support the <tt>add</tt> or <tt>addAll</tt> operations.
+ *
+ * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
+ * that will never throw {@link ConcurrentModificationException},
+ * and guarantees to traverse elements as they existed upon
+ * construction of the iterator, and may (but is not guaranteed to)
+ * reflect any modifications subsequent to construction.
+ */
+ public Collection<V> values() {
+ Collection<V> vs = values;
+ return (vs != null) ? vs : (values = new Values());
+ }
+
+ /**
+ * Returns a {@link Set} view of the mappings contained in this map.
+ * The set is backed by the map, so changes to the map are
+ * reflected in the set, and vice-versa. The set supports element
+ * removal, which removes the corresponding mapping from the map,
+ * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
+ * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
+ * operations. It does not support the <tt>add</tt> or
+ * <tt>addAll</tt> operations.
+ *
+ * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
+ * that will never throw {@link ConcurrentModificationException},
+ * and guarantees to traverse elements as they existed upon
+ * construction of the iterator, and may (but is not guaranteed to)
+ * reflect any modifications subsequent to construction.
+ */
+ public Set<Map.Entry<K,V>> entrySet() {
+ Set<Map.Entry<K,V>> es = entrySet;
+ return (es != null) ? es : (entrySet = new EntrySet());
+ }
+
+ /**
+ * Returns an enumeration of the keys in this table.
+ *
+ * @return an enumeration of the keys in this table
+ * @see #keySet()
+ */
+ public Enumeration<K> keys() {
+ return new KeyIterator();
+ }
+
+ /**
+ * Returns an enumeration of the values in this table.
+ *
+ * @return an enumeration of the values in this table
+ * @see #values()
+ */
+ public Enumeration<V> elements() {
+ return new ValueIterator();
+ }
+
+ /* ---------------- Iterator Support -------------- */
+
+ abstract class HashIterator {
+ int nextSegmentIndex;
+ int nextTableIndex;
+ HashEntry<K,V>[] currentTable;
+ HashEntry<K, V> nextEntry;
+ HashEntry<K, V> lastReturned;
+ K currentKey; // Strong reference to weak key (prevents gc)
+
+ HashIterator() {
+ nextSegmentIndex = segments.length - 1;
+ nextTableIndex = -1;
+ advance();
+ }
+
+ public boolean hasMoreElements() { return hasNext(); }
+
+ final void advance() {
+ if (nextEntry != null && (nextEntry = nextEntry.next) != null)
+ return;
+
+ while (nextTableIndex >= 0) {
+ if ( (nextEntry = currentTable[nextTableIndex--]) != null)
+ return;
+ }
+
+ while (nextSegmentIndex >= 0) {
+ Segment<K,V> seg = segments[nextSegmentIndex--];
+ if (seg.count != 0) {
+ currentTable = seg.table;
+ for (int j = currentTable.length - 1; j >= 0; --j) {
+ if ( (nextEntry = currentTable[j]) != null) {
+ nextTableIndex = j - 1;
+ return;
+ }
+ }
+ }
+ }
+ }
+
+ public boolean hasNext() {
+ while (nextEntry != null) {
+ if (nextEntry.key() != null)
+ return true;
+ advance();
+ }
+
+ return false;
+ }
+
+ HashEntry<K,V> nextEntry() {
+ do {
+ if (nextEntry == null)
+ throw new NoSuchElementException();
+
+ lastReturned = nextEntry;
+ currentKey = lastReturned.key();
+ advance();
+ } while (currentKey == null); // Skip GC'd keys
+
+ return lastReturned;
+ }
+
+ public void remove() {
+ if (lastReturned == null)
+ throw new IllegalStateException();
+ ConcurrentReferenceHashMap.this.remove(currentKey);
+ lastReturned = null;
+ }
+ }
+
+ final class KeyIterator
+ extends HashIterator
+ implements Iterator<K>, Enumeration<K>
+ {
+ public K next() { return super.nextEntry().key(); }
+ public K nextElement() { return super.nextEntry().key(); }
+ }
+
+ final class ValueIterator
+ extends HashIterator
+ implements Iterator<V>, Enumeration<V>
+ {
+ public V next() { return super.nextEntry().value(); }
+ public V nextElement() { return super.nextEntry().value(); }
+ }
+
+ /*
+ * This class is needed for JDK5 compatibility.
+ */
+ static class SimpleEntry<K, V> implements Entry<K, V>,
+ java.io.Serializable {
+ private static final long serialVersionUID = -8499721149061103585L;
+
+ private final K key;
+ private V value;
+
+ public SimpleEntry(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ public SimpleEntry(Entry<? extends K, ? extends V> entry) {
+ this.key = entry.getKey();
+ this.value = entry.getValue();
+ }
+
+ public K getKey() {
+ return key;
+ }
+
+ public V getValue() {
+ return value;
+ }
+
+ public V setValue(V value) {
+ V oldValue = this.value;
+ this.value = value;
+ return oldValue;
+ }
+
+ public boolean equals(Object o) {
+ if (!(o instanceof Map.Entry))
+ return false;
+ @SuppressWarnings("unchecked")
+ Map.Entry e = (Map.Entry) o;
+ return eq(key, e.getKey()) && eq(value, e.getValue());
+ }
+
+ public int hashCode() {
+ return (key == null ? 0 : key.hashCode())
+ ^ (value == null ? 0 : value.hashCode());
+ }
+
+ public String toString() {
+ return key + "=" + value;
+ }
+
+ private static boolean eq(Object o1, Object o2) {
+ return o1 == null ? o2 == null : o1.equals(o2);
+ }
+ }
+
+
+ /**
+ * Custom Entry class used by EntryIterator.next(), that relays setValue
+ * changes to the underlying map.
+ */
+ final class WriteThroughEntry extends SimpleEntry<K,V>
+ {
+ private static final long serialVersionUID = -7900634345345313646L;
+
+ WriteThroughEntry(K k, V v) {
+ super(k,v);
+ }
+
+ /**
+ * Set our entry's value and write through to the map. The
+ * value to return is somewhat arbitrary here. Since a
+ * WriteThroughEntry does not necessarily track asynchronous
+ * changes, the most recent "previous" value could be
+ * different from what we return (or could even have been
+ * removed in which case the put will re-establish). We do not
+ * and cannot guarantee more.
+ */
+ public V setValue(V value) {
+ if (value == null) throw new NullPointerException();
+ V v = super.setValue(value);
+ ConcurrentReferenceHashMap.this.put(getKey(), value);
+ return v;
+ }
+ }
+
+ final class EntryIterator
+ extends HashIterator
+ implements Iterator<Entry<K,V>>
+ {
+ public Map.Entry<K,V> next() {
+ HashEntry<K,V> e = super.nextEntry();
+ return new WriteThroughEntry(e.key(), e.value());
+ }
+ }
+
+ final class KeySet extends AbstractSet<K> {
+ public Iterator<K> iterator() {
+ return new KeyIterator();
+ }
+ public int size() {
+ return ConcurrentReferenceHashMap.this.size();
+ }
+ public boolean isEmpty() {
+ return ConcurrentReferenceHashMap.this.isEmpty();
+ }
+ public boolean contains(Object o) {
+ return ConcurrentReferenceHashMap.this.containsKey(o);
+ }
+ public boolean remove(Object o) {
+ return ConcurrentReferenceHashMap.this.remove(o) != null;
+ }
+ public void clear() {
+ ConcurrentReferenceHashMap.this.clear();
+ }
+ }
+
+ final class Values extends AbstractCollection<V> {
+ public Iterator<V> iterator() {
+ return new ValueIterator();
+ }
+ public int size() {
+ return ConcurrentReferenceHashMap.this.size();
+ }
+ public boolean isEmpty() {
+ return ConcurrentReferenceHashMap.this.isEmpty();
+ }
+ public boolean contains(Object o) {
+ return ConcurrentReferenceHashMap.this.containsValue(o);
+ }
+ public void clear() {
+ ConcurrentReferenceHashMap.this.clear();
+ }
+ }
+
+ final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
+ public Iterator<Map.Entry<K,V>> iterator() {
+ return new EntryIterator();
+ }
+ public boolean contains(Object o) {
+ if (!(o instanceof Map.Entry))
+ return false;
+ Map.Entry<?,?> e = (Map.Entry<?,?>)o;
+ V v = ConcurrentReferenceHashMap.this.get(e.getKey());
+ return v != null && v.equals(e.getValue());
+ }
+ public boolean remove(Object o) {
+ if (!(o instanceof Map.Entry))
+ return false;
+ Map.Entry<?,?> e = (Map.Entry<?,?>)o;
+ return ConcurrentReferenceHashMap.this.remove(e.getKey(), e.getValue());
+ }
+ public int size() {
+ return ConcurrentReferenceHashMap.this.size();
+ }
+ public boolean isEmpty() {
+ return ConcurrentReferenceHashMap.this.isEmpty();
+ }
+ public void clear() {
+ ConcurrentReferenceHashMap.this.clear();
+ }
+ }
+
+ /* ---------------- Serialization Support -------------- */
+
+ /**
+ * Save the state of the <tt>ConcurrentReferenceHashMap</tt> instance to a
+ * stream (i.e., serialize it).
+ * @param s the stream
+ * @serialData
+ * the key (Object) and value (Object)
+ * for each key-value mapping, followed by a null pair.
+ * The key-value mappings are emitted in no particular order.
+ */
+ private void writeObject(java.io.ObjectOutputStream s) throws IOException {
+ s.defaultWriteObject();
+
+ for (int k = 0; k < segments.length; ++k) {
+ Segment<K,V> seg = segments[k];
+ seg.lock();
+ try {
+ HashEntry<K,V>[] tab = seg.table;
+ for (int i = 0; i < tab.length; ++i) {
+ for (HashEntry<K,V> e = tab[i]; e != null; e = e.next) {
+ K key = e.key();
+ if (key == null) // Skip GC'd keys
+ continue;
+
+ s.writeObject(key);
+ s.writeObject(e.value());
+ }
+ }
+ } finally {
+ seg.unlock();
+ }
+ }
+ s.writeObject(null);
+ s.writeObject(null);
+ }
+
+ /**
+ * Reconstitute the <tt>ConcurrentReferenceHashMap</tt> instance from a
+ * stream (i.e., deserialize it).
+ * @param s the stream
+ */
+ @SuppressWarnings("unchecked")
+ private void readObject(java.io.ObjectInputStream s)
+ throws IOException, ClassNotFoundException {
+ s.defaultReadObject();
+
+ // Initialize each segment to be minimally sized, and let grow.
+ for (int i = 0; i < segments.length; ++i) {
+ segments[i].setTable(new HashEntry[1]);
+ }
+
+ // Read the keys and values, and put the mappings in the table
+ for (;;) {
+ K key = (K) s.readObject();
+ V value = (V) s.readObject();
+ if (key == null)
+ break;
+ put(key, value);
+ }
+ }
+}
Copied: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/NamingThreadFactory.java (from rev 4696, remoting3/trunk/util/src/main/java/org/jboss/remoting/util/NamingThreadFactory.java)
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/NamingThreadFactory.java (rev 0)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/NamingThreadFactory.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -0,0 +1,35 @@
+package org.jboss.remoting.core.util;
+
+import java.util.concurrent.ThreadFactory;
+
+/**
+ * A wrapper {@code ThreadFactory} that gives the threads a sensible name.
+ */
+public final class NamingThreadFactory implements ThreadFactory {
+ private final ThreadFactory delegate;
+ private final String namePattern;
+
+ /**
+ * Create a new instance. The pattern is a format string such as one would provide to
+ * {@link String#format(String, Object[])}. The format string should contain one {@code %s} which will be replaced
+ * with the original thread name.
+ *
+ * @param delegate the thread factory to actually use to produce the thread
+ * @param namePattern the name pattern to apply
+ */
+ public NamingThreadFactory(final ThreadFactory delegate, final String namePattern) {
+ this.delegate = delegate;
+ this.namePattern = namePattern;
+ }
+
+ public Thread newThread(final Runnable r) {
+ final Thread thread = delegate.newThread(r);
+ final String originalName = thread.getName();
+ try {
+ thread.setName(String.format(namePattern, originalName));
+ } catch (SecurityException ex) {
+ // oh well, we tried
+ }
+ return thread;
+ }
+}
Copied: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/OrderedExecutor.java (from rev 4696, remoting3/trunk/util/src/main/java/org/jboss/remoting/util/OrderedExecutor.java)
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/OrderedExecutor.java (rev 0)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/OrderedExecutor.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -0,0 +1,95 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, 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.jboss.remoting.core.util;
+
+import java.util.LinkedList;
+import java.util.concurrent.Executor;
+import org.jboss.xnio.log.Logger;
+
+/**
+ * An executor that always runs all tasks in order, using a delegate executor to run the tasks.
+ * <p/>
+ * More specifically, any call B to the {@link #execute(Runnable)} method that happens-after another call A to the
+ * same method, will result in B's task running after A's.
+ */
+public final class OrderedExecutor implements Executor {
+ private static final Logger log = Logger.getLogger(OrderedExecutor.class);
+
+ // @protectedby tasks
+ private final LinkedList<Runnable> tasks = new LinkedList<Runnable>();
+ // @protectedby tasks
+ private boolean running;
+ private final Executor parent;
+ private final Runnable runner;
+
+ /**
+ * Construct a new instance.
+ *
+ * @param parent the parent executor
+ */
+ public OrderedExecutor(final Executor parent) {
+ this.parent = parent;
+ runner = new Runnable() {
+ public void run() {
+ for (;;) {
+ final Runnable task;
+ synchronized(tasks) {
+ task = tasks.poll();
+ if (task == null) {
+ running = false;
+ return;
+ }
+ }
+ try {
+ task.run();
+ } catch (Throwable t) {
+ log.error(t, "Runnable task %s failed", task);
+ }
+ }
+ }
+ };
+ }
+
+ /**
+ * Run a task.
+ *
+ * @param command the task to run.
+ */
+ public void execute(Runnable command) {
+ synchronized(tasks) {
+ tasks.add(command);
+ if (! running) {
+ running = true;
+ boolean ok = false;
+ try {
+ parent.execute(runner);
+ ok = true;
+ } finally {
+ if (! ok) {
+ running = false;
+ }
+ }
+ }
+ }
+ }
+}
Copied: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/OrderedExecutorFactory.java (from rev 4696, remoting3/trunk/util/src/main/java/org/jboss/remoting/util/OrderedExecutorFactory.java)
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/OrderedExecutorFactory.java (rev 0)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/OrderedExecutorFactory.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -0,0 +1,28 @@
+package org.jboss.remoting.core.util;
+
+import java.util.concurrent.Executor;
+
+/**
+ * A factory for producing executors that run all tasks in order, which delegate to a single common executor instance.
+ */
+public final class OrderedExecutorFactory {
+ private final Executor parent;
+
+ /**
+ * Construct a new instance delegating to the given parent executor.
+ *
+ * @param parent the parent executor
+ */
+ public OrderedExecutorFactory(final Executor parent) {
+ this.parent = parent;
+ }
+
+ /**
+ * Get an executor that always executes tasks in order.
+ *
+ * @return an ordered executor
+ */
+ public Executor getOrderedExecutor() {
+ return new OrderedExecutor(parent);
+ }
+}
Copied: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedCollection.java (from rev 4696, remoting3/trunk/util/src/main/java/org/jboss/remoting/util/SynchronizedCollection.java)
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedCollection.java (rev 0)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedCollection.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -0,0 +1,118 @@
+package org.jboss.remoting.core.util;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+/**
+ *
+ */
+public class SynchronizedCollection<V> implements Collection<V> {
+ private final Collection<V> delegate;
+ private final Object monitor;
+
+ public SynchronizedCollection(final Collection<V> delegate) {
+ this.delegate = delegate;
+ monitor = this;
+ }
+
+ public SynchronizedCollection(final Collection<V> delegate, final Object monitor) {
+ this.delegate = delegate;
+ this.monitor = monitor;
+ }
+
+ public int size() {
+ synchronized (monitor) {
+ return delegate.size();
+ }
+ }
+
+ public boolean isEmpty() {
+ synchronized (monitor) {
+ return delegate.isEmpty();
+ }
+ }
+
+ public boolean contains(final Object o) {
+ synchronized (monitor) {
+ return delegate.contains(o);
+ }
+ }
+
+ public Iterator<V> iterator() {
+ synchronized (monitor) {
+ return new SynchronizedIterator<V>(delegate.iterator(), monitor);
+ }
+ }
+
+ public Object[] toArray() {
+ synchronized (monitor) {
+ return delegate.toArray();
+ }
+ }
+
+ public <T> T[] toArray(final T[] a) {
+ synchronized (monitor) {
+ return delegate.toArray(a);
+ }
+ }
+
+ public boolean add(final V o) {
+ synchronized (monitor) {
+ return delegate.add(o);
+ }
+ }
+
+ public boolean remove(final Object o) {
+ synchronized (monitor) {
+ return delegate.remove(o);
+ }
+ }
+
+ public boolean containsAll(final Collection<?> c) {
+ synchronized (monitor) {
+ return delegate.containsAll(c);
+ }
+ }
+
+ public boolean addAll(final Collection<? extends V> c) {
+ synchronized (monitor) {
+ return delegate.addAll(c);
+ }
+ }
+
+ public boolean removeAll(final Collection<?> c) {
+ synchronized (monitor) {
+ return delegate.removeAll(c);
+ }
+ }
+
+ public boolean retainAll(final Collection<?> c) {
+ synchronized (monitor) {
+ return delegate.retainAll(c);
+ }
+ }
+
+ public void clear() {
+ synchronized (monitor) {
+ delegate.clear();
+ }
+ }
+
+ public boolean equals(final Object o) {
+ synchronized (monitor) {
+ return delegate.equals(o);
+ }
+ }
+
+ public int hashCode() {
+ synchronized (monitor) {
+ return delegate.hashCode();
+ }
+ }
+
+ public String toString() {
+ synchronized (monitor) {
+ return delegate.toString();
+ }
+ }
+}
Copied: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedIterator.java (from rev 4696, remoting3/trunk/util/src/main/java/org/jboss/remoting/util/SynchronizedIterator.java)
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedIterator.java (rev 0)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedIterator.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -0,0 +1,52 @@
+package org.jboss.remoting.core.util;
+
+import java.util.Iterator;
+
+/**
+ *
+ */
+public class SynchronizedIterator<T> implements Iterator<T> {
+ private final Iterator<T> delegate;
+ private final Object monitor;
+
+ protected SynchronizedIterator(final Iterator<T> delegate, final Object monitor) {
+ this.delegate = delegate;
+ this.monitor = monitor;
+ }
+
+ public boolean hasNext() {
+ synchronized (monitor) {
+ return delegate.hasNext();
+ }
+ }
+
+ public T next() {
+ synchronized (monitor) {
+ return delegate.next();
+ }
+ }
+
+ public void remove() {
+ synchronized (monitor) {
+ delegate.remove();
+ }
+ }
+
+ public int hashCode() {
+ synchronized (monitor) {
+ return delegate.hashCode();
+ }
+ }
+
+ public boolean equals(Object obj) {
+ synchronized (monitor) {
+ return delegate.equals(obj);
+ }
+ }
+
+ public String toString() {
+ synchronized (monitor) {
+ return delegate.toString();
+ }
+ }
+}
Copied: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedMap.java (from rev 4696, remoting3/trunk/util/src/main/java/org/jboss/remoting/util/SynchronizedMap.java)
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedMap.java (rev 0)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedMap.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -0,0 +1,156 @@
+package org.jboss.remoting.core.util;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ *
+ */
+public class SynchronizedMap<K, V> implements ConcurrentMap<K, V> {
+ private final Object monitor;
+ private final Map<K, V> delegate;
+
+ public SynchronizedMap(final Map<K, V> delegate) {
+ this.delegate = delegate;
+ monitor = this;
+ }
+
+ protected SynchronizedMap(final Map<K, V> delegate, final Object monitor) {
+ this.monitor = monitor;
+ this.delegate = delegate;
+ }
+
+ public int size() {
+ synchronized (monitor) {
+ return delegate.size();
+ }
+ }
+
+ public boolean isEmpty() {
+ synchronized (monitor) {
+ return delegate.isEmpty();
+ }
+ }
+
+ public boolean containsKey(final Object key) {
+ synchronized (monitor) {
+ return delegate.containsKey(key);
+ }
+ }
+
+ public boolean containsValue(final Object value) {
+ synchronized (monitor) {
+ return delegate.containsValue(value);
+ }
+ }
+
+ public V get(final Object key) {
+ synchronized (monitor) {
+ return delegate.get(key);
+ }
+ }
+
+ public V put(final K key, final V value) {
+ synchronized (monitor) {
+ return delegate.put(key, value);
+ }
+ }
+
+ public V remove(final Object key) {
+ synchronized (monitor) {
+ return delegate.remove(key);
+ }
+ }
+
+ public void putAll(final Map<? extends K, ? extends V> t) {
+ synchronized (monitor) {
+ delegate.putAll(t);
+ }
+ }
+
+ public void clear() {
+ synchronized (monitor) {
+ delegate.clear();
+ }
+ }
+
+ public Set<K> keySet() {
+ synchronized (monitor) {
+ return new SynchronizedSet<K>(delegate.keySet(), monitor);
+ }
+ }
+
+ public Collection<V> values() {
+ synchronized (monitor) {
+ return new SynchronizedCollection<V>(delegate.values(), monitor);
+ }
+ }
+
+ public Set<Entry<K, V>> entrySet() {
+ synchronized (monitor) {
+ return new SynchronizedSet<Entry<K, V>>(delegate.entrySet(), monitor);
+ }
+ }
+
+ public boolean equals(final Object o) {
+ synchronized (monitor) {
+ return delegate.equals(o);
+ }
+ }
+
+ public int hashCode() {
+ synchronized (monitor) {
+ return delegate.hashCode();
+ }
+ }
+
+ public V putIfAbsent(final K key, final V value) {
+ synchronized (monitor) {
+ if (delegate.containsKey(key)) {
+ return delegate.get(key);
+ } else {
+ return delegate.put(key, value);
+ }
+ }
+ }
+
+ public boolean remove(final Object key, final Object value) {
+ synchronized (monitor) {
+ if (delegate.containsKey(key) && (value == null && delegate.get(key) == null || delegate.get(key).equals(value))) {
+ delegate.remove(key);
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ public boolean replace(final K key, final V oldValue, final V newValue) {
+ synchronized (monitor) {
+ if (delegate.containsKey(key) && (oldValue == null ? delegate.get(key) == null : delegate.get(key).equals(oldValue))) {
+ delegate.put(key, newValue);
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ public V replace(final K key, final V value) {
+ synchronized (monitor) {
+ if (delegate.containsKey(key)) {
+ return delegate.put(key, value);
+ } else {
+ return null;
+ }
+ }
+ }
+
+ public String toString() {
+ synchronized (monitor) {
+ return delegate.toString();
+ }
+ }
+}
Copied: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedQueue.java (from rev 4696, remoting3/trunk/util/src/main/java/org/jboss/remoting/util/SynchronizedQueue.java)
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedQueue.java (rev 0)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedQueue.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -0,0 +1,249 @@
+package org.jboss.remoting.core.util;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Queue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+/**
+ *
+ */
+public class SynchronizedQueue<T> implements BlockingQueue<T> {
+ private final Queue<T> delegate;
+ private final Object monitor;
+
+ public SynchronizedQueue(final Queue<T> delegate) {
+ this.delegate = delegate;
+ monitor = this;
+ }
+
+ protected SynchronizedQueue(final Queue<T> delegate, final Object monitor) {
+ this.monitor = monitor;
+ this.delegate = delegate;
+ }
+
+ public boolean offer(final T o) {
+ synchronized(monitor) {
+ return delegate.offer(o);
+ }
+ }
+
+ public T poll() {
+ synchronized(monitor) {
+ return delegate.poll();
+ }
+ }
+
+ public T remove() {
+ synchronized(monitor) {
+ return delegate.remove();
+ }
+ }
+
+ public T peek() {
+ synchronized(monitor) {
+ return delegate.peek();
+ }
+ }
+
+ public T element() {
+ synchronized(monitor) {
+ return delegate.element();
+ }
+ }
+
+ public int size() {
+ synchronized(monitor) {
+ return delegate.size();
+ }
+ }
+
+ public boolean isEmpty() {
+ synchronized(monitor) {
+ return delegate.isEmpty();
+ }
+ }
+
+ public boolean contains(final Object o) {
+ synchronized(monitor) {
+ return delegate.contains(o);
+ }
+ }
+
+ public Iterator<T> iterator() {
+ synchronized(monitor) {
+ return delegate.iterator();
+ }
+ }
+
+ public Object[] toArray() {
+ synchronized(monitor) {
+ return delegate.toArray();
+ }
+ }
+
+ public <U> U[] toArray(final U[] a) {
+ synchronized(monitor) {
+ //noinspection SuspiciousToArrayCall
+ return delegate.toArray(a);
+ }
+ }
+
+ public boolean add(final T o) {
+ synchronized(monitor) {
+ return delegate.add(o);
+ }
+ }
+
+ public boolean remove(final Object o) {
+ synchronized(monitor) {
+ return delegate.remove(o);
+ }
+ }
+
+ public boolean containsAll(final Collection<?> c) {
+ synchronized(monitor) {
+ return delegate.containsAll(c);
+ }
+ }
+
+ public boolean addAll(final Collection<? extends T> c) {
+ synchronized(monitor) {
+ return delegate.addAll(c);
+ }
+ }
+
+ public boolean removeAll(final Collection<?> c) {
+ synchronized(monitor) {
+ return delegate.removeAll(c);
+ }
+ }
+
+ public boolean retainAll(final Collection<?> c) {
+ synchronized(monitor) {
+ return delegate.retainAll(c);
+ }
+ }
+
+ public void clear() {
+ synchronized(monitor) {
+ delegate.clear();
+ }
+ }
+
+ public boolean equals(final Object o) {
+ synchronized(monitor) {
+ return delegate.equals(o);
+ }
+ }
+
+ public int hashCode() {
+ synchronized(monitor) {
+ return delegate.hashCode();
+ }
+ }
+
+ public boolean offer(final T o, final long timeout, final TimeUnit unit) throws InterruptedException {
+ long startTime = System.currentTimeMillis();
+ long timeoutMillis = unit.toMillis(timeout);
+ long deadline = startTime + timeoutMillis < 0L ? Long.MAX_VALUE : startTime + timeoutMillis;
+ synchronized(monitor) {
+ for (;;) {
+ if (offer(o)) {
+ return true;
+ }
+ if (deadline <= startTime) {
+ return false;
+ }
+ monitor.wait(deadline - startTime);
+ startTime = System.currentTimeMillis();
+ }
+ }
+ }
+
+ public T poll(final long timeout, final TimeUnit unit) throws InterruptedException {
+ long startTime = System.currentTimeMillis();
+ long timeoutMillis = unit.toMillis(timeout);
+ long deadline = startTime + timeoutMillis < 0L ? Long.MAX_VALUE : startTime + timeoutMillis;
+ synchronized(monitor) {
+ for (;;) {
+ final T v = poll();
+ if (v != null) {
+ return v;
+ }
+ if (deadline <= startTime) {
+ return null;
+ }
+ monitor.wait(deadline - startTime);
+ startTime = System.currentTimeMillis();
+ }
+ }
+ }
+
+ public T take() throws InterruptedException {
+ synchronized(monitor) {
+ for (;;) {
+ final T v = poll();
+ if (v != null) {
+ return v;
+ }
+ monitor.wait();
+ }
+ }
+ }
+
+ public void put(final T o) throws InterruptedException {
+ synchronized(monitor) {
+ for(;;) {
+ if (add(o)) {
+ return;
+ }
+ monitor.wait();
+ }
+ }
+ }
+
+ public int remainingCapacity() {
+ return Integer.MAX_VALUE;
+ }
+
+ public int drainTo(final Collection<? super T> c) {
+ if (c == this) {
+ throw new IllegalArgumentException("Attempt to drain queue to itself");
+ }
+ int cnt = 0;
+ synchronized(monitor) {
+ for (;;) {
+ T v = poll();
+ if (v == null) {
+ return cnt;
+ } else {
+ c.add(v);
+ cnt++;
+ }
+ }
+ }
+ }
+
+ public int drainTo(final Collection<? super T> c, final int maxElements) {
+ if (c == this) {
+ throw new IllegalArgumentException("Attempt to drain queue to itself");
+ }
+ int cnt = 0;
+ synchronized(monitor) {
+ for (;;) {
+ T v = poll();
+ if (v == null) {
+ return cnt;
+ } else {
+ c.add(v);
+ cnt++;
+ if (cnt == maxElements) {
+ return cnt;
+ }
+ }
+ }
+ }
+ }
+}
Copied: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedSet.java (from rev 4696, remoting3/trunk/util/src/main/java/org/jboss/remoting/util/SynchronizedSet.java)
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedSet.java (rev 0)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/SynchronizedSet.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -0,0 +1,17 @@
+package org.jboss.remoting.core.util;
+
+import java.util.Set;
+
+/**
+ *
+ */
+public class SynchronizedSet<K> extends SynchronizedCollection<K> implements Set<K> {
+
+ public SynchronizedSet(final Set<K> delegate) {
+ super(delegate);
+ }
+
+ public SynchronizedSet(final Set<K> delegate, final Object monitor) {
+ super(delegate, monitor);
+ }
+}
Copied: remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/WeakHashSet.java (from rev 4696, remoting3/trunk/util/src/main/java/org/jboss/remoting/util/WeakHashSet.java)
===================================================================
--- remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/WeakHashSet.java (rev 0)
+++ remoting3/trunk/core/src/main/java/org/jboss/remoting/core/util/WeakHashSet.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -0,0 +1,76 @@
+package org.jboss.remoting.core.util;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.WeakHashMap;
+
+/**
+ *
+ */
+public final class WeakHashSet<T> implements Set<T> {
+ private final WeakHashMap<T,Void> map = new WeakHashMap<T,Void>();
+
+ public int size() {
+ return map.size();
+ }
+
+ public boolean isEmpty() {
+ return map.isEmpty();
+ }
+
+ public boolean contains(final Object o) {
+ return map.containsKey(o);
+ }
+
+ public Iterator<T> iterator() {
+ return map.keySet().iterator();
+ }
+
+ public Object[] toArray() {
+ return map.keySet().toArray();
+ }
+
+ public <U> U[] toArray(final U[] a) {
+ return map.keySet().toArray(a);
+ }
+
+ public boolean add(final T o) {
+ try {
+ return ! map.containsKey(o);
+ } finally {
+ map.put(o, null);
+ }
+ }
+
+ public boolean remove(final Object o) {
+ return map.keySet().remove(o);
+ }
+
+ public boolean containsAll(final Collection<?> c) {
+ return map.keySet().containsAll(c);
+ }
+
+ public boolean addAll(final Collection<? extends T> c) {
+ boolean changed = false;
+ for (T t : c) {
+ if (! map.containsKey(t)) {
+ changed = true;
+ map.put(t, null);
+ }
+ }
+ return changed;
+ }
+
+ public boolean retainAll(final Collection<?> c) {
+ return map.keySet().retainAll(c);
+ }
+
+ public boolean removeAll(final Collection<?> c) {
+ return map.keySet().removeAll(c);
+ }
+
+ public void clear() {
+ map.clear();
+ }
+}
Modified: remoting3/trunk/mc-deployers/src/main/java/org/jboss/remoting/metadata/EndpointMetaData.java
===================================================================
--- remoting3/trunk/mc-deployers/src/main/java/org/jboss/remoting/metadata/EndpointMetaData.java 2008-11-19 15:28:09 UTC (rev 4703)
+++ remoting3/trunk/mc-deployers/src/main/java/org/jboss/remoting/metadata/EndpointMetaData.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -5,7 +5,7 @@
import org.jboss.beans.metadata.spi.BeanMetaData;
import org.jboss.beans.metadata.spi.BeanMetaDataFactory;
import org.jboss.beans.metadata.spi.builder.BeanMetaDataBuilder;
-import org.jboss.remoting.util.CollectionUtil;
+import org.jboss.remoting.core.util.CollectionUtil;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
Modified: remoting3/trunk/mc-deployers/src/main/java/org/jboss/remoting/metadata/RemotingMetaData.java
===================================================================
--- remoting3/trunk/mc-deployers/src/main/java/org/jboss/remoting/metadata/RemotingMetaData.java 2008-11-19 15:28:09 UTC (rev 4703)
+++ remoting3/trunk/mc-deployers/src/main/java/org/jboss/remoting/metadata/RemotingMetaData.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -6,7 +6,7 @@
import java.util.List;
import org.jboss.beans.metadata.spi.BeanMetaData;
import org.jboss.beans.metadata.spi.BeanMetaDataFactory;
-import org.jboss.remoting.util.CollectionUtil;
+import org.jboss.remoting.core.util.CollectionUtil;
import org.jboss.xb.annotations.JBossXmlSchema;
import javax.xml.bind.annotation.XmlElement;
Modified: remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/IntegerBiMap.java
===================================================================
--- remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/IntegerBiMap.java 2008-11-19 15:28:09 UTC (rev 4703)
+++ remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/IntegerBiMap.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -22,7 +22,7 @@
package org.jboss.remoting.protocol.multiplex;
-import org.jboss.remoting.util.SynchronizedSet;
+import org.jboss.remoting.core.util.SynchronizedSet;
import java.util.Set;
/**
Modified: remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/IntegerResourceBiMap.java
===================================================================
--- remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/IntegerResourceBiMap.java 2008-11-19 15:28:09 UTC (rev 4703)
+++ remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/IntegerResourceBiMap.java 2008-11-19 15:47:10 UTC (rev 4704)
@@ -24,8 +24,7 @@
import org.jboss.remoting.spi.AutoCloseable;
import org.jboss.remoting.spi.Handle;
-import org.jboss.remoting.util.SynchronizedSet;
-import org.jboss.remoting.util.SynchronizedCollection;
+import org.jboss.remoting.core.util.SynchronizedCollection;
import java.util.Iterator;
import java.util.Collection;
16 years, 3 months
JBoss Remoting SVN: r4703 - remoting3/trunk/transporter/src/main/java/org/jboss/remoting/transporter.
by jboss-remoting-commits@lists.jboss.org
Author: david.lloyd(a)jboss.com
Date: 2008-11-19 10:28:09 -0500 (Wed, 19 Nov 2008)
New Revision: 4703
Modified:
remoting3/trunk/transporter/src/main/java/org/jboss/remoting/transporter/TransporterInvocation.java
Log:
One more unsigned short fix
Modified: remoting3/trunk/transporter/src/main/java/org/jboss/remoting/transporter/TransporterInvocation.java
===================================================================
--- remoting3/trunk/transporter/src/main/java/org/jboss/remoting/transporter/TransporterInvocation.java 2008-11-19 14:41:04 UTC (rev 4702)
+++ remoting3/trunk/transporter/src/main/java/org/jboss/remoting/transporter/TransporterInvocation.java 2008-11-19 15:28:09 UTC (rev 4703)
@@ -70,11 +70,11 @@
name = (String) in.readObject();
final int cnt = in.readShort() & 0xffff;
final Class<?>[] parameterTypes = new Class<?>[cnt];
- for (short i = 0; i < cnt; i ++) {
+ for (int i = 0; i < cnt; i ++) {
parameterTypes[i] = (Class<?>) in.readObject();
}
final Object[] args = new Object[cnt];
- for (short i = 0; i < cnt; i ++) {
+ for (int i = 0; i < cnt; i ++) {
args[i] = in.readObject();
}
this.parameterTypes = parameterTypes;
16 years, 3 months
JBoss Remoting SVN: r4702 - remoting3/trunk/transporter/src/main/java/org/jboss/remoting/transporter.
by jboss-remoting-commits@lists.jboss.org
Author: david.lloyd(a)jboss.com
Date: 2008-11-19 09:41:04 -0500 (Wed, 19 Nov 2008)
New Revision: 4702
Modified:
remoting3/trunk/transporter/src/main/java/org/jboss/remoting/transporter/TransporterInvocation.java
Log:
Fix a bug where fields are not updated; also make sure the length value is read as unsigned short
Modified: remoting3/trunk/transporter/src/main/java/org/jboss/remoting/transporter/TransporterInvocation.java
===================================================================
--- remoting3/trunk/transporter/src/main/java/org/jboss/remoting/transporter/TransporterInvocation.java 2008-11-18 20:39:56 UTC (rev 4701)
+++ remoting3/trunk/transporter/src/main/java/org/jboss/remoting/transporter/TransporterInvocation.java 2008-11-19 14:41:04 UTC (rev 4702)
@@ -68,7 +68,7 @@
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
name = (String) in.readObject();
- final short cnt = in.readShort();
+ final int cnt = in.readShort() & 0xffff;
final Class<?>[] parameterTypes = new Class<?>[cnt];
for (short i = 0; i < cnt; i ++) {
parameterTypes[i] = (Class<?>) in.readObject();
@@ -77,6 +77,8 @@
for (short i = 0; i < cnt; i ++) {
args[i] = in.readObject();
}
+ this.parameterTypes = parameterTypes;
+ this.args = args;
}
public String getName() {
16 years, 3 months
JBoss Remoting SVN: r4701 - remoting2/branches/2.x/docs/guide/en.
by jboss-remoting-commits@lists.jboss.org
Author: ron.sigal(a)jboss.com
Date: 2008-11-18 15:39:56 -0500 (Tue, 18 Nov 2008)
New Revision: 4701
Modified:
remoting2/branches/2.x/docs/guide/en/chap10.xml
Log:
JBREM-1057: Replacing screwed up chapter.
Modified: remoting2/branches/2.x/docs/guide/en/chap10.xml
===================================================================
--- remoting2/branches/2.x/docs/guide/en/chap10.xml 2008-11-18 20:39:41 UTC (rev 4700)
+++ remoting2/branches/2.x/docs/guide/en/chap10.xml 2008-11-18 20:39:56 UTC (rev 4701)
@@ -1,2634 +1,19 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<chapter>
- <title>How to use it - sample code</title>
+ <chapter>
+ <title>Transporters - beaming POJOs</title>
- <para>Sample code demonstrating different remoting features can be found in
- the examples directory. They can be compiled and run manually via your IDE
- or via an ant build file found in the examples directory. There are many
- sets of sample code, each with their own package. Within most of these
- packages, there will be a server and a client class that will need to be
- executed</para>
+ <para>There are many ways in which to expose a remote interface to a java
+ object. Some require a complex framework API based on a standard
+ specification and some require new technologies like annotations and AOP.
+ Each of these have their own benefits. JBoss Remoting transporters provide
+ the same behavior via a simple API without the need for any of the newer
+ technologies.</para>
- <section>
- <title>Simple invocation</title>
-
- <para>The simple invocation sample (found in the
- org.jboss.remoting.samples.simple package), has two classes; SimpleClient
- and SimpleServer. It demonstrates making a simple invocation from a
- remoting client to a remoting server. The SimpleClient class will create
- an InvokerLocator object from a simple url-like string that identifies the
- remoting server to call upon (which will be socket://localhost:5400 by
- default). Then the SimpleClient will create a remoting Client class,
- passing the newly created InvokerLocator. Next the Client will be called
- to make an invocation on the remoting server, passing the request payload
- object (which is a String with the value of "Do something"). The server
- will return a response from this call which is printed to standard
- output.</para>
-
- <para>Within the SimpleServer, a remoting server is created and started.
- This is done by first creating an InvokerLocator, just like was done in
- the SimpleClient. Then constructing a Connector, passing the
- InvokerLocator. Next, need to call create() on the Connector to initialize
- all the resources, such as the remoting server invoker. Once created, need
- to create the invocation handler. The invocation handler is the class that
- the remoting server will pass client requests on to. The invocation
- handler in this sample simply returns the simple String "This is the
- return to SampleInvocationHandler invocation". Once created, the handler
- is added to the Connector. Finally, the Connector is started and will
- start listening for incoming client requests.</para>
-
- <para>To run this example, can compile both the SimpleClient and
- SimpleServer class, then first run the SimpleServer and then the
- SimpleClient. Or can go to the examples directory and run the ant target
- 'run-simple-server' and then in another console window run the ant target
- 'run-simple-client'. For example:</para>
-
- <para><programlisting>ant run-simple-server</programlisting>ant
- then:</para>
-
- <para><programlisting>ant run-simple-client</programlisting>The output
- when running the SimpleClient should look like:</para>
-
- <programlisting>Calling remoting server with locator uri of: socket://localhost:5400
-Invoking server with request of 'Do something'
-Invocation response: This is the return to SampleInvocationHandler invocation</programlisting>
-
- <para>The output when running the SimpleServer should look like:</para>
-
- <programlisting>Starting remoting server with locator uri of: socket://localhost:5400
-Invocation request is: Do something
-Returning response of: This is the return to SampleInvocationHandler invocation</programlisting>
-
- <para>Note: will have to manually shut down the SimpleServer once
- started.</para>
- </section>
-
- <section>
- <title>HTTP invocation</title>
-
- <para>This http invocation sample (found in the
- org.jboss.remoting.samples.http package), demonstrates how the http
- invoker can be used for a variety of http based invocations. This time,
- will start with the server side. The SimpleServer class is much like the
- one from the previous simple invocation example, except that instead of
- using the 'socket' transport, will be using the 'http' transport. Also,
- instead of using the SampleInvocationHandler class as the handler, will be
- using the WebInvocationHandler (code shown below).</para>
-
- <programlisting>public class <emphasis role="bold">WebInvocationHandler</emphasis> implements <emphasis
- role="bold">ServerInvocationHandler</emphasis>
-{
- // Pre-defined returns to be sent back to client based on type of request.
- public static final String RESPONSE_VALUE = "This is the return to simple text based http invocation.";
- public static final ComplexObject OBJECT_RESPONSE_VALUE = new ComplexObject(5, "dub", false);
- public static final String HTML_PAGE_RESPONSE = "<html><head><title>Test HTML page</title></head><body>" +
- "<h1>HTTP/Servlet Test HTML page</h1><p>This is a simple page served for test." +
- "<p>Should show up in browser or via invoker client</body></html>";
-
- // Different request types that client may make
- public static final String NULL_RETURN_PARAM = "return_null";
- public static final String OBJECT_RETURN_PARAM = "return_object";
- public static final String STRING_RETURN_PARAM = "return_string";
-
-
- /**
- * called to handle a specific invocation
- *
- * @param invocation
- * @return
- * @throws Throwable
- */
- <emphasis role="bold">public Object invoke(InvocationRequest invocation) throws Throwable
- {
- // Print out the invocation request
- System.out.println("Invocation request from client is: " + invocation.getParameter());
- if(NULL_RETURN_PARAM.equals(invocation.getParameter()))
- {
- return null;
- }
- else if(invocation.getParameter() instanceof ComplexObject)
- {
- return OBJECT_RESPONSE_VALUE;
- }
- else if(STRING_RETURN_PARAM.equals(invocation.getParameter()))
- {
- Map responseMetadata = invocation.getReturnPayload();
- responseMetadata.put(HTTPMetadataConstants.RESPONSE_CODE, new Integer(207));
- responseMetadata.put(HTTPMetadataConstants.RESPONSE_CODE_MESSAGE, "Custom response code and message from remoting server");
- // Just going to return static string as this is just simple example code.
- return RESPONSE_VALUE;
- }
- else
- {
- return HTML_PAGE_RESPONSE;
- }</emphasis>
- }
-</programlisting>
-
- <para>The most interesting part of the WebInvocationHandler is its
- invoke() method implementation. First it will check to see what the
- request parameter was from the InvocationRequest and based on what the
- value is, will return different responses. The first check is to see if
- the client passed a request to return a null value. The second will check
- to see if the request parameter from the client was of type ComplexObject.
- If so, return the pre-built ComplexObject that was created as a static
- variable.</para>
-
- <para>After that, will check to see if the request parameter was for
- returning a simple String. Notice in this block, will set the desired
- response code and message to be returned to the client. In this case, are
- setting the response code to be returned to 207 and the response message
- to "Custom response code and message from remoting server". These are
- non-standard code and message, but can be anything desired.</para>
-
- <para>Last, if have not found a matching invocation request parameter,
- will just return some simple html.</para>
-
- <para>Now onto the client side for making the calls to this handler, which
- can be found in SimpleClient (code shown below).</para>
-
- <programlisting>public class <emphasis role="bold">SimpleClient</emphasis>
-{
- // Default locator values
- private static String transport = "<emphasis role="bold">http</emphasis>";
- private static String host = "localhost";
- private static int port = 5400;
-
- public void makeInvocation(String locatorURI) throws Throwable
- {
- // create InvokerLocator with the url type string
- // indicating the target remoting server to call upon.
- InvokerLocator locator = new InvokerLocator(locatorURI);
- System.out.println("Calling remoting server with locator uri of: " + locatorURI);
-
- Client remotingClient = new Client(locator);
-
- // make invocation on remoting server and send complex data object
- // by default, the remoting http client invoker will use method type of POST,
- // which is needed when ever sending objects to the server. So no metadata map needs
- // to be passed to the invoke() method.
- <emphasis role="bold">Object response = remotingClient.invoke(new ComplexObject(2, "foo", true), null);</emphasis>
-
- System.out.println("\nResponse from remoting http server when making http POST request and sending a complex data object:\n" + response);
-
-
- <emphasis role="bold">Map metadata = new HashMap();</emphasis>
- // set the metadata so remoting client knows to use http GET method type
- <emphasis role="bold">metadata.put("TYPE", "GET");</emphasis>
- // not actually sending any data to the remoting server, just want to get its response
- <emphasis role="bold">response = remotingClient.invoke((Object) null, metadata);</emphasis>
-
- System.out.println("\nResponse from remoting http server when making GET request:\n" + response);
-
- // now set type back to POST and send a plain text based request
- <emphasis role="bold">metadata.put("TYPE", "POST");</emphasis>
- <emphasis role="bold">response = remotingClient.invoke(WebInvocationHandler.STRING_RETURN_PARAM, metadata);</emphasis>
-
- System.out.println("\nResponse from remoting http server when making http POST request and sending a text based request:\n" + response);
-
- // notice are getting custom response code and message set by web invocation handler
- <emphasis role="bold">Integer responseCode = (Integer) metadata.get(HTTPMetadataConstants.RESPONSE_CODE);
- String responseMessage = (String) metadata.get(HTTPMetadataConstants.RESPONSE_CODE_MESSAGE);</emphasis>
- System.out.println("Response code from server: " + responseCode);
- System.out.println("Response message from server: " + responseMessage);
-
- }
-</programlisting>
-
- <para>This SimpleClient, like the one before in the simple invocation
- example, starts off by creating an InvokerLocator and remoting Client
- instance, except is using http transport instead of socket. The first
- invocation made is to send a newly constructed ComplexObject. If remember
- from the WebInvocationHandler above, will expect this invocation to return
- a different ComplexObject, which can be seen in the following system
- output line.</para>
-
- <para>The next invocation to be made is a simple http GET request. To do
- this, must first let the remoting client know that the method type needs
- to be changed from the default, which is POST, to be GET. Then make the
- invocation with a null payload (since not wanting to send any data, just
- get data in response) and the metadata map just populated with the GET
- type. This invocation request will return a response of html.</para>
-
- <para>Then, will change back to being a POST type request and will pass a
- simple String as the payload to the invocation request. This will return a
- simple String as the response from the WebInvocationHandler. Afterward,
- will see the specific response code and message printed to standard
- output, as well as the exception itself.</para>
-
- <para>To run this example, can compile all the classes in the package,
- then first run the SimpleServer and then the SimpleClient. Or can go to
- the examples directory and run the ant target 'run-http-server' and then
- in another console window run the ant target 'run-http-client'. For
- example:</para>
-
- <programlisting>ant run-http-server</programlisting>
-
- <para>and then:</para>
-
- <programlisting>ant run-http-client</programlisting>
-
- <para>The output when running the SimpleClient should look like:</para>
-
- <programlisting>Response from remoting http server when making http POST request and sending a complex data object:
-ComplexObject (i = 5, s = dub, b = false, bytes.length = 0)
-
-Response from remoting http server when making GET request:
-<html><head><title>Test HTML page</title></head><body><h1>HTTP/Servlet Test HTML page</h1><p>This is a simple page served for test.<p>Should show up in browser or via invoker client</body></html>
-
-Response from remoting http server when making http POST request and sending a text based request:
-This is the return to simple text based http invocation.
-Response code from server: 207
-Response message from server: Custom response code and message from remoting server</programlisting>
-
- <para>Notice that the first response is the ComplexObject from the static
- variable returned within WebInvocationHandler. The next response is html
- and then simple text from the WebInvocationHandler. Can see the specific
- response code and message set in the WebInvocationHandler.</para>
-
- <para>The output from the SimpleServer should look like:</para>
-
- <programlisting>Starting remoting server with locator uri of: http://localhost:5400
-Jan 26, 2006 11:39:53 PM org.apache.coyote.http11.Http11BaseProtocol init
-INFO: Initializing Coyote HTTP/1.1 on http-127.0.0.1-5400
-Jan 26, 2006 11:39:53 PM org.apache.coyote.http11.Http11BaseProtocol start
-INFO: Starting Coyote HTTP/1.1 on http-127.0.0.1-5400
-Invocation request from client is: ComplexObject (i = 2, s = foo, b = true, bytes.length = 0)
-Invocation request from client is: null
-Invocation request from client is: return_string</programlisting>
-
- <para>First the information for the http server invoker is written, which
- includes the locator uri used to start the server and the output from
- starting the Tomcat connector. Then will see the invocation parameter
- passed for each client request.</para>
-
- <para>Since the SimpleServer should still be running, can open a web
- browser and enter the locator uri, http://localhost:5400. This should
- cause the browser to render the html returned from the
- WebInvocationHandler.</para>
- </section>
-
- <section>
- <title>Oneway invocation</title>
-
- <para>The oneway invocation sample (found in the
- org.jboss.remoting.samples.oneway package) is very similar to the simple
- invocation example, except in this sample, the client will make
- asynchronous invocations on the server.</para>
-
- <para>The OnewayClient class sets up the remoting client as in the simple
- invocation sample, but instead of using the invoke() method, it uses the
- invokeOneway() method on the Client class. There are two basic modes when
- making a oneway invocation in remoting. The first is to have the calling
- thread to be the one that makes the actual call to the server. This allows
- the caller to ensure that the invocation request at least made it to the
- server. Once the server receives the invocation request, the call will
- return (and the request will be processed by a separate worker thread on
- the server). The other mode, which is demonstrated in the second call to
- invokeOneway, allows for the calling thread to return immediately and a
- worker thread on the client side will make the actual invocation on the
- server. This is faster of the two modes, but if there is a problem making
- the request on the server, the original caller will be unaware.</para>
-
- <para>The OnewayServer is exactly the same as the SimpleServer from the
- previous example, with the exception that invocation handler returns null
- (since even if did return a response, would not be delivered to the
- original caller).</para>
-
- <para>To run this example, can compile both the OnewayClient and
- OnewayServer class, then run the OnewayServer and then the OnewayClient.
- Or can go to the examples directory and run the ant target
- 'run-oneway-server' and then in another console window run the ant target
- 'run-oneway-client'. For example:</para>
-
- <programlisting>ant run-oneway-server</programlisting>
-
- <para>and then:</para>
-
- <programlisting>ant run-oneway-client</programlisting>
-
- <para>The output when running the OnewayClient should look like:</para>
-
- <programlisting>Calling remoting server with locator uri of: socket://localhost:5400
-Making oneway invocation with payload of 'Oneway call 1.'
-Making oneway invocation with payload of 'Oneway call 2.'</programlisting>
-
- <para>The output when running the OnewayServer should look like:</para>
-
- <programlisting>Starting remoting server with locator uri of: socket://localhost:5400
-Invocation request is: Oneway call 1.
-Invocation request is: Oneway call 2.</programlisting>
-
- <para>Note: will have to manually shut down the OnewayServer once
- started.</para>
-
- <para>Although this example only demonstrates making one way invocations,
- could include this with callbacks (see further down) to have asynchronous
- invocations with callbacks to verify was processed.</para>
- </section>
-
- <section>
- <title>Discovery and invocation</title>
-
- <para>The discovery sample (found in the
- org.jboss.remoting.samples.detection package) is similar to the simple
- invocation example in that it makes a simple invocation from the client to
- the server. However, in this example, instead of explicitly specifying the
- invoker locator to use for the target remoting server, it is discovered
- dynamically during runtime. This example is composed of two classes;
- SimpleDetectorClient and SimpleDetectorServer.</para>
-
- <para>The SimpleDetectorClient starts off by setting up the remoting
- detector. Detection on the client side requires a few components; a JMX
- MBeanServer, one or more Detectors, and a NetworkRegistry. The Detectors
- will listen for detection messages from remoting servers and then add the
- information for the detected servers to the NetworkRegistry. They use JMX
- to lookup and call on the NetworkRegistry. The NetworkRegistry uses JMX
- Notifications to emit changes in network topology (remoting servers being
- added or removed).</para>
-
- <para>In this particular example, the SimpleDetectorClient is registered
- with the NetworkRegistry as a notification listener. When it receives
- notifications from the NetworkRegistry (via the handleNotification()
- method), it will check to see if the notification is for adding or
- removing a remoting server. If it is for adding a remoting server, the
- SimpleDetectorClient will get the array of InvokerLocators from the
- NetworkNotification and make a remote call for each. If the notification
- is for removing a remoting server, the SimpleDetectorClient will simply
- print out a message saying which server has been removed.</para>
-
- <para>The biggest change between the SimpleDetectorServer and the
- SimpleServer from the first sample is that have added a method,
- setupDetector(), to create and start a remoting Detector. On the server
- side, only two components are needed for detection; the Detector and a JMX
- MBeanServer. As for the setup of the Connector, it is exactly the same as
- before. Notice that even though we have added a Detector on the server
- side, the Connector is not directly aware of either Detector or the
- MBeanServer, so no code changes for the Connector setup is
- required.</para>
-
- <para>To run this example, can compile both the SimpleDetectorClient and
- SimpleDetectorServer class, then run the SimpleDetectorServer and then the
- SimpleDetectorClient. Or can go to the examples directory and run the ant
- target 'run-detector-server' and then in another window run the ant target
- 'run-detector-client'. For example:</para>
-
- <programlisting>ant run-detector-server</programlisting>
-
- <para>and then:</para>
-
- <programlisting>ant run-detector-client</programlisting>
-
- <para>The initial output when running the SimpleDetectorClient should look
- like:</para>
-
- <programlisting>ri Jan 13 09:36:50 EST 2006: [CLIENT]: Starting JBoss/Remoting client... to stop this client, kill it manually via Control-C
-Fri Jan 13 09:36:50 EST 2006: [CLIENT]: NetworkRegistry has been created
-Fri Jan 13 09:36:50 EST 2006: [CLIENT]: NetworkRegistry has added the client as a listener
-Fri Jan 13 09:36:50 EST 2006: [CLIENT]: MulticastDetector has been created and is listening for new NetworkRegistries to come online
-Fri Jan 13 09:36:50 EST 2006: [CLIENT]: GOT A NETWORK-REGISTRY NOTIFICATION: jboss.network.server.added
-Fri Jan 13 09:36:50 EST 2006: [CLIENT]: New server(s) have been detected - getting locators and sending welcome messages
-Fri Jan 13 09:36:50 EST 2006: [CLIENT]: Sending welcome message to remoting server with locator uri of: socket://127.0.0.1:5400/
-Fri Jan 13 09:36:50 EST 2006: [CLIENT]: The newly discovered server sent this response to our welcome message: Received your welcome message. Thank you!</programlisting>
-
- <para>The output when running the SimpleDetectorServer should look
- like:</para>
-
- <programlisting>Fri Jan 13 09:36:46 EST 2006: [SERVER]: Starting JBoss/Remoting server... to stop this server, kill it manually via Control-C
-Fri Jan 13 09:36:46 EST 2006: [SERVER]: This server's endpoint will be: socket://localhost:5400
-Fri Jan 13 09:36:46 EST 2006: [SERVER]: MulticastDetector has been created and is listening for new NetworkRegistries to come online
-Fri Jan 13 09:36:46 EST 2006: [SERVER]: Starting remoting server with locator uri of: socket://localhost:5400
-Fri Jan 13 09:36:46 EST 2006: [SERVER]: Added our invocation handler; we are now ready to begin accepting messages from clients
-Fri Jan 13 09:36:50 EST 2006: [SERVER]: RECEIVED A CLIENT MESSAGE: Welcome Aboard!
-Fri Jan 13 09:36:50 EST 2006: [SERVER]: Returning the following message back to the client: Received your welcome message. Thank you!</programlisting>
-
- <para>At this point, try stopping the SimpleDetectorServer (notice that
- the SimpleDetectorClient should still be running). After a few seconds,
- the client detector should detect that the server is no longer available
- and will see something like the following appended in the
- SimpleDetectorClient console window:</para>
-
- <programlisting>Fri Jan 13 09:37:04 EST 2006: [CLIENT]: GOT A NETWORK-REGISTRY NOTIFICATION: jboss.network.server.removed
-Fri Jan 13 09:37:04 EST 2006: [CLIENT]: It has been detected that a server has gone down with a locator of: InvokerLocator [socket://127.0.0.1:5400/]</programlisting>
- </section>
-
- <section>
- <title>Callbacks</title>
-
- <para>The callback sample (found in the
- org.jboss.remoting.samples.callback package) illustrates how to perform
- callbacks from a remoting server to a remoting client. This example is
- composed of two classes; CallbackClient and CallbackServer.</para>
-
- <para>Within remoting, there are two approaches in which a callback can be
- received. The first is to actively ask for callback messages from the
- remoting server, which is called a pull callback (since are pulling the
- callbacks from the server). The second is to have the server send the
- callbacks to the client as they are generated, which is called a push
- callback. This sample demonstrates how to do both pull and push
- callbacks.</para>
-
- <para>Looking at the CallbackClient class, will see that the first thing
- done is to create a remoting Client, which is done in the same manner as
- previous examples. Next, we'll perform a pull callback, which requires the
- creation of a CallbackHandler. The CallbackHandler, which implements the
- InvokerCallbackHandler interface, is what is called upon with a Callback
- object when a callback is received. The Callback object contains
- information such as the callback message (in Object form), the server
- locator from where the callback originally came from, and a handle object
- which can help to identify callback context (similar to the handle object
- within a JMX Notification). Once created, the CallbackHandler is then
- registered as a listener within the Client. This will cause the client to
- make a call to the server to notify the server it has a callback listener
- (more on this below in the server section). Although the CallbackHandler
- is not called upon directly when doing pull callbacks, it is needed as an
- identifier for the callbacks.</para>
-
- <para>Then the client will wait a few seconds, make a simple invocation on
- the server, and then call on the remoting Client instance to get any
- callbacks that may be available for our CallbackHandler. This will return
- a list of callbacks, if any exist. The list will be iterated and each
- callback will be printed to standard output. Finally, the callback handler
- will be removed as a listener from the remoting Client (which in turns
- removes it from the remoting server).</para>
-
- <para>After performing a pull callback, will perform a push callback. This
- is a little more involved as requires creating a callback server to which
- the remoting target server can callback on when it generates a callback
- message. To do this, will need to create a remoting Connector, just as
- have seen in previous examples. For this particular example, we use the
- same locator url as our target remoting server, but increment the port to
- listen on by one. Will also notice that use the SampleInvocationHandler
- hander from the CallbackServer (more in this in a minute). After creating
- our callback server, a CallbackHandler and callback handle object is
- created. Next, remoting Client is called to add our callback listener.
- Here we pass not only the CallbackHandler, but the InvokerLocator for the
- callback server (so the target server will know where to deliver callback
- messages to), and the callback handle object (which will be included in
- all the callback messages delivered for this particular callback
- listener).</para>
-
- <para>Then the client will wait a few seconds, to allow the target server
- time to generate and deliver callback messages. After that, we remove the
- callback listener and clean up our callback server.</para>
-
- <para>The CallbackServer is pretty much the same as the previous samples
- in setting up the remoting server, via the Connector. The biggest change
- resides in the ServerInvocationHandler implementation,
- SampleInvocationHandler (which is an inner class to CallbackServer). The
- first thing to notice is now have a variable called listeners, which is a
- List to hold any callback listeners that get registered. Also, in the
- constructor of the SampleInvocationHandler, we set up a new thread to run
- in the background. This thread, executing the run() method in
- SampleInvocationHandler, will continually loop looking to see if the
- shouldGenerateCallbacks has been set. If it has been, will create a
- Callback object and loop through its list of listeners and tell each
- listener to handle the newly created callback. Have also added
- implementation to the addListener() and removeListener() methods where
- will either add or remove specified callback listener from the internal
- callback listener list and set the shouldGenerateCallbacks flag
- accordingly. The invoke() method remains the same as in previous
- samples.</para>
-
- <para>To run this example, can compile both the CallbackClient and
- CallbackServer class, then run the CallbackServer and then the
- CallbackClient. Or can go to the examples directory and run the ant target
- 'run-callback-server' and then in another window run the ant target
- 'run-callback-client. For example:</para>
-
- <programlisting>ant run-callback-server</programlisting>
-
- <para>and then:</para>
-
- <programlisting>ant run-callback-client</programlisting>
-
- <para>The output in the CallbackClient console window should look
- like:</para>
-
- <programlisting>Calling remoting server with locator uri of: socket://localhost:5400
-Invocation response: This is the return to SampleInvocationHandler invocation
-Pull Callback value = Callback 1: This is the payload of callback invocation.
-Pull Callback value = Callback 2: This is the payload of callback invocation.
-Starting remoting server with locator uri of: InvokerLocator [socket://127.0.0.1:5401/]
-Received push callback.
-Received callback value of: Callback 3: This is the payload of callback invocation.
-Received callback handle object of: myCallbackHandleObject
-Received callback server invoker of: InvokerLocator [socket://127.0.0.1:5400/]
-Received push callback.
-Received callback value of: Callback 4: This is the payload of callback invocation.
-Received callback handle object of: myCallbackHandleObject
-Received callback server invoker of: InvokerLocator [socket://127.0.0.1:5400/]</programlisting>
-
- <para>This output shows that client first pulled two callbacks generated
- from the server. Then, after creating and registering our second callback
- handler and a callback server, two callbacks were received from the target
- server.</para>
-
- <para>The output in the CallbackServer console window should look
- like:</para>
-
- <programlisting>Starting remoting server with locator uri of: socket://localhost:5400
-Adding callback listener.
-Invocation request is: Do something
-Removing callback listener.
-Adding callback listener.
-Removing callback listener. </programlisting>
-
- <para>This output shows two distinct callback handlers being added and
- removed (with an invocation request being received after the first was
- added).</para>
-
- <para>There are a few important points to mention about this example.
- First, notice that in the client, the same callback handle object in the
- push callbacks was received as was registered with the callback listener.
- However, there was no special code required to facilitate this within the
- SampleInvocationHandler. This is handled within remoting automatically.
- Also notice when the callback server was created within the client, no
- special coding was required to register the callback handler with it, both
- were simply passed to the remoting Client instance when registering the
- callback listener and was handled internally.</para>
- </section>
-
- <section>
- <title>Streaming</title>
-
- <para>The streaning sample (found in the org.jboss.remoting.samples.stream
- package) illustrates how a java.io.InputStream can be sent from a client
- and read on demand from a server. This example is composed of two classes:
- StreamingClient and StreamingServer.</para>
-
- <para>Unlike the previous examples that sent plain old java objects as the
- payload, this example will be sending a java.io.FileInputStream as the
- payload to the server. This is a special case because streams can not be
- serialized. One approach to this might be to write out the contents of a
- stream to a byte buffer and send the whole data content to the server.
- However, this approach can be dangerous because if the data content of the
- stream is large, such as an 800MB file, would run the risk of causing an
- out of memory error (since are loading all 800MB into memory). Another
- approach, which is used by JBossRemoting, is to create a proxy to the
- original stream. This proxy can then be called upon for reading, same as
- the original stream. When this happens, the proxy will call back the
- original stream for the requested data.</para>
-
- <para>Looking at the StreamingClient, the remoting Client is created as in
- previous samples. Next, will create a java.io.FileInputStream to the
- sample.txt file on disk (which is in the same directory as the test
- classes). Finally, will call the remoting Client to do its invocation,
- passing the new FileInputStream and the name of the file. The second
- parameter could be of any Object type and is meant to supply some
- meaningful context to the server in regards to the stream being passed,
- such as the file name to use when writing to disk on the server side. The
- response from the server, in this example, is the size of the file it
- wrote to disk.</para>
-
- <para>The StreamingServer sets up the remoting server as was done in
- previous examples. However, instead of using an implementation of the
- ServerInvocationHandler class as the server handler, an implementation of
- the StreamInvocationHandler (which extends the ServerInvocationHandler) is
- used. The StreamInvocationHandler includes an extra method called
- handleStream() especially for processing requests with a stream as the
- payload. In this example, the class implementing the
- StreamInvocationHandler is the TestStreamInvocationHandler class, which is
- an inner class to the StreamingServer. The handleStream() method within
- the TestStreamInvocationHandler will use the stream passed to it to write
- out its contents to a file on disk, as specified by the second parameter
- passed to the handleStream() method. Upon writing out the file to disk,
- the handleStream() method will return to the client caller the size of the
- file.</para>
-
- <para>To run this example, can compile both the StreamingClient and
- StreamingServer class, then run the StreamingServer and then the
- StreamingClient. Or can go to the examples directory and run the ant
- target 'run-stream-server' and then in another window run the ant target
- 'run-stream-client'. For example:</para>
-
- <programlisting>ant run-stream-server</programlisting>
-
- <para>and then:</para>
-
- <programlisting>ant run-stream-client</programlisting>
-
- <para>The output in the StreamingClient console window should look
- like:</para>
-
- <programlisting>Calling on remoting server with locator uri of: socket://localhost:5400
-Sending input stream for file sample.txt to server.
-Size of file sample.txt is 987
-Server returned 987 as the size of the file read.</programlisting>
-
- <para>The output in the StreamingServer console window should look
- like:</para>
-
- <programlisting>Starting remoting server with locator uri of: socket://localhost:5400
-Received input stream from client to write out to file server_sample.txt
-Read stream of size 987. Now writing to server_sample.txt
-New file server_sample.txt has been written out to C:\tmp\JBossRemoting_1_4_0_final\examples\server_sample.txt</programlisting>
-
- <para>After running this example, there should be a newly created
- server_sample.txt file in the root examples directory. The contents of the
- file should look exactly like the contents of the sample.txt file located
- in the examples\org\jboss\remoting\samples\stream directory.</para>
- </section>
-
- <section>
- <title>JBoss Serialization</title>
-
- <para>The serialization sample (found in the
- org.jboss.remoting.samples.serialization package) illustrates how JBoss
- Serialization can be used in place of the standard java serialization to
- allow for sending of invocation payload objects that do not implement the
- java.io.Serializable interface. This example is composed of three classes:
- SerializationClient, SerializationServer, and
- NonSerializablePayload.</para>
-
- <para>This example is exactly like the one from the simple example with
- two differences. The first difference is the use of JBoss Serialization to
- convert object instances to binary data format for wire transfer. This is
- accomplished by adding an extra parameter (serializationtype) to the
- locator url with a value of 'jboss'. Is important to note that use of
- JBoss Serialization requires JDK 1.5, so this example will need to be run
- using JDK 1.5. The second difference is instead of sending and receiving a
- simple String type for the remote invocation payload, will be sending and
- receiving an instance of the NonSerializablePayload class.</para>
-
- <para>There are a few important points to notice with the
- NonSerializablePayload class. The first is that it does NOT implement the
- java.io.Serializable interface. The second is that it has a void parameter
- constructor. This is a requirement of JBoss Serialization for object
- instances that do not implement the Serializable interface. However, this
- void parameter constructor can be private, as in the case of
- NonSerializablePayload, as to not change the external API of the
- class.</para>
-
- <para>To run this example, can compile both the SerializationClient and
- SerializationServer class, then run the SerializationServer and then the
- SerializationClient. Or can go to the examples directory and run the ant
- target 'run-serialization-server' and then in another window run the ant
- target 'run-serialization-client'. For example:</para>
-
- <programlisting>ant run-serialization-server</programlisting>
-
- <para>and then:</para>
-
- <programlisting>ant run-serialization-client</programlisting>
-
- <para>The output in the SerializationClient console window should look
- like:</para>
-
- <programlisting>Calling remoting server with locator uri of: socket://localhost:5400/?serializationtype=jboss
-Invoking server with request of 'NonSerializablePayload - name: foo, id: 1'
-Invocation response: NonSerializablePayload - name: bar, id: 2</programlisting>
-
- <para>The output in the SerializationServer console window should look
- like:</para>
-
- <programlisting>Starting remoting server with locator uri of: socket://localhost:5400/?serializationtype=jboss
-Invocation request is: NonSerializablePayload - name: foo, id: 1
-Returning response of: NonSerializablePayload - name: bar, id: 2</programlisting>
-
- <para>Note: will have to manually shut down the SerializationServer once
- started.</para>
- </section>
-
- <section>
- <title>Transporters</title>
-
- <section>
- <title>Transporters - beaming POJOs</title>
-
- <para>There are many ways in which to expose a remote interface to a
- java object. Some require a complex framework API based on a standard
- specification and some require new technologies like annotations and
- AOP. Each of these have their own benefits. JBoss Remoting transporters
- provide the same behavior via a simple API without the need for any of
- the newer technologies.</para>
-
- <para>When boiled down, transporters take a plain old java object (POJO)
- and expose a remote proxy to it via JBoss Remoting. Dynamic proxies and
- reflection are used to make the typed method calls on that target POJO.
- Since JBoss Remoting is used, can select from a number of different
- network transports (i.e. rmi, http, socket, multiplex, etc.), including
- support for SSL. Even clustering features can be included.</para>
-
- <bridgehead>How it works</bridgehead>
-
- <para>In this section will discuss how remoting transporters can be
- used, some requirments for usage, and a little detail on the
- implementation. For greater breath on usage, please review the
- transporter samples as most use cases are covered there.</para>
-
- <para>To start, will need to have a plain old java object that
- implements one or more interfaces that want to expose for remote method
- invocation. Then will need to create a
- <code>org.jboss.remoting.transporter.TransporterServer</code> to wrap
- around it, so that can be exposed remotely. This can be done in one of
- two basic ways. The first is to use a static
- <code>createTransporterServer()</code> method of the TransporterServer
- class. There are many of these create methods, but all basically do that
- same thing in that they take a remoting locator and target pojo and will
- return a TransporterServer instance that has been started and ready to
- receive remote invocations (see javadoc for TransporterServer for all
- the different static createTransporterServer() methods). The other way
- to create a TransporterServer for the target pojo is to construct an
- instance of it. This provides a little more flexibility as are able to
- control more aspects of the TransporterServer, such as when it will be
- started.</para>
-
- <para>When a TransporterServer is created, it will create a remoting
- Connector using the locator provided. It will generate a server
- invocation handler that wraps the target pojo provided and use
- reflection to make the calls on it based on the invocations it receives
- from clients. By default, the subsystem underwhich the server invocation
- handler is registered is the interface class name for which the target
- pojo is exposing. If the target implements multiple interfaces, and a
- specific one to use is not specified, all the interfaces will be
- registered as subsystems for the same server invocation handler.
- Whenever no long want the target pojo to receive remote method
- invocations, will need to call the <code>stop()</code> method on the
- TransporterServer for the target pojo (this is very important, as
- otherwise will never be released from memory and will continue to
- consume network and memory resources).</para>
-
- <para>On the client side, in order to be able to call on the target pojo
- remotely, will need to use the
- <code>org.jboss.remoting.transporter.TransporterClient</code>. Unlike
- the TransporterServer, can only use the static create methods of the
- TransporterClient (this is because the return to the static create
- method is a typed dynamic proxy). The static method to call on the
- TransportClient is <code>createTransporterClient()</code>, where will
- pass the locator to find the target pojo (same as one used when creating
- the TransporterServer) and the interface for the target pojo that want
- to make remote method invocations on. The return from this create call
- will be a dynamic proxy which you can cast to to same interface type
- supplied. At that point, can make typed method invocations on the
- returned object, which will then make the remote invocations under the
- covers. Note that can have multiple transporter clients to the same
- target pojo, each using different interface types for making
- calls.</para>
-
- <para>When no longer need to make invocations on the target pojo, the
- resources associated with the remoting client will need to be cleaned
- up. This is done by calling the <code>destroyTransporterClient()</code>
- method of the TransporterClient. This is important to remember to do, as
- will otherwise leave network resources active even though not in
- use.</para>
-
- <para>One of the features of using remoting transporters is location
- transparency. By this mean that client proxies returned by the
- TransporterClient can be passed over the network. For example, can have
- a target pojo that returns from a method call a client proxy (that it
- created using the TransporterClient) in which the client can call on
- directly as well. See the transporter proxy sample code to see how this
- can be done.</para>
-
- <para>Another nice feature when using transporters is the ability to
- cluster. To be more specific, can create multiple target pojos using the
- TransporterServer in clustered mode and then use the TransporterClient
- in clustered mode to create a client proxy that will discover the
- location of the target pojos are wanting to call on. Will also provide
- automatic, seemless failover of remote method invocations in the case
- that a particular target pojo instance fails. However, note that only
- provide invocation failover and does not take into account state
- transfer between target pojos (would need addition of JBoss Cache or
- some other state synchronization tool).</para>
- </section>
-
- <para>The transporter sample spans several examples showing different ways
- to use the transporter. Each specific example is within its own package
- under the org.jboss.remoting.samples.transporter package. Since each of
- the transporter examples includes common objects, as well as client and
- server classes, the common objects will be found under the main
- transporter sub-package and the client and server classes in their
- respective sub-packages (named client and server).</para>
-
- <section>
- <title>Transporters sample - simple</title>
-
- <para>The simple transporter example (found in
- org.jboss.remoting.samples.transporter.simple package) demonstrates a
- very simple example of how to use the transporters to expose a plain old
- java object for remote method invocations.</para>
-
- <para>In this simple transporter example, will be taking a class that
- formats a java.util.Date into a simple String representation and
- exposing it so can call on the remotely. The target object in this case,
- org.jboss.remoting.samples.transporter.simple.DateProcessorImpl,
- implements the
- org.jboss.remoting.samples.transporter.simple.DateProcessor interfaces
- (as shown below):</para>
-
- <programlisting>public interface DateProcessor
-{
- public String formatDate(Date dateToConvert);
-}
-
-
-public class DateProcessorImpl implements DateProcessor
-{
- public String formatDate(Date dateToConvert)
- {
- DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
- return dateFormat.format(dateToConvert);
- }
-}</programlisting>
-
- <para>This is then exposed using the TransporterServer by the
- org.jboss.remoting.samples.transporter.simple.Server class.</para>
-
- <programlisting>public class Server
-{
- public static void main(String[] args) throws Exception
- {
- TransporterServer server = TransporterServer.createTransporterServer("socket://localhost:5400", new DateProcessorImpl(), DateProcessor.class.getName());
- Thread.sleep(10000);
- server.stop();
- }
-}</programlisting>
-
- <para>The Server class simply creates a TransporterServer by indicating
- the locator url would like to use for the remoting server, a newly
- created instance of DataProcessorImpl, and the interface type would like
- to expose remotely. The TransporterServer returned from the
- createTransporterServer call is live and ready to receive incoming
- method invocation requests. Will then wait 10 seconds for a request,
- then stop the server.</para>
-
- <para>Next need to have client to make the remote invocation. This can
- be found within
- org.jboss.remoting.samples.transporter.simple.Client.</para>
-
- <programlisting>public class Client
-{
- public static void main(String[] args) throws Exception
- {
- DateProcessor dateProcessor = (DateProcessor) TransporterClient.createTransporterClient("socket://localhost:5400", DateProcessor.class);
- String formattedDate = dateProcessor.formatDate(new Date());
- System.out.println("Current date: " + formattedDate);
- }
-}</programlisting>
-
- <para>In the Client class, create a TransporterClient which can be cast
- to the desired type, which is DataProcessor in this case. In calling the
- createTransporterClient, need to specify the locator ulr (same as was
- used for the TransporterServer), and the interface type will be calling
- on for the target pojo. Once have the DateProcessor variable, will make
- the call to formatDate() and pass a newly created Date object. The
- return will be a formated String of the date passed.</para>
-
- <para>To run this example, can run the Server and then the Client. Or
- can go to the examples directory and run the ant target
- 'run-transporter-simple-server' and then in another window run the ant
- target 'run-transporter-simple-client'. For example:</para>
-
- <programlisting>ant run-transporter-simple-server</programlisting>
-
- <para>and then:</para>
-
- <programlisting>ant run-transporter-simple-client</programlisting>
-
- <para>The output from the client window should look similar to:</para>
-
- <programlisting>Current date: Jul 31, 2006</programlisting>
- </section>
-
- <section>
- <title>Transporter sample - basic</title>
-
- <para>The basic transporter example (found in
- org.jboss.remoting.samples.transporter.basic package) illustrates how to
- build a simple transporter for making remote invocations on plain old
- java objects.</para>
-
- <para>In this basic transporter example, will be using a few domain
- objects; <code>Customer</code> and Address, which are just data
- objects.</para>
-
- <programlisting>public class <emphasis role="bold">Customer</emphasis> implements Serializable
-{
- private String firstName = null;
- private String lastName = null;
- private Address addr = null;
- private int customerId = -1;
-
- public String getFirstName()
- {
- return firstName;
- }
-
- public void setFirstName(String firstName)
- {
- this.firstName = firstName;
- }
-
- public String getLastName()
- {
- return lastName;
- }
-
- public void setLastName(String lastName)
- {
- this.lastName = lastName;
- }
-
- public Address getAddr()
- {
- return addr;
- }
-
- public void setAddr(Address addr)
- {
- this.addr = addr;
- }
-
- public int getCustomerId()
- {
- return customerId;
- }
-
- public void setCustomerId(int customerId)
- {
- this.customerId = customerId;
- }
-
- public String toString()
- {
- StringBuffer buffer = new StringBuffer();
- buffer.append("\nCustomer:\n");
- buffer.append("customer id: " + customerId + "\n");
- buffer.append("first name: " + firstName + "\n");
- buffer.append("last name: " + lastName + "\n");
- buffer.append("street: " + addr.getStreet() + "\n");
- buffer.append("city: " + addr.getCity() + "\n");
- buffer.append("state: " + addr.getState() + "\n");
- buffer.append("zip: " + addr.getZip() + "\n");
-
- return buffer.toString();
- }
-}</programlisting>
-
- <programlisting>public class <emphasis role="bold">Address</emphasis> implements Serializable
-{
- private String street = null;
- private String city = null;
- private String state = null;
- private int zip = -1;
-
- public String getStreet()
- {
- return street;
- }
-
- public void setStreet(String street)
- {
- this.street = street;
- }
-
- public String getCity()
- {
- return city;
- }
-
- public void setCity(String city)
- {
- this.city = city;
- }
-
- public String getState()
- {
- return state;
- }
-
- public void setState(String state)
- {
- this.state = state;
- }
-
- public int getZip()
- {
- return zip;
- }
-
- public void setZip(int zip)
- {
- this.zip = zip;
- }
-}</programlisting>
-
- <para>Next comes the POJO that we want to expose a remote proxy for,
- which is <code>CustomerProcessorImpl</code> class. This implementation
- has one method to process a <code>Customer</code> object. It also
- implements the <code>CustomerProcessor</code> interface.</para>
-
- <programlisting>public class <emphasis role="bold">CustomerProcessorImpl</emphasis> implements <emphasis
- role="bold">CustomerProcessor</emphasis>
-{
- /**
- * Takes the customer passed, and if not null and customer id
- * is less than 0, will create a new random id and set it.
- * The customer object returned will be the modified customer
- * object passed.
- *
- * @param customer
- * @return
- */
- public Customer processCustomer(Customer customer)
- {
- if(customer != null && customer.getCustomerId() < 0)
- {
- customer.setCustomerId(new Random().nextInt(1000));
- }
- System.out.println("processed customer with new id of " + customer.getCustomerId());
- return customer;
- }
-}</programlisting>
-
- <programlisting>public interface <emphasis role="bold">CustomerProcessor</emphasis>
-{
- /**
- * Process a customer object. Implementors
- * should ensure that the customer object
- * passed as parameter should have its internal
- * state changed somehow and returned.
- *
- * @param customer
- * @return
- */
- public Customer processCustomer(Customer customer);
-}</programlisting>
-
- <para>So far, nothing special, just plain old java objects. Next need to
- create the server component that will listen for remote request to
- invoke on the target POJO. This is where the transporter comes
- in.</para>
-
- <programlisting>public class <emphasis role="bold">Server</emphasis>
-{
- private String locatorURI = "socket://localhost:5400";
- private TransporterServer server = null;
-
- public void start() throws Exception
- {
- server = <emphasis role="bold">TransporterServer.createTransporterServer(locatorURI, new CustomerProcessorImpl())</emphasis>;
- }
-
- public void stop()
- {
- if(server != null)
- {
- server.stop();
- }
- }
-
- public static void main(String[] args)
- {
- Server server = new Server();
- try
- {
- server.start();
-
- Thread.currentThread().sleep(60000);
-
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- server.stop();
- }
- }
-}</programlisting>
-
- <para>The <code>Server</code> class is a pretty simple one. It calls the
- <code>TransporterServer</code> factory method to create the server
- component for the <code>CustomerProcessorImpl</code> instance using the
- specified remoting locator information.</para>
-
- <para>The <code>TransporterServer</code> returned from the
- <code>createTransporterServer() </code>call will be a running instance
- of a remoting server using the <literal>socket</literal> transport that
- is bound to <literal>localhost</literal> and listening for remote
- requests on port <literal>5400</literal>. The requests that come in will
- be forwarded to the remoting handler which will convert them into direct
- method calls on the target POJO, <code>CustomerProcessorImpl</code> in
- this case, using reflection.</para>
-
- <para>The <code>TransporterServer</code> has a <code>start()</code> and
- <code>stop()</code> method exposed to control when to start and stop the
- running of the remoting server. The <code>start()</code> method is
- called automatically within the <code>createTransporterServer()</code>
- method, so is ready to receive requests upon the return of this method.
- The <code>stop()</code> method, however, needs to be called explicitly
- when no longer wish to receive remote calls on the target POJO.</para>
-
- <para>Next up is the client side. This is represented by the
- <code>Client</code> class.</para>
-
- <programlisting>public class <emphasis role="bold">Client</emphasis>
-{
- private String locatorURI = "socket://localhost:5400";
-
- public void makeClientCall() throws Exception
- {
- Customer customer = createCustomer();
-
- <emphasis role="bold">CustomerProcessor customerProcessor = (CustomerProcessor) TransporterClient.createTransporterClient(locatorURI, CustomerProcessor.class);</emphasis>
-
- System.out.println("Customer to be processed: " + customer);
- <emphasis role="bold">Customer processedCustomer = customerProcessor.processCustomer(customer);</emphasis>
- System.out.println("Customer is now: " + processedCustomer);
-
- <emphasis role="bold">TransporterClient.destroyTransporterClient(customerProcessor);</emphasis>
- }
-
- private Customer createCustomer()
- {
- Customer cust = new Customer();
- cust.setFirstName("Bob");
- cust.setLastName("Smith");
- Address addr = new Address();
- addr.setStreet("101 Oak Street");
- addr.setCity("Atlanata");
- addr.setState("GA");
- addr.setZip(30249);
- cust.setAddr(addr);
-
- return cust;
- }
-
- public static void main(String[] args)
- {
- Client client = new Client();
- try
- {
- client.makeClientCall();
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
-}</programlisting>
-
- <para>The <code>Client</code> class is also pretty simple. It creates a
- new <code>Customer</code> object instance, creates the remote proxy to
- the <code>CustomerProcessor</code>, and then calls on the
- <code>CustomerProcessor</code> to process its new <code>Customer</code>
- instance.</para>
-
- <para>To get the remote proxy for the <code>CustomerProcessor</code>,
- all that is required is to call the <code>TransporterClient</code>'s
- method <code>createTransporterClient()</code> method and pass the
- locator uri and the type of the remote proxy (and explicitly cast the
- return to that type). This will create a dynamic proxy for the specified
- type, <code>CustomerProcessor</code> in this case, which is backed by a
- remoting client which in turn makes the calls to the remote POJO's
- remoting server. Once the call to <code>createTransportClient()</code>
- has returned, the remoting client has already made its connection to the
- remoting server and is ready to make calls (will throw an exception if
- it could not connect to the specified remoting server).</para>
-
- <para>When finished making calls on the remote POJO proxy, will need to
- explicitly destroy the client by calling
- <code>destroyTransporterClient()</code> and pass the remote proxy
- instance. This allows the remoting client to disconnect from the POJO's
- remoting server and clean up any network resources previously
- used.</para>
-
- <para>To run this example, can run the Server and then the Client. Or
- can go to the examples directory and run the ant target
- 'run-transporter-basic-server' and then in another window run the ant
- target 'run-transporter-basic-client'. For example:</para>
-
- <programlisting>ant run-transporter-basic-server</programlisting>
-
- <para>and then:</para>
-
- <programlisting>ant run-transporter-basic-client</programlisting>
-
- <para>The output from the Client console should be similar to:</para>
-
- <programlisting>Customer to be processed:
-Customer:
-customer id: -1
-first name: Bob
-last name: Smith
-street: 101 Oak Street
-city: Atlanata
-state: GA
-zip: 30249
-
-Customer is now:
-Customer:
-customer id: 204
-first name: Bob
-last name: Smith
-street: 101 Oak Street
-city: Atlanata
-state: GA
-zip: 30249
-
-</programlisting>
-
- <para>and the output from the Server class should be similar to:</para>
-
- <programlisting>processed customer with new id of 204</programlisting>
-
- <para>The output shows that the <code>Customer</code> instance created
- on the client was sent to the server where it was processed (by setting
- the customer id to 204) and returned to the client (and printed out
- showing that the customer id was set to 204).</para>
- </section>
-
- <section>
- <title>Transporter sample - JBoss serialization</title>
-
- <para>The transporter serialization example (found in
- org.jboss.remoting.samples.transporter.serialization package) is very
- similar to the previous basic example, except in this one, the domain
- objects being sent over the wire will NOT be Serializable. This is
- accomplished via the use of JBoss Serialization. This can be useful when
- don't know which domain objects you may be using in remote calls or if
- adding ability for remote calls on legacy code.</para>
-
- <para>To start, there are a few more domain objects: <code>Order</code>,
- <code>OrderProcessor</code>, and <code>OrderProcessorImpl</code>. These
- will use some of the domain objects from the previous example as well,
- such as <code>Customer</code>.</para>
-
- <programlisting>public class <emphasis role="bold">Order</emphasis>
-{
- private int orderId = -1;
- private boolean isProcessed = false;
- private Customer customer = null;
- private List items = null;
-
-
- public int getOrderId()
- {
- return orderId;
- }
-
- public void setOrderId(int orderId)
- {
- this.orderId = orderId;
- }
-
- public boolean isProcessed()
- {
- return isProcessed;
- }
-
- public void setProcessed(boolean processed)
- {
- isProcessed = processed;
- }
-
- public Customer getCustomer()
- {
- return customer;
- }
-
- public void setCustomer(Customer customer)
- {
- this.customer = customer;
- }
-
- public List getItems()
- {
- return items;
- }
-
- public void setItems(List items)
- {
- this.items = items;
- }
-
- public String toString()
- {
- StringBuffer buffer = new StringBuffer();
- buffer.append("\nOrder:\n");
- buffer.append("\nIs processed: " + isProcessed);
- buffer.append("\nOrder id: " + orderId);
- buffer.append(customer.toString());
-
- buffer.append("\nItems ordered:");
- Iterator itr = items.iterator();
- while(itr.hasNext())
- {
- buffer.append("\n" + itr.next().toString());
- }
-
- return buffer.toString();
- }
-}</programlisting>
-
- <programlisting>public class <emphasis role="bold">OrderProcessorImpl</emphasis> implements <emphasis
- role="bold">OrderProcessor</emphasis>
-{
- private CustomerProcessor customerProcessor = null;
-
- public OrderProcessorImpl()
- {
- customerProcessor = new CustomerProcessorImpl();
- }
-
- public Order processOrder(Order order)
- {
- System.out.println("Incoming order to process from customer.\n" + order.getCustomer());
-
- // has this customer been processed?
- if(order.getCustomer().getCustomerId() < 0)
- {
- order.setCustomer(customerProcessor.processCustomer(order.getCustomer()));
- }
-
- List items = order.getItems();
- System.out.println("Items ordered:");
- Iterator itr = items.iterator();
- while(itr.hasNext())
- {
- System.out.println(itr.next());
- }
-
- order.setOrderId(new Random().nextInt(1000));
- order.setProcessed(true);
-
- System.out.println("Order processed. Order id now: " + order.getOrderId());
- return order;
- }
-}</programlisting>
-
- <programlisting>public interface OrderProcessor
-{
- public Order processOrder(Order order);
-}</programlisting>
-
- <para>The <code>OrderProcessorImpl</code> will take orders, via the
- <code>processOrder() </code>method, check that the customer for the
- order has been processed, and if not have the customer processor process
- the new customer. Then will place the order, which means will just set
- the order id and processed attribute to true.</para>
-
- <para>The most important point to this example is that the
- <code>Order</code> class does NOT implement
- <code>java.io.Serializable</code>.</para>
-
- <para>Now onto the <code>Server</code> class. This is just like the
- previous <code>Server</code> class in the basic example with one main
- difference: the <code>locatorURI</code> value.</para>
-
- <programlisting>public class <emphasis role="bold">Server</emphasis>
-{
- private String locatorURI = "socket://localhost:5400/?<emphasis role="bold">serializationtype=jboss</emphasis>";
- private TransporterServer server = null;
-
- public void start() throws Exception
- {
- server = TransporterServer.createTransporterServer(locatorURI, new OrderProcessorImpl());
- }
-
- public void stop()
- {
- if(server != null)
- {
- server.stop();
- }
- }
-
- public static void main(String[] args)
- {
- Server server = new Server();
- try
- {
- server.start();
-
- Thread.currentThread().sleep(60000);
-
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- server.stop();
- }
- }
-}</programlisting>
-
- <para>The addition of <literal>serializationtype=jboss</literal> tells
- the remoting framework to use JBoss Serialization in place of the
- standard java serialization.</para>
-
- <para>On the client side, there is the <code>Client</code> class, just
- as in the previous basic example.</para>
-
- <programlisting>public class <emphasis role="bold">Client</emphasis>
-{
- private String locatorURI = "socket://localhost:5400/?<emphasis role="bold">serializationtype=jboss</emphasis>";
-
- public void makeClientCall() throws Exception
- {
- Order order = createOrder();
-
- OrderProcessor orderProcessor = (OrderProcessor) TransporterClient.createTransporterClient(locatorURI, OrderProcessor.class);
-
- System.out.println("Order to be processed: " + order);
- Order changedOrder = orderProcessor.processOrder(order);
- System.out.println("Order now processed " + changedOrder);
-
- TransporterClient.destroyTransporterClient(orderProcessor);
-
- }
-
- private Order createOrder()
- {
- Order order = new Order();
- Customer customer = createCustomer();
- order.setCustomer(customer);
-
- List items = new ArrayList();
- items.add("Xbox 360");
- items.add("Wireless controller");
- items.add("Ghost Recon 3");
-
- order.setItems(items);
-
- return order;
- }
-
- private Customer createCustomer()
- {
- Customer cust = new Customer();
- cust.setFirstName("Bob");
- cust.setLastName("Smith");
- Address addr = new Address();
- addr.setStreet("101 Oak Street");
- addr.setCity("Atlanata");
- addr.setState("GA");
- addr.setZip(30249);
- cust.setAddr(addr);
-
- return cust;
- }
-
- public static void main(String[] args)
- {
- Client client = new Client();
- try
- {
- client.makeClientCall();
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
-}</programlisting>
-
- <para>Again, the biggest difference to note is that have added
- <literal>serializationtype=jboss</literal> to the locator uri.</para>
-
- <para>Note: Running this example requires JDK 1.5.</para>
-
- <para>To run this example, can run the Server and then the Client. Or
- can go to the examples directory and run the ant target 'ant
- run-transporter-serialization-server' and then in another window run the
- ant target 'ant run-transporter-serialization-client'. For
- example:</para>
-
- <programlisting>ant run-transporter-serialization-server</programlisting>
-
- <para>and then:</para>
-
- <programlisting>ant run-transporter-serialization-client</programlisting>
-
- <para>When the server and client are run the output for the
- <code>Client</code> class is:</para>
-
- <programlisting>Order to be processed:
-Order:
-
-Is processed: false
-Order id: -1
-Customer:
-customer id: -1
-first name: Bob
-last name: Smith
-street: 101 Oak Street
-city: Atlanata
-state: GA
-zip: 30249
-
-Items ordered:
-Xbox 360
-Wireless controller
-Ghost Recon 3
-Order now processed
-Order:
-
-Is processed: true
-Order id: 221
-Customer:
-customer id: 861
-first name: Bob
-last name: Smith
-street: 101 Oak Street
-city: Atlanata
-state: GA
-zip: 30249
-
-Items ordered:
-Xbox 360
-Wireless controller
-Ghost Recon 3
-</programlisting>
-
- <para>The client output shows the printout of the newly created order
- before calling the <code>OrderProcessor</code> and then the processed
- order afterwards. Noticed that the processed order has its customer's id
- set, its order id set and the processed attribute is set to true.</para>
-
- <para>And the output from the <code>Server</code> is:</para>
-
- <programlisting>Incoming order to process from customer.
-
-Customer:
-customer id: -1
-first name: Bob
-last name: Smith
-street: 101 Oak Street
-city: Atlanata
-state: GA
-zip: 30249
-
-processed customer with new id of 861
-Items ordered:
-Xbox 360
-Wireless controller
-Ghost Recon 3
-Order processed. Order id now: 221
-</programlisting>
-
- <para>The server output shows the printout of the customer before being
- processed and then the order while being processed.</para>
- </section>
-
- <section>
- <title>Transporter sample - clustered</title>
-
- <para>In the previous examples, there has been one and only one target
- POJO to make calls upon. If that target POJO was not available, the
- client call would fail. In the transporter clustered example (found in
- org.jboss.remoting.samples.transporter.clustered package), will show how
- to use the transporter in clustered mode so that if one target POJO
- becomes unavailable, the client call can be seamlessly failed over to
- another available target POJO on the network, regardless of network
- transport type.</para>
-
- <para>This example uses the domain objects from the first, basic
- example, so only need to cover the client and server code. For this
- example, there are three different server classes. The first class is
- the <code>SocketServer</code> class, which is the exact same as the
- <code>Server</code> class in the basic example, except for the call to
- the <code>TransportServer</code>'s <code>createTransportServer()
- </code>method.</para>
-
- <programlisting>public class <emphasis role="bold">SocketServer</emphasis>
-{
- public static String locatorURI = "socket://localhost:5400";
- private TransporterServer server = null;
-
- public void start() throws Exception
- {
- server = <emphasis role="bold">TransporterServer.createTransporterServer(getLocatorURI(), new CustomerProcessorImpl(),
- CustomerProcessor.class.getName(), true)</emphasis>;
- }
-
- protected String getLocatorURI()
- {
- return locatorURI;
- }
-
- public void stop()
- {
- if(server != null)
- {
- server.stop();
- }
- }
-
- public static void main(String[] args)
- {
- SocketServer server = new SocketServer();
- try
- {
- server.start();
-
- Thread.currentThread().sleep(60000);
-
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- server.stop();
- }
- }
-}</programlisting>
-
- <para>Notice that are now calling on the <code>TransportServer</code> to
- create a server with the locator uri and target POJO
- (<code>CustomerProcessorImpl</code>) as before, but have also added the
- interface type of the target POJO (<code>CustomerProcessor</code>) and
- that want clustering turned on (via the last <literal>true</literal>
- parameter).</para>
-
- <para>The interface type of the target POJO is needed because this will
- be used as the subsystem within the remoting server for the target POJO.
- The subsystem value will be what the client uses to determine if
- discovered remoting server is for the target POJO they are looking
- for.</para>
-
- <sidebar>
- <para>The transporter uses the MulticastDetector from JBoss Remoting
- for automatic discovery when in clustered mode. The actual detection
- of remote servers that come online can take up to a few seconds once
- started. There is a JNDI based detector provided within JBoss
- Remoting, but has not been integrated within the transporters
- yet.</para>
- </sidebar>
-
- <para>The second server class is the <code>RMIServer</code> class. The
- <code>RMIServer</code> class extends the <code>SocketServer</code> class
- and uses a different locator uri to specify <literal>rmi</literal> as the
- transport protocol and a different port
- (<literal>5500</literal>).</para>
-
- <programlisting>public class <emphasis role="bold">RMIServer</emphasis> extends <emphasis
- role="bold">SocketServer</emphasis>
-{
- private String localLocatorURI = "<emphasis role="bold">rmi://localhost:5500</emphasis>";
-
- protected String getLocatorURI()
- {
- return localLocatorURI;
- }
-
- public static void main(String[] args)
- {
- SocketServer server = new RMIServer();
- try
- {
- server.start();
-
- Thread.currentThread().sleep(60000);
-
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- server.stop();
- }
- }
-}</programlisting>
-
- <para>The last server class is the <code>HTTPServer</code> class. The
- <code>HTTPServer</code> class also extends the <code>SocketServer</code>
- class and specifies <literal>http</literal> as the transport protocol
- and <literal>5600</literal> as the port to listen for requests
- on.</para>
-
- <programlisting>public class <emphasis role="bold">HTTPServer</emphasis> extends <emphasis
- role="bold">SocketServer</emphasis>
-{
- private String localLocatorURI = "<emphasis role="bold">http://localhost:5600</emphasis>";
-
- protected String getLocatorURI()
- {
- return localLocatorURI;
- }
-
- public static void main(String[] args)
- {
- SocketServer server = new HTTPServer();
- try
- {
- server.start();
-
- Thread.currentThread().sleep(60000);
-
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- server.stop();
- }
- }
-}</programlisting>
-
- <para>On the client side, there is only the <code>Client</code> class.
- This class is very similar to the one from the basic example. The main
- exceptions are (1) the addition of a <code>TransporterClient</code> call
- to create a transporter client and (2) the fact that it continually
- loops, making calls on its <code>customerProcessor</code> variable to
- process customers. This is done so that when we run the client, we can
- kill the different servers and see that the client continues to loop
- making its calls without any exceptions or errors.</para>
-
- <programlisting>public class <emphasis role="bold">Client</emphasis>
-{
- <emphasis role="bold">private String locatorURI = SocketServer.locatorURI;</emphasis>
-
- private CustomerProcessor customerProcessor = null;
-
- public void makeClientCall() throws Exception
- {
- Customer customer = createCustomer();
-
- System.out.println("Customer to be processed: " + customer);
- <emphasis role="bold">Customer processedCustomer = customerProcessor.processCustomer(customer);</emphasis>
- System.out.println("Customer is now: " + processedCustomer);
-
- //TransporterClient.destroyTransporterClient(customerProcessor);
- }
-
- public void getCustomerProcessor() throws Exception
- {
- customerProcessor = (CustomerProcessor) <emphasis role="bold">TransporterClient.createTransporterClient(locatorURI, CustomerProcessor.class, true)</emphasis>;
- }
-
- private Customer createCustomer()
- {
- Customer cust = new Customer();
- cust.setFirstName("Bob");
- cust.setLastName("Smith");
- Address addr = new Address();
- addr.setStreet("101 Oak Street");
- addr.setCity("Atlanata");
- addr.setState("GA");
- addr.setZip(30249);
- cust.setAddr(addr);
-
- return cust;
- }
-
- public static void main(String[] args)
- {
- Client client = new Client();
- try
- {
-<emphasis role="bold"> client.getCustomerProcessor();
- while(true)
- {
- try
- {
- client.makeClientCall();
- Thread.currentThread().sleep(5000);
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
-</emphasis> }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
-}</programlisting>
-
- <para>The first item of note is that the locator uri from the
- <code>SocketServer</code> class is being used. Technically, this is not
- required as once the clustered <code>TransporterClient</code> is
- started, it will start to discover the remoting servers that exist on
- the network. However, this process can take several seconds to occur, so
- unless it is known that no calls will be made on the remote proxy right
- away, it is best to bootstrap with a known target server.</para>
-
- <para>Can also see that in the <code>main()</code> method, the first
- call on the Client instance is to <code>getCustomerProcessor()</code>.
- This method will call the <code>TransporterClient</code>'s
- <code>createTransporterClient()</code> method and passes the locator uri
- for the target POJO server, the type of POJO's remote proxy, and that
- clustering should be enabled.</para>
-
- <para>After getting the customer processor remote proxy, will
- continually loop making calls using the remote proxy (via the
- <code>processCustomer()</code> method on the
- <code>customerProcessor</code> variable).</para>
-
- <para>To run this example, all the servers need to be started (by
- running the <code>SocketServer</code>, <code>RMIServer</code>, and
- <code>HTTPServer</code> classes). Then run the Client class. This can be
- done via ant targets as well. So for example, could open four console
- windows and enter the ant targets as follows:</para>
-
- <programlisting>ant run-transporter-clustered-socket-server</programlisting>
-
- <programlisting>ant run-transporter-clustered-http-server</programlisting>
-
- <programlisting>ant run-transporter-clustered-rmi-server</programlisting>
-
- <programlisting>ant run-transporter-clustered-client</programlisting>
-
- <para>Once the client starts running, should start to see output logged
- to the <code>SocketServer</code>, since this is the one used to
- bootstrap. This output would look like:</para>
-
- <programlisting>processed customer with new id of 378
-processed customer with new id of 487
-processed customer with new id of 980</programlisting>
-
- <para>Once the <code>SocketServer</code> instance has received a few
- calls, kill this instance. The next time the client makes a call on its
- remote proxy, which happens every five seconds, it should fail over to
- another one of the servers (and will see similar output on that server
- instance). After that server has received a few calls, kill it and
- should see it fail over once again to the last server instance that is
- still running. Then, if kill that server instance, will see a
- CannotConnectException and stack trace similar to the following:</para>
-
- <programlisting><emphasis role="bold">...
-org.jboss.remoting.CannotConnectException</emphasis>: Can not connect http client invoker.
- at org.jboss.remoting.transport.http.HTTPClientInvoker.useHttpURLConnection(HTTPClientInvoker.java:147)
- at org.jboss.remoting.transport.http.HTTPClientInvoker.transport(HTTPClientInvoker.java:56)
- at org.jboss.remoting.RemoteClientInvoker.invoke(RemoteClientInvoker.java:112)
- at org.jboss.remoting.Client.invoke(Client.java:226)
- at org.jboss.remoting.Client.invoke(Client.java:189)
- at org.jboss.remoting.Client.invoke(Client.java:174)
- at org.jboss.remoting.transporter.TransporterClient.invoke(TransporterClient.java:219)
- at $Proxy0.processCustomer(Unknown Source)
- at org.jboss.remoting.samples.transporter3.client.Client.makeClientCall(Client.java:29)
- at org.jboss.remoting.samples.transporter3.client.Client.main(Client.java:64)
- at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
- at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
- at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
- at java.lang.reflect.Method.invoke(Method.java:585)
- at com.intellij.rt.execution.application.AppMain.main(AppMain.java:86)
-Caused by: java.net.ConnectException: Connection refused: connect
- at java.net.PlainSocketImpl.socketConnect(Native Method)
- at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
- at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
- at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
- at java.net.Socket.connect(Socket.java:507)
- at java.net.Socket.connect(Socket.java:457)
- at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
- at sun.net.www.http.HttpClient.openServer(HttpClient.java:365)
- at sun.net.www.http.HttpClient.openServer(HttpClient.java:477)
- at sun.net.www.http.HttpClient.<init>(HttpClient.java:214)
- at sun.net.www.http.HttpClient.New(HttpClient.java:287)
- at sun.net.www.http.HttpClient.New(HttpClient.java:299)
- at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:792)
- at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:744)
- at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:669)
- at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:836)
- at org.jboss.remoting.transport.http.HTTPClientInvoker.useHttpURLConnection(HTTPClientInvoker.java:117)
- ... 14 more</programlisting>
-
- <para>since there are no target servers left to make calls on. Notice
- that earlier in the client output there were no errors while was failing
- over to the different servers as they were being killed.</para>
-
- <para>Because the CannotConnectException is being caught within the
- while loop, the client will continue to try calling the remote proxy and
- getting this exception. Now re-run any of the previously killed servers
- and will see that the client will discover that server instance and
- begin to successfully call on that server. The output should look
- something like:</para>
-
- <programlisting>...
- at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:669)
- at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:836)
- at org.jboss.remoting.transport.http.HTTPClientInvoker.useHttpURLConnection(HTTPClientInvoker.java:117)
- ... 14 more
-
-Customer to be processed:
-Customer:
-customer id: -1
-first name: Bob
-last name: Smith
-street: 101 Oak Stree
-city: Atlanata
-state: null
-zip: 30249
-
-Customer is now:
-Customer:
-customer id: 633
-first name: Bob
-last name: Smith
-street: 101 Oak Stree
-city: Atlanata
-state: null
-zip: 30249
-
-...</programlisting>
-
- <sidebar>
- <para>As demonstrated in this example, fail over can occur across any
- of the JBoss Remoting transports. Clustered transporters is also
- supported using JBoss Serialization, which was introduced in the
- previous example.</para>
-
- <para>It is important to understand that in the context of
- transporters, clustering means invocation fail over. The JBoss
- Remoting transporters themselves do not handle any form of state
- replication. If this feature were needed, could use JBoss Cache to
- store the target POJO instances so that when their state changed, that
- change would be replicated to the other target POJO instances running
- in other processes.</para>
- </sidebar>
- </section>
-
- <section>
- <title>Transporters sample - multiple</title>
-
- <para>The multiple transporter example (found in
- org.jboss.remoting.samples.transporter.multiple package) shows how can
- have a multiple target pojos exposed via the same TransporterServer. In
- this example, will be two pojos being exposed, CustomerProcessorImpl and
- AccountProcessorImpl. Since the domain objects for this example is
- similar to the others discussed in previous examples, will just focus on
- the server and client code. On the server side, need to create the
- TransporterServer so that will included both of the target pojos.</para>
-
- <programlisting>public class Server
-{
- private String locatorURI = "socket://localhost:5400";
- private TransporterServer server = null;
-
- public void start() throws Exception
- {
- server = TransporterServer.createTransporterServer(locatorURI, new CustomerProcessorImpl(), CustomerProcessor.class.getName());
- server.addHandler(new AccountProcessorImpl(), AccountProcessor.class.getName());
- }
-
- public void stop()
- {
- if(server != null)
- {
- server.stop();
- }
- }
-
- public static void main(String[] args)
- {
- Server server = new Server();
- try
- {
- server.start();
-
- Thread.currentThread().sleep(60000);
-
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- server.stop();
- }
- }
-}</programlisting>
-
- <para>The TransporterServer is created with the CustomerProcessorImpl as
- the inital target pojo. Now that have a live TransporterServer, can add
- other pojos as targets. This is done using the addHandler() method where
- the target pojo instance is passed and then the interface type to be
- exposed as.</para>
-
- <para>Next have the Client that makes the call to both pojos.</para>
-
- <programlisting>public class Client
-{
- private String locatorURI = "socket://localhost:5400";
-
- public void makeClientCall() throws Exception
- {
- Customer customer = createCustomer();
-
- CustomerProcessor customerProcessor = (CustomerProcessor) TransporterClient.createTransporterClient(locatorURI, CustomerProcessor.class);
-
- System.out.println("Customer to be processed: " + customer);
- Customer processedCustomer = customerProcessor.processCustomer(customer);
- System.out.println("Customer is now: " + processedCustomer);
-
- AccountProcessor accountProcessor = (AccountProcessor) TransporterClient.createTransporterClient(locatorURI, AccountProcessor.class);
-
- System.out.println("Asking for a new account to be created for customer.");
- Account account = accountProcessor.createAccount(processedCustomer);
- System.out.println("New account: " + account);
-
- TransporterClient.destroyTransporterClient(customerProcessor);
- TransporterClient.destroyTransporterClient(accountProcessor);
-
- }
-
- private Customer createCustomer()
- {
- Customer cust = new Customer();
- cust.setFirstName("Bob");
- cust.setLastName("Smith");
- Address addr = new Address();
- addr.setStreet("101 Oak Street");
- addr.setCity("Atlanta");
- addr.setState("GA");
- addr.setZip(30249);
- cust.setAddr(addr);
-
- return cust;
- }
-
- public static void main(String[] args)
- {
- org.jboss.remoting.samples.transporter.multiple.client.Client client = new org.jboss.remoting.samples.transporter.multiple.client.Client();
- try
- {
- client.makeClientCall();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
-
-
-}</programlisting>
-
- <para>Notice that TransporterClients are created for each target pojo
- want to call upon, they just happen to share the same locator uri. These
- are independant instances so need to both be destroyed on their own when
- finished with them.</para>
-
- <para>To run this example, run the Server class and then the Client
- class. This can be done via ant targets
- 'run-transporter-multiple-server' and then
- 'run-transporter-multiple-client'. For example:</para>
-
- <programlisting>ant run-transporter-multiple-server</programlisting>
-
- <para>and then:</para>
-
- <programlisting>ant run-transporter-multiple-client</programlisting>
-
- <para>The output for the server should look similar to:</para>
-
- <programlisting>processed customer with new id of 980
-Created new account with account number: 1 and for customer:
-
-Customer:
-customer id: 980
-first name: Bob
-last name: Smith
-street: 101 Oak Street
-city: Atlanta
-state: GA
-zip: 30249</programlisting>
-
- <para>and the output from the client should look similar to:</para>
-
- <programlisting>Customer to be processed:
-Customer:
-customer id: -1
-first name: Bob
-last name: Smith
-street: 101 Oak Street
-city: Atlanta
-state: GA
-zip: 30249
-
-Customer is now:
-Customer:
-customer id: 980
-first name: Bob
-last name: Smith
-street: 101 Oak Street
-city: Atlanta
-state: GA
-zip: 30249
-
-Asking for a new account to be created for customer.
-New account: Account - account number: 1
-Customer:
-Customer:
-customer id: 980
-first name: Bob
-last name: Smith
-street: 101 Oak Street
-city: Atlanta
-state: GA
-zip: 30249
-</programlisting>
- </section>
-
- <section>
- <title>Transporters sample - proxy</title>
-
- <para>The proxy transporter example (found in
- org.jboss.remoting.samples.transporter.proxy package) shows how can have
- a TransporterClient sent over the network and called upon. In this
- example, will have a target pojo, CustomerProcessorImpl which itself
- creates a TransporterClient to another target pojo, Customer, and return
- it as response to a method invocation.</para>
-
- <para>To start, will look at the initial target pojo,
- CustomerProcessorImpl.</para>
-
- <programlisting>public class CustomerProcessorImpl implements CustomerProcessor
-{
- private String locatorURI = "socket://localhost:5401";
-
- /**
- * Takes the customer passed, and if not null and customer id
- * is less than 0, will create a new random id and set it.
- * The customer object returned will be the modified customer
- * object passed.
- *
- * @param customer
- * @return
- */
- public ICustomer processCustomer(Customer customer)
- {
- if (customer != null && customer.getCustomerId() < 0)
- {
- customer.setCustomerId(new Random().nextInt(1000));
- }
-
- ICustomer customerProxy = null;
- try
- {
- TransporterServer server = TransporterServer.createTransporterServer(locatorURI, customer, ICustomer.class.getName());
- customerProxy = (ICustomer) TransporterClient.createTransporterClient(locatorURI, ICustomer.class);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
-
- System.out.println("processed customer with new id of " + customerProxy.getCustomerId());
- return customerProxy;
- }
-
-}</programlisting>
-
- <para>Notice that the processCustomer() method will take a Customer
- object and set customer id on it. Then it will create a
- TransporterServer for that customer instance and also create a
- TransporterClient for the same instance and return that
- TransporterClient proxy as the return to the processCustomer()
- method.</para>
-
- <para>Next will look at the Customer class. It is a basic data object in
- that is really just stores the customer data.</para>
-
- <programlisting>public class Customer implements Serializable, ICustomer
-{
- private String firstName = null;
- private String lastName = null;
- private Address addr = null;
- private int customerId = -1;
-
- public String getFirstName()
- {
- return firstName;
- }
-
- public void setFirstName(String firstName)
- {
- this.firstName = firstName;
- }
-
- public String getLastName()
- {
- return lastName;
- }
-
- public void setLastName(String lastName)
- {
- this.lastName = lastName;
- }
-
- public Address getAddr()
- {
- return addr;
- }
-
- public void setAddr(Address addr)
- {
- this.addr = addr;
- }
-
- public int getCustomerId()
- {
- return customerId;
- }
-
- public void setCustomerId(int customerId)
- {
- this.customerId = customerId;
- }
-
- public String toString()
- {
- System.out.println("Customer.toString() being called.");
- StringBuffer buffer = new StringBuffer();
- buffer.append("\nCustomer:\n");
- buffer.append("customer id: " + customerId + "\n");
- buffer.append("first name: " + firstName + "\n");
- buffer.append("last name: " + lastName + "\n");
- buffer.append("street: " + addr.getStreet() + "\n");
- buffer.append("city: " + addr.getCity() + "\n");
- buffer.append("state: " + addr.getState() + "\n");
- buffer.append("zip: " + addr.getZip() + "\n");
-
- return buffer.toString();
- }
-
-
-}
-</programlisting>
-
- <para>Notice the toString() method and how it prints out to the standard
- out when being called. This will be important when the sample is run
- later.</para>
-
- <para>Now if look at the Server class, will see is a standard setup like
- have seen in previous samples.</para>
-
- <programlisting>public class Server
-{
- private String locatorURI = "socket://localhost:5400";
- private TransporterServer server = null;
-
- public void start() throws Exception
- {
- server = TransporterServer.createTransporterServer(locatorURI, new CustomerProcessorImpl(), CustomerProcessor.class.getName());
- }
-
- public void stop()
- {
- if (server != null)
- {
- server.stop();
- }
- }
-
- public static void main(String[] args)
- {
- Server server = new Server();
- try
- {
- server.start();
-
- Thread.currentThread().sleep(60000);
-
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- server.stop();
- }
- }
-}</programlisting>
-
- <para>It is creating a TransporterServer for the CustomerProcessImpl
- upon being started and will wait 60 seconds for invocations.</para>
-
- <para>Next is the Client class. </para>
-
- <programlisting>public class Client
-{
- private String locatorURI = "socket://localhost:5400";
-
- public void makeClientCall() throws Exception
- {
- Customer customer = createCustomer();
-
- CustomerProcessor customerProcessor = (CustomerProcessor) TransporterClient.createTransporterClient(locatorURI, CustomerProcessor.class);
-
- System.out.println("Customer to be processed: " + customer);
- ICustomer processedCustomer = customerProcessor.processCustomer(customer);
- // processedCustomer returned is actually a proxy to the Customer instnace
- // that lives on the server. So when print it out below, will actually
- // be calling back to the server to get the string (vi toString() call).
- // Notice the output of 'Customer.toString() being called.' on the server side.
- System.out.println("Customer is now: " + processedCustomer);
-
- TransporterClient.destroyTransporterClient(customerProcessor);
-
-
- }
-
- private Customer createCustomer()
- {
- Customer cust = new Customer();
- cust.setFirstName("Bob");
- cust.setLastName("Smith");
- Address addr = new Address();
- addr.setStreet("101 Oak Street");
- addr.setCity("Atlanta");
- addr.setState("GA");
- addr.setZip(30249);
- cust.setAddr(addr);
-
- return cust;
- }
-
- public static void main(String[] args)
- {
- Client client = new Client();
- try
- {
- client.makeClientCall();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
-
-
-}</programlisting>
-
- <para>The client class looks similar to the other example seen in that
- it creates a TransporterClient for the CustomerProcessor and calls on it
- to process the customer. Will then call on the ICustomer instance
- returned from the processCustomer() method call and call toString() on
- it (in the system out call). </para>
-
- <para>To run this example, run the Server class and then the Client
- class. This can be done via ant targets 'run-transporter-proxy-server'
- and then 'run-transporter-proxy-client'. For example:</para>
-
- <programlisting>ant run-transporter-proxy-server</programlisting>
-
- <para>ant then:</para>
-
- <programlisting>ant run-transporter-proxy-client</programlisting>
-
- <para>The output for the client should look similar to:</para>
-
- <programlisting>Customer.toString() being called.
-Customer to be processed:
-Customer:
-customer id: -1
-first name: Bob
-last name: Smith
-street: 101 Oak Street
-city: Atlanta
-state: GA
-zip: 30249
-
-Customer is now:
-Customer:
-customer id: 418
-first name: Bob
-last name: Smith
-street: 101 Oak Street
-city: Atlanta
-state: GA
-zip: 30249
-</programlisting>
-
- <para>The first line
- is the print out from calling the Customer's toString() method that was
- created to be passed to the CustomerProcessor's processCustomer()
- method. Then the contents of the Customer object before being processed.
- Then have the print out of the customer after has been processed. Notice
- that when the ICustomer object instance is printed out the second time,
- do not see the 'Customer.toString() being called'. This is because that
- code is no longer being executed in the client vm, but instead is a
- remote call to the customer instance living on the server (remember, the
- processCustomer() method returned a TransporterClient proxy to the
- customer living on the server side).</para>
-
- <para>Now, if look at output from the server will look similar
- to:</para>
-
- <programlisting>processed customer with new id of 418
-Customer.toString() being called.</programlisting>
-
- <para>Notice that the 'Customer.toString() being called.' printed out at
- the end. This is the result of the client's call to print out the
- contents of the customer object returned from the processCustomer()
- method, which actually lives within the server vm.</para>
-
- <para>This example has shown how can pass around TransporterClient
- proxies to target pojos. However, when doing this, is important to
- understand where the code is actually being executed as there are
- consequences to being remote verse local, which need to be
- understood.</para>
- </section>
-
- <section>
- <title>Transporter sample -complex</title>
-
- <para>The complex transporter example (found in
- org.jboss.remoting.samples.transporter.complex package) is based off a
- test case a user, Milt Grinberg, provided (thanks Milt). The example is
- similar to the previous examples, except in this case involves matching
- Doctors and Patients using the ProviderInterface and provides a more
- complex sample in which to demonstrate how to use transporters.</para>
-
- <para>This example requires JDK 1.5 to run, since is using JBoss
- Serialization (and non-serialized data objects). To run this example,
- run the Server class and then the Client class. This can be done via ant
- targets 'run-transporter-complex-server' and then
- 'run-transporter-complex-client' as well. For example:</para>
-
- <programlisting>ant run-transporter-complex-server</programlisting>
-
- <para>and then:</para>
-
- <programlisting>ant run-transporter-complex-client</programlisting>
-
- <para>The output for the client should look similar to:</para>
-
- <programlisting>*** Have a new patient that needs a doctor. The patient is:
-
-Patient:
- Name: Bill Gates
- Ailment - Type: financial, Description: Money coming out the wazoo.
-
-*** Looking for doctor that can help our patient...
-
-*** Found doctor for our patient. Doctor found is:
-Doctor:
- Name: Andy Jones
- Specialty: financial
- Patients:
-
-Patient:
- Name: Larry Ellison
- Ailment - Type: null, Description: null
- Doctor - Name: Andy Jones
-
-Patient:
- Name: Steve Jobs
- Ailment - Type: null, Description: null
- Doctor - Name: Andy Jones
-
-Patient:
- Name: Bill Gates
- Ailment - Type: financial, Description: Money coming out the wazoo.
-
-*** Set doctor as patient's doctor. Patient info is now:
-
-Patient:
- Name: Bill Gates
- Ailment - Type: financial, Description: Money coming out the wazoo.
- Doctor - Name: Andy Jones
-
-*** Have a new patient that we need to find a doctor for (remember, the previous one retired and there are no others)
-*** Could not find doctor for patient. This is an expected exception when there are not doctors available.
-org.jboss.remoting.samples.transporter.complex.NoDoctorAvailableException: No doctor available for ailment 'financial'
- at org.jboss.remoting.RemoteClientInvoker.invoke(RemoteClientInvoker.java:183)
- at org.jboss.remoting.Client.invoke(Client.java:325)
- at org.jboss.remoting.Client.invoke(Client.java:288)
- at org.jboss.remoting.Client.invoke(Client.java:273)
- at org.jboss.remoting.transporter.TransporterClient.invoke(TransporterClient.java:237)
- at $Proxy0.findDoctor(Unknown Source)
- at org.jboss.remoting.samples.transporter.complex.client.Client.makeClientCall(Client.java:72)
- at org.jboss.remoting.samples.transporter.complex.client.Client.main(Client.java:90)
- at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
- at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
- at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
- at java.lang.reflect.Method.invoke(Method.java:585)
- at com.intellij.rt.execution.application.AppMain.main(AppMain.java:86)
-</programlisting>
-
- <para>From the output see the creation of a new patient, Bill Gates, and
- the attempt to find a doctor that specializes in his ailment. For Mr.
- Gates, we were able to find a doctor, Andy Jones, and can see that he
- has been added to the list of Dr. Jones' patients. Then we have Dr.
- Jones retire. Then we create a new patient and try to find an available
- doctor for the same ailment. Since Dr. Jones has retired, and there are
- no other doctors that specialize in that particular ailment, an
- exception is thrown. This is as expected.</para>
- </section>
- </section>
-
- <section>
- <title id="section-multiplex-invokers"
- xreflabel="Multiplex invokers">Multiplex invokers</title>
-
- <para>This section illustrates the construction of multiplex invoker
- groups described in the section <xref linkend="section-multiplex-invoker" />. The
- directory</para>
-
- <blockquote>
- <para><code>examples/org/jboss/remoting/samples/multiplex/invoker</code></para>
- </blockquote>
-
- <para>contains a server class,
- <classname>MultiplexInvokerServer</classname>, which is suitable for use
- with any of the client classes described below. It may be run in an IDE or
- from the command line using ant target <code>run-multiplex-server</code>
- from the <code>build.xml</code> file found in the <code>examples</code>
- directory. The server will stay alive, processing invocation requests as
- they are presented, until it has sent two push callbacks to however many
- listeners are registered, at which time it will shut itself down.</para>
-
- <para>The sample clients are as follows. Each sample client
- <emphasis><client></emphasis> may be run in an IDE or by using the
- ant target <code>run-</code><emphasis><client></emphasis> (e.g.,
- <code>run-Client2Server1</code>).</para>
-
- <itemizedlist>
- <listitem>
- <para><classname>Client2Server1</classname>: A
- <classname>MultiplexClientInvoker</classname> starts according to
- client rule 2, after which a
- <classname>MultiplexServerInvoker</classname> is started according to
- server rule 1. Note that the <classname>Client</classname> and
- <classname>Connector</classname> are passed matching
- <emphasis>clientMultiplexId</emphasis> and
- <emphasis>serverMultiplexId</emphasis> parameters,
- respectively.</para>
- </listitem>
-
- <listitem>
- <para><classname>Client2Server2</classname>: A
- <classname>MultiplexClientInvoker</classname> starts according to
- client rule 2, after which a
- <classname>MultiplexServerInvoker</classname> is started according to
- server rule 2. Note that no <emphasis>clientMultiplexId</emphasis> is
- passed to the <classname>Client</classname> and no
- <emphasis>serverMultiplexId</emphasis> parameter is passed to the
- <classname>Connector</classname> in this example.</para>
- </listitem>
-
- <listitem>
- <para><classname>Client3Server1</classname>: A
- <classname>MultiplexClientInvoker</classname> is created, and, lacking
- binding information, finds itself governed by client rule 3.
- Subsequently, a <classname>MultiplexServerInvoker</classname> is
- started according to server rule 1, providing the binding information
- which allows the <classname>MultiplexClientInvoker</classname> to
- start. Note that the <classname>Client</classname> and
- <classname>Connector</classname> are passed matching
- <emphasis>clientMultiplexId</emphasis> and
- <emphasis>serverMultiplexId</emphasis> parameters,
- respectively.</para>
- </listitem>
-
- <listitem>
- <para><classname>Server2Client1</classname>: A
- <classname>MultiplexServerInvoker</classname> starts according to
- server rule 2, after which a
- <classname>MultiplexClientInvoker</classname> is started according to
- client rule 1. Note that the <classname>Connector</classname> and
- <classname>Client</classname> are passed matching
- <emphasis>serverMultiplexId</emphasis> and
- <emphasis>clientMultiplexId</emphasis> parameters,
- respectively.</para>
- </listitem>
-
- <listitem>
- <para><classname>Server2Client2</classname>: A
- <classname>MultiplexServerInvoker</classname> starts according to
- server rule 2, after which a
- <classname>MultiplexClientInvoker</classname> is started according to
- client rule 2. Note that no <emphasis>serverMultiplexId</emphasis> is
- passed to the <classname>Connector</classname> and no
- <emphasis>clientMultiplexId</emphasis> parameter is passed to the
- <classname>Client</classname> in this example.</para>
- </listitem>
-
- <listitem>
- <para><classname>Server3Client1</classname>: A
- <classname>MultiplexServerInvoker</classname> is created, and, lacking
- connect information, finds itself governed by server rule 3.
- Subsequently, a <classname>MultiplexClientInvoker</classname> is
- started according to client rule 1, providing the connect information
- which allows the <classname>MultiplexServerInvoker</classname> to
- start. Note that the <classname>Connector</classname> and
- <classname>Client</classname> are passed matching
- <emphasis>serverMultiplexId</emphasis> and
- <emphasis>clientMultiplexId</emphasis> parameters,
- respectively.</para>
- </listitem>
- </itemizedlist>
-
- <para>For variety, the examples in which the client invoker starts first
- use the configuration <classname>Map</classname> to pass invoker group
- parameters, and the examples in which the server invoker starts first pass
- parameters in the <classname>InvokerLocator</classname>.</para>
- </section>
-</chapter>
\ No newline at end of file
+ <para>When boiled down, transporters take a plain old java object (POJO)
+ and expose a remote proxy to it via JBoss Remoting. Dynamic proxies and
+ reflection are used to make the typed method calls on that target POJO.
+ Since JBoss Remoting is used, can select from a number of different
+ network transports (i.e. rmi, http, socket, multiplex, etc.), including
+ support for SSL. Even clustering features can be included. See the
+ transporter samples in the next chapter for detailed examples of how to
+ set up use of a transporter.</para>
+ </chapter>
\ No newline at end of file
16 years, 4 months
JBoss Remoting SVN: r4700 - remoting2/branches/2.x/docs/guide/en.
by jboss-remoting-commits@lists.jboss.org
Author: ron.sigal(a)jboss.com
Date: 2008-11-18 15:39:41 -0500 (Tue, 18 Nov 2008)
New Revision: 4700
Modified:
remoting2/branches/2.x/docs/guide/en/chap12.xml
Log:
JBREM-1057: Replacing screwed up chapter.
Modified: remoting2/branches/2.x/docs/guide/en/chap12.xml
===================================================================
--- remoting2/branches/2.x/docs/guide/en/chap12.xml 2008-11-18 20:39:26 UTC (rev 4699)
+++ remoting2/branches/2.x/docs/guide/en/chap12.xml 2008-11-18 20:39:41 UTC (rev 4700)
@@ -1,17 +1,23 @@
<chapter>
- <title>Compatibility and versioning</title>
+ <title>Client programming model</title>
- <para>As of JBossRemoting 2.0.0 versioning has been added to guarantee
- compatibility between different versions. This is accomplished by changing
- serialization formats for certain classes and by using wire versioning. By
- wire versioning, mean that the version used by a client and server will be
- sent on the wire so that the other side will be able to adjust
- accordingly. This will be automatic for JBossRemoting 2.0.0 and later
- versions. However, since versioning was not introduced until the 2.0.0
- release, if need to have a 1.4.x version of remoting communicate to a
- later version, will need to set a system property on the 2.0.0 version so
- that knows to use the older wire protocol version. The system property to
- set is 'jboss.remoting.pre_2_0_compatible' and should be set to true.
- There are a few minor features that will not be fully compatible between
- 1.4.x release and 2.0.0, which are listed in the release notes.</para>
+ <para>The approach taken for the programming model on the client side is
+ one based on a session based model. This means that it is expected that
+ once a Client is created for a particular target server, it will be used
+ exclusively to make calls on that server. This expectation dictates some
+ of the behavior of the remoting client.</para>
+
+ <para>For example, if create a Client on the client side to make server
+ invocations, including adding callback listeners, will have to use that
+ same instance of Client to remove the callback listeners. This is because
+ the Client creates a unique session id that it passes within the calls to
+ the server. This id is used as part of the key for registering callback
+ listeners on the server. If create a new Client instance and attempt to
+ remove the callback listeners, a new session id will be passed to the
+ server invoker, who will not recognize the callback listener to be
+ removed.</para>
+
+ <para>See test case
+ <code>org.jboss.test.remoting.callback.push.MultipleCallbackServersTestCase</code>
+ .</para>
</chapter>
\ No newline at end of file
16 years, 4 months
JBoss Remoting SVN: r4699 - remoting2/branches/2.x/docs/guide/en.
by jboss-remoting-commits@lists.jboss.org
Author: ron.sigal(a)jboss.com
Date: 2008-11-18 15:39:26 -0500 (Tue, 18 Nov 2008)
New Revision: 4699
Modified:
remoting2/branches/2.x/docs/guide/en/chap15.xml
Log:
JBREM-1057: Replacing screwed up chapter.
Modified: remoting2/branches/2.x/docs/guide/en/chap15.xml
===================================================================
--- remoting2/branches/2.x/docs/guide/en/chap15.xml 2008-11-18 20:39:09 UTC (rev 4698)
+++ remoting2/branches/2.x/docs/guide/en/chap15.xml 2008-11-18 20:39:26 UTC (rev 4699)
@@ -1,22 +1,16 @@
<chapter>
- <title>Future plans</title>
+ <title>Known issues</title>
- <para>Full road map for JBossRemoting can be found at <!--<link linkend="???">
- http://jira.jboss.com/jira/browse/JBREM?report=com.atlassian.jira.plugin....
- </link>--> <ulink
- url="http://jira.jboss.com/jira/browse/JBREM?report=com.atlassian.jira.plugin....">
- http://jira.jboss.com/jira/browse/JBREM?report=com.atlassian.jira.plugin....
- </ulink>.</para>
-
- <para>If you have questions, comments, bugs, fixes, contributions, or
- flames, please post them to the JBoss Remoting users forum <!--<link linkend="???">http://www.jboss.com/index.html?module=bb&op=viewforum&f=222</link>-->
+ <para>All of the known issues and road map can be found on our bug
+ tracking system, Jira, at <!--<link linkend="???">http://jira.jboss.com/jira/secure/BrowseProject.jspa?id=10031</link>-->
+ <ulink
+ url="http://jira.jboss.com/jira/secure/BrowseProject.jspa?id=10031">
+ http://jira.jboss.com/jira/secure/BrowseProject.jspa?id=10031 </ulink>
+ (require member plus registration, which is free). If you find more,
+ please post them to Jira. If you have questions post them to the JBoss
+ Remoting users forum <!--<link linkend="???">http://www.jboss.com/index.html?module=bb&op=viewforum&f=222</link>-->
(<ulink
url="http://www.jboss.com/index.html?module=bb&op=viewforum&f=222">
http://www.jboss.com/index.html?module=bb&op=viewforum&f=222
- </ulink>). You can also find more information about JBoss Remoting on our
- <!--<link linkend="???">http://www.jboss.org/wiki/Wiki.jsp?page=Remoting</link>-->
- wiki (<ulink url="http://www.jboss.org/wiki/Wiki.jsp?page=Remoting">
- http://www.jboss.org/wiki/Wiki.jsp?page=Remoting </ulink> ). The wiki will
- usually contain the latest updates to doc and features that did not make
- into previous release.</para>
+ </ulink>).</para>
</chapter>
\ No newline at end of file
16 years, 4 months
JBoss Remoting SVN: r4698 - remoting2/branches/2.x/docs/guide/en.
by jboss-remoting-commits@lists.jboss.org
Author: ron.sigal(a)jboss.com
Date: 2008-11-18 15:39:09 -0500 (Tue, 18 Nov 2008)
New Revision: 4698
Modified:
remoting2/branches/2.x/docs/guide/en/chap7.xml
Log:
JBREM-1057: Replacing screwed up chapter.
Modified: remoting2/branches/2.x/docs/guide/en/chap7.xml
===================================================================
--- remoting2/branches/2.x/docs/guide/en/chap7.xml 2008-11-18 18:52:09 UTC (rev 4697)
+++ remoting2/branches/2.x/docs/guide/en/chap7.xml 2008-11-18 20:39:09 UTC (rev 4698)
@@ -1,44 +1,121 @@
- <chapter>
- <title>Serialization</title>
+<chapter>
+ <title>Sending streams</title>
- <para>Serialization - how it works within remoting: In general, remoting
- will rely on a factory to provide the serialization implementation, or
- <code>org.jboss.remoting.serialization.SerializationManager</code>, to be
- used when doing object serialization. This factory is
- <code>org.jboss.remoting.serialization.SerializationStreamFactory</code>
- and is a (as defined by its javadoc):</para>
+ <para>Remoting supports the sending of InputStreams. It is important to
+ note that this feature DOES NOT copy the stream data directly from the
+ client to the server, but is a true on demand stream. Although this is
+ obviously slower than reading from a stream on the server that has been
+ copied locally, it does allow for true streaming on the server. It also
+ allows for better memory control by the user (versus the framework trying
+ to copy a 3 Gig file into memory and getting out of memory errors).</para>
- <literallayout>factory is for defining the Object stream implemenations to be used along with creating those implemenations for use.
-The main function will be to return instance of ObjectOutput and ObjectInput. By default, the implementations will be
-java.io.ObjectOutputStream and java.io.ObjectInputStream.
-</literallayout>
+ <para>Use of this new feature is simple. From the client side, there is a
+ method in org.jboss.remoting.Client with the signature:</para>
- <para>Currently there are only two different types of serialization
- implementations; 'java' and 'jboss'. The 'java' type uses
- <code>org.jboss.remoting.serialization.impl.java.JavaSerializationManager</code>
- as the SerializationManager implementation and is backed by standard Java
- serialization provide by the JVM, which is the default. The 'jboss' type
- uses
- <code>org.jboss.remoting.serialization.impl.jboss.JBossSerializationManager</code>
- as the SerializationManager implementation and is backed by JBoss
- Serialization.</para>
+ <programlisting>public Object invoke(InputStream inputStream, Object param) throws Throwable
+ </programlisting>
- <para>JBoss Serialization is a new project under development to provide a
- more performant implementation of object serialization. It complies with
- java serialization standard with three exceptions:</para>
+ <para>So from the client side, would just call invoke as done in the past,
+ and pass the InputStream and the payload as the parameters. An example of
+ the code from the client side would be (this is taken directly from
+ org.jboss.test.remoting.stream.StreamingTestClient):</para>
- <para>- SerialUID not needed</para>
+ <programlisting>
+ String param = "foobar";
+ File testFile = new File(fileURL.getFile());
+ ...
+ Object ret = remotingClient.invoke(fileInput, param);
+ </programlisting>
- <para>- java.io.Serializable is not required</para>
+ <para>From the server side, will need to implement
+ <code>org.jboss.remoting.stream.StreamInvocationHandler</code> instead of
+ <code>org.jboss.remoting.ServerInvocationHandler</code> .
+ StreamInvocationHandler extends ServerInvocationHandler, with the addition
+ of one new method:</para>
- <para>- different protocol</para>
+ <programlisting>public Object handleStream(InputStream stream, Object param)</programlisting>
- <para>JBoss Serialization requires JDK 1.5</para>
+ <para>The stream passed to this method can be called on just as any
+ regular local stream. Under the covers, the InputStream passed is really
+ proxy to the real input stream that exists in the client's VM. Subsequent
+ calls to the passed stream will actually be converted to calls on the real
+ stream on the client via this proxy. If the client makes an invocation on
+ the server passing an InputStream as the parameter and the server handler
+ does not implement StreamInvocationhandler, an exception will be thrown to
+ the client caller.</para>
- <para></para>
+ <para>If want to have more control over the stream server being created to
+ send the stream data back to the caller, instead of letting remoting
+ create it internally, can do this by creating a Connector to act as stream
+ server and pass it when making Client invocation.</para>
- <para>It is possible to override the default SerializationManger
- implementation to be used by setting the system property 'SERIALIZATION'
- to the fully qualified name of the class to use (which will need to
- provide a void constructor).</para>
+ <programlisting>public Object invoke(InputStream inputStream, Object param, Connector streamConnector) throws Throwable</programlisting>
+
+ <para>Note, the Connector passed must already have been started (else an
+ exception will be thrown). The stream handler will then be added to the
+ connector with the subystem 'stream'. The Connector passed will NOT be
+ stopped when the stream is closed by the server's stream proxy (which
+ happens automatically when remoting creates the stream server
+ internally).</para>
+
+ <para>Can also call <methodname>invoke()</methodname> method on client and
+ pass the invoker locator
+ would like to use and allow remoting to create the stream server using the
+ specified locator.</para>
+
+ <programlisting>public Object invoke(InputStream inputStream, Object param, InvokerLocator streamServerLocator) throws Throwable </programlisting>
+
+ <para>In this case, the Connector created internally by remoting will be
+ stopped when the stream is closed by the server's stream proxy.</para>
+
+ <para>It is VERY IMPORTANT that the StreamInvocationHandler implementation
+ close the InputStream when it finishes reading, as will close the real
+ stream that lives within the client VM.</para>
+
+ <section>
+ <title>Configuration</title>
+
+ <para>By default, the stream server which runs within the client JVM
+ uses the following values for its locator uri:</para>
+
+ <para>transport - socket</para>
+
+ <para>host - tries to first get local host name and if that fails, the
+ local ip (if that fails, localhost).</para>
+
+ <para>port - 5405</para>
+
+ <para>Currently, the only way to override these settings is to set the
+ following system properties (either via JVM arguments or via
+ <code>System.setProperty()</code> method):</para>
+
+ <para>remoting.stream.transport - sets the transport type (rmi, http,
+ socket, etc.)</para>
+
+ <para>remoting.stream.host - host name or ip address to use</para>
+
+ <para>remoting.stream.port - the port to listen on</para>
+
+ <para>These properties are important because currently the only way for
+ a target server to get the stream data from the stream server (running
+ within the client JVM) is to have the server invoker make the invocation
+ on a new connection back to the client (see issues below).</para>
+ </section>
+
+ <section>
+ <title>Issues</title>
+
+ <para>This is a first pass at the implementation and needs some work in
+ regards to optimizations and configuration. In particular, there is a
+ remoting server that is started to service requests from the stream
+ proxy on the target server for data from the original stream. This
+ raises an issue with the current transports, since the client will have
+ to accept calls for the original stream on a different socket. This may
+ be difficult when control over the client's environment (including
+ firewalls) may not be available. A bi-directional transport, called
+ multiplex, is being introduced as of 1.4.0 release which will allow
+ calls from the server to go over the same socket connection established
+ by the client to the server (JBREM-91). This will make communications
+ back to client much simpler from this standpoint.</para>
+ </section>
</chapter>
\ No newline at end of file
16 years, 4 months
JBoss Remoting SVN: r4697 - remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex.
by jboss-remoting-commits@lists.jboss.org
Author: david.lloyd(a)jboss.com
Date: 2008-11-18 13:52:09 -0500 (Tue, 18 Nov 2008)
New Revision: 4697
Modified:
remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/FutureRemoteRequestHandlerSource.java
remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexConnection.java
remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexReadHandler.java
remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexReplyHandler.java
remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexRequestHandler.java
remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexRequestHandlerSource.java
Log:
More logging updates
Modified: remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/FutureRemoteRequestHandlerSource.java
===================================================================
--- remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/FutureRemoteRequestHandlerSource.java 2008-11-15 02:11:16 UTC (rev 4696)
+++ remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/FutureRemoteRequestHandlerSource.java 2008-11-18 18:52:09 UTC (rev 4697)
@@ -43,4 +43,8 @@
protected boolean setResult(final RequestHandlerSource result) {
return super.setResult(result);
}
+
+ public String toString() {
+ return "future remote request handler source <" + Integer.toHexString(hashCode()) + ">";
+ }
}
Modified: remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexConnection.java
===================================================================
--- remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexConnection.java 2008-11-15 02:11:16 UTC (rev 4696)
+++ remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexConnection.java 2008-11-18 18:52:09 UTC (rev 4697)
@@ -141,6 +141,7 @@
}
void doBlockingWrite(ByteBuffer... buffers) throws IOException {
+ log.trace("Sending message:\n%s", new MultiDumper(buffers));
if (buffers.length == 1) doBlockingWrite(buffers[0]); else for (;;) {
if (channel.send(buffers)) {
return;
@@ -149,6 +150,30 @@
}
}
+ private static final class MultiDumper {
+ private final ByteBuffer[] buffers;
+
+ public MultiDumper(final ByteBuffer[] buffers) {
+ this.buffers = buffers;
+ }
+
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ for (int i = 0; i < buffers.length; i++) {
+ ByteBuffer buffer = buffers[i];
+ builder.append("Buffer ");
+ builder.append(i);
+ builder.append(":\n");
+ try {
+ Buffers.dump(buffer, builder, 8, 1);
+ } catch (IOException e) {
+ // ignore
+ }
+ }
+ return builder.toString();
+ }
+ }
+
void doBlockingWrite(ByteBuffer buffer) throws IOException {
log.trace("Sending message:\n%s", Buffers.createDumper(buffer, 8, 1));
for (;;) {
@@ -256,6 +281,7 @@
}
public Handle<RequestHandlerSource> openRemoteService(final QualifiedName name) throws IOException {
+ log.trace("Sending request to open remote service \"%s\"", name);
final FutureRemoteRequestHandlerSource future = new FutureRemoteRequestHandlerSource();
int id;
for (;;) {
@@ -272,7 +298,7 @@
doBlockingWrite(buffer);
try {
final Handle<RequestHandlerSource> handle = future.getInterruptibly().getHandle();
- log.trace("Opened %s to %s", handle, this);
+ log.trace("Opened %s", handle);
return handle;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
@@ -426,7 +452,7 @@
}
public String toString() {
- return "multiplex connection <" + Integer.toHexString(hashCode()) + "> on " + channel;
+ return "multiplex connection <" + Integer.toHexString(hashCode()) + "> via " + channel;
}
@SuppressWarnings({ "unchecked" })
Modified: remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexReadHandler.java
===================================================================
--- remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexReadHandler.java 2008-11-15 02:11:16 UTC (rev 4696)
+++ remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexReadHandler.java 2008-11-18 18:52:09 UTC (rev 4697)
@@ -84,7 +84,7 @@
channel.resumeReads();
return;
}
- log.trace("Received message:\n%s", Buffers.createDumper(buffer, 8, 1));
+ log.trace("Received raw message:\n%s", Buffers.createDumper(buffer, 8, 1));
final MessageType msgType;
try {
msgType = MessageType.getMessageType(buffer.get() & 0xff);
@@ -92,7 +92,6 @@
log.trace("Received invalid message type");
return;
}
- log.trace("Decoded message type %s", msgType);
switch (msgType) {
case REQUEST: {
final int clientId = buffer.getInt();
@@ -109,6 +108,7 @@
unmarshaller.start(Marshalling.createByteInput(buffer));
payload = unmarshaller.readObject();
unmarshaller.finish();
+ log.trace("Received inbound request (client id = %d, request id = %d) (type is %s)", Integer.valueOf(clientId), Integer.valueOf(requestId), payload == null ? "null" : payload.getClass());
} finally {
IoUtils.safeClose(unmarshaller);
}
@@ -155,6 +155,7 @@
unmarshaller.start(Marshalling.createByteInput(buffer));
payload = unmarshaller.readObject();
unmarshaller.finish();
+ log.trace("Received inbound reply (id = %d) (type is %s)", Integer.valueOf(requestId), payload == null ? "null" : payload.getClass());
} finally {
IoUtils.safeClose(unmarshaller);
}
@@ -171,6 +172,7 @@
final int requestId = buffer.getInt();
final RemoteRequestContext context = connection.getLocalRequest(requestId);
if (context != null) {
+ log.trace("Received inbound cancel request (request id = %d) to %s", Integer.valueOf(requestId), context);
context.cancel();
}
break;
@@ -179,6 +181,7 @@
final int requestId = buffer.getInt();
final ReplyHandler replyHandler = connection.getRemoteRequest(requestId);
if (replyHandler != null) {
+ log.trace("Received inbound cancel acknowledge (request id = %d) to ", Integer.valueOf(requestId), replyHandler);
SpiUtils.safeHandleCancellation(replyHandler);
}
break;
@@ -187,7 +190,7 @@
final int requestId = buffer.getInt();
final ReplyHandler replyHandler = connection.removeRemoteRequest(requestId);
if (replyHandler == null) {
- log.trace("Got reply to unknown request %d", Integer.valueOf(requestId));
+ log.trace("Got a failure reply to unknown request %d to %s", Integer.valueOf(requestId), replyHandler);
break;
}
final IOException cause;
@@ -197,13 +200,16 @@
unmarshaller.start(Marshalling.createByteInput(buffer));
cause = (IOException) unmarshaller.readObject();
unmarshaller.finish();
+ log.trace("Received inbound request receive failure notification to %s: %s", replyHandler, cause);
} finally {
IoUtils.safeClose(unmarshaller);
}
} catch (IOException e) {
+ log.trace("Received inbound request receive failure notification; the remote exception could not be read: %s", e);
SpiUtils.safeHandleException(replyHandler, new RemoteExecutionException("Remote operation failed; the remote exception could not be read", e));
break;
} catch (ClassNotFoundException e) {
+ log.trace("Received inbound request receive failure notification; the remote exception could not be read: %s", e);
SpiUtils.safeHandleException(replyHandler, new RemoteExecutionException("Remote operation failed; the remote exception could not be read", e));
break;
}
@@ -224,11 +230,14 @@
unmarshaller.start(Marshalling.createByteInput(buffer));
try {
cause = (IOException) unmarshaller.readObject();
+ log.trace("Received inbound request failure notification: %s", cause);
} catch (ClassNotFoundException e) {
+ log.trace("Received inbound request failure notification; the remote exception could not be read: %s", e);
SpiUtils.safeHandleException(replyHandler, new RemoteExecutionException("Remote request failed (and an ClassNotFoundException occurred when attempting to unmarshal the cause)"));
log.trace(e, "Class not found in exception reply to request ID %d", Integer.valueOf(requestId));
break;
} catch (ClassCastException e) {
+ log.trace("Received inbound request failure notification; the remote exception could not be read: %s", e);
SpiUtils.safeHandleException(replyHandler, new RemoteExecutionException("Remote request failed (and an ClassCastException occurred when attempting to unmarshal the cause)"));
log.trace(e, "Class cast exception in exception reply to request ID %d", Integer.valueOf(requestId));
break;
@@ -237,7 +246,7 @@
IoUtils.safeClose(unmarshaller);
}
} catch (IOException ex) {
- log.trace("Failed to unmarshal an exception reply (%s), sending a generic execution exception");
+ log.trace("Received inbound request failure notification; the remote exception could not be read: %s", ex);
SpiUtils.safeHandleException(replyHandler, new RemoteExecutionException("Remote request failed (and an unexpected I/O error occurred when attempting to read the cause)"));
break;
}
@@ -251,6 +260,7 @@
log.warn("Got client close message for unknown client %d", Integer.valueOf(clientId));
break;
}
+ log.trace("Received inbound client close for %s", handle);
IoUtils.safeClose(handle);
break;
}
@@ -278,6 +288,7 @@
case SERVICE_OPEN_REQUEST: {
final int serviceId = buffer.getInt();
final QualifiedName qualifiedName = MultiplexConnection.getQualifiedName(buffer);
+ log.trace("Received a service open request for service %d on path \"%s\"", Integer.valueOf(serviceId), qualifiedName);
final Handle<RequestHandlerSource> service = connection.getService(qualifiedName);
if (service == null) {
ByteBuffer replyBuffer = ByteBuffer.allocate(5);
@@ -285,6 +296,7 @@
replyBuffer.putInt(serviceId);
replyBuffer.flip();
try {
+ log.trace("Sending a service-open-not-found message for request for service %d on path \"%s\"", Integer.valueOf(serviceId), qualifiedName);
connection.doBlockingWrite(replyBuffer);
} catch (IOException e) {
log.error(e, "Failed to send an error reply to an invalid service open request");
@@ -301,6 +313,7 @@
replyBuffer.putInt(serviceId);
replyBuffer.flip();
try {
+ log.trace("Sending a service-open-failed message for request for service %d on path \"%s\"", Integer.valueOf(serviceId), qualifiedName);
connection.doBlockingWrite(replyBuffer);
} catch (IOException e2) {
log.trace(e, "Failed to send an exception reply to a service open request");
@@ -313,6 +326,7 @@
replyBuffer.putInt(serviceId);
replyBuffer.flip();
try {
+ log.trace("Sending a service open reply message for request for service %d on path \"%s\"", Integer.valueOf(serviceId), qualifiedName);
connection.doBlockingWrite(replyBuffer);
} catch (IOException e) {
log.trace(e, "Failed to send a reply to a service open request");
@@ -323,6 +337,7 @@
case SERVICE_OPEN_NOT_FOUND:
case SERVICE_OPEN_FORBIDDEN: {
final int serviceId = buffer.getInt();
+ log.trace("Received a service open failure (%s) message for service %d", msgType, Integer.valueOf(serviceId));
final FutureRemoteRequestHandlerSource future = connection.removeFutureRemoteService(serviceId);
if (future == null) {
log.trace("Service open failure reply received for unknown service ID %d", Integer.valueOf(serviceId));
@@ -342,6 +357,7 @@
log.trace("Service open reply received for unknown service ID %d", Integer.valueOf(serviceId));
break;
}
+ log.trace("Received a service open reply message for service %d for %s", Integer.valueOf(serviceId), future);
final MultiplexRequestHandlerSource requestHandlerSource = new MultiplexRequestHandlerSource(serviceId, connection);
future.setResult(requestHandlerSource);
break;
@@ -349,6 +365,7 @@
case SERVICE_CLOSE_NOTIFY: {
final int serviceId = buffer.getInt();
final FutureRemoteRequestHandlerSource future = connection.removeFutureRemoteService(serviceId);
+ log.trace("Received a service close notify message for service %d for %s", Integer.valueOf(serviceId), future);
future.addNotifier(new IoFuture.HandlingNotifier<RequestHandlerSource>() {
public void handleDone(final RequestHandlerSource result) {
IoUtils.safeClose(result);
Modified: remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexReplyHandler.java
===================================================================
--- remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexReplyHandler.java 2008-11-15 02:11:16 UTC (rev 4696)
+++ remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexReplyHandler.java 2008-11-18 18:52:09 UTC (rev 4697)
@@ -24,6 +24,7 @@
import org.jboss.remoting.spi.ReplyHandler;
import org.jboss.xnio.IoUtils;
+import org.jboss.xnio.log.Logger;
import org.jboss.marshalling.Marshaller;
import org.jboss.marshalling.ByteOutput;
import java.nio.ByteBuffer;
@@ -35,6 +36,7 @@
*
*/
final class MultiplexReplyHandler implements ReplyHandler {
+ private static final Logger log = Logger.getLogger("org.jboss.remoting.multiplex.reply-handler");
private final int requestId;
private final MultiplexConnection connection;
@@ -45,6 +47,7 @@
}
public void handleReply(final Object reply) throws IOException {
+ log.trace("Sending outbound reply (request id = %d) (type is %s)", Integer.valueOf(requestId), reply == null ? "null" : reply.getClass());
final MultiplexConnection connection = this.connection;
final Marshaller marshaller = connection.getMarshallerFactory().createMarshaller(connection.getMarshallingConfiguration());
try {
@@ -58,6 +61,7 @@
marshaller.close();
output.close();
connection.doBlockingWrite(bufferList);
+ log.trace("Sent reply %s", reply);
} finally {
IoUtils.safeClose(output);
}
@@ -95,4 +99,8 @@
buffer.flip();
connection.doBlockingWrite(buffer);
}
+
+ public String toString() {
+ return "forwarding reply handler <" + Integer.toString(hashCode(), 16) + "> (request id = " + requestId + ") for " + connection;
+ }
}
Modified: remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexRequestHandler.java
===================================================================
--- remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexRequestHandler.java 2008-11-15 02:11:16 UTC (rev 4696)
+++ remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexRequestHandler.java 2008-11-18 18:52:09 UTC (rev 4697)
@@ -66,7 +66,7 @@
}
public RemoteRequestContext receiveRequest(final Object request, final ReplyHandler handler) {
- log.trace("Sending outbound request of type %s", request == null ? "null" : request.getClass());
+ log.trace("Sending outbound request (request id = %d) (type is %s)", request == null ? "null" : request.getClass());
final List<ByteBuffer> bufferList;
final MultiplexConnection connection = this.connection;
try {
@@ -85,7 +85,6 @@
marshaller.close();
output.close();
connection.doBlockingWrite(bufferList);
- log.trace("Sent request %s", request);
return new RemoteRequestContextImpl(id, connection);
} finally {
IoUtils.safeClose(output);
@@ -101,7 +100,7 @@
}
public String toString() {
- return "forwarding request handler <" + Integer.toString(hashCode(), 16) + "> (id = " + identifier + ")";
+ return "forwarding request handler <" + Integer.toString(hashCode(), 16) + "> (id = " + identifier + ") for " + connection;
}
}
@@ -120,6 +119,7 @@
public void cancel() {
if (! cancelSent.getAndSet(true)) try {
+ log.trace("Sending cancel request from %s", this);
final ByteBuffer buffer = ByteBuffer.allocate(5);
buffer.put((byte) MessageType.CANCEL_REQUEST.getId());
buffer.putInt(id);
@@ -131,6 +131,6 @@
}
public String toString() {
- return "remote request context (multiplex) <" + Integer.toString(hashCode(), 16) + "> (id = " + id + ")";
+ return "remote request context <" + Integer.toString(hashCode(), 16) + "> (request id = " + id + ") for " + connection;
}
}
Modified: remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexRequestHandlerSource.java
===================================================================
--- remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexRequestHandlerSource.java 2008-11-15 02:11:16 UTC (rev 4696)
+++ remoting3/trunk/protocol/multiplex/src/main/java/org/jboss/remoting/protocol/multiplex/MultiplexRequestHandlerSource.java 2008-11-18 18:52:09 UTC (rev 4697)
@@ -57,6 +57,7 @@
}
public Handle<RequestHandler> createRequestHandler() throws IOException {
+ log.trace("Creating new request handler from %s", this);
final int id = connection.nextRemoteClient();
final RequestHandler requestHandler = new MultiplexRequestHandler(id, connection);
boolean ok = false;
@@ -70,6 +71,7 @@
buffer.flip();
connection.doBlockingWrite(buffer);
final Handle<RequestHandler> handlerHandle = new MultiplexRequestHandler(id, connection).getHandle();
+ log.trace("Created new request handler with a handle of %s", handlerHandle);
ok = true;
return handlerHandle;
} finally {
@@ -85,6 +87,6 @@
}
public String toString() {
- return "forwarding request handler source <" + Integer.toString(hashCode(), 16) + "> (id = " + identifier + ")";
+ return "forwarding request handler source <" + Integer.toString(hashCode(), 16) + "> (id = " + identifier + ") for " + connection;
}
}
16 years, 4 months
JBoss Remoting SVN: r4696 - remoting3/trunk/api/src/main/java/org/jboss/remoting/spi.
by jboss-remoting-commits@lists.jboss.org
Author: david.lloyd(a)jboss.com
Date: 2008-11-14 21:11:16 -0500 (Fri, 14 Nov 2008)
New Revision: 4696
Modified:
remoting3/trunk/api/src/main/java/org/jboss/remoting/spi/QualifiedName.java
Log:
Javadoc
Modified: remoting3/trunk/api/src/main/java/org/jboss/remoting/spi/QualifiedName.java
===================================================================
--- remoting3/trunk/api/src/main/java/org/jboss/remoting/spi/QualifiedName.java 2008-11-15 01:52:25 UTC (rev 4695)
+++ remoting3/trunk/api/src/main/java/org/jboss/remoting/spi/QualifiedName.java 2008-11-15 02:11:16 UTC (rev 4696)
@@ -32,24 +32,49 @@
import java.io.UnsupportedEncodingException;
/**
- *
+ * A qualified name for service registration. A qualified name is a path-like structure comprised of a series of
+ * zero or more name segments. The string representation of a qualified name is a sequence of a forward slash
+ * ({@code /}) followed by a non-empty URL-encoded name segment.
*/
public final class QualifiedName implements Comparable<QualifiedName>, Iterable<String> {
+
+ /**
+ * The root name.
+ */
+ public static final QualifiedName ROOT_NAME = new QualifiedName(new String[0]);
+
private final String[] segments;
- private static final QualifiedName ROOT_NAME = new QualifiedName(new String[0]);
- public QualifiedName(final String[] segments) {
- if (segments == null) {
+ /**
+ * Create a new qualified name from the given name segments.
+ *
+ * @param nameSegments the name segments
+ * @throws NullPointerException if {@code nameSegments} is {@code null} or if any element of that array is {@code null}
+ * @throws IllegalArgumentException if an element of {@code nameSegments} is an empty string
+ */
+ public QualifiedName(final String[] nameSegments) throws NullPointerException, IllegalArgumentException {
+ if (nameSegments == null) {
throw new NullPointerException("segments is null");
}
+ String[] segments = nameSegments.clone();
for (String s : segments) {
if (s == null) {
- throw new NullPointerException("a segment is null");
+ throw new NullPointerException("Null segment");
}
+ if (s.length() == 0) {
+ throw new IllegalArgumentException("Empty segment");
+ }
}
this.segments = segments;
}
+ /**
+ * Compare this qualified name to another for equality. Returns {@code true} if both names have the same number of segments
+ * with the same content.
+ *
+ * @param o the object to compare to
+ * @return {@code true} if the given object is a qualified name which is equal to this name
+ */
public boolean equals(final Object o) {
if (this == o) return true;
if (! (o instanceof QualifiedName)) return false;
@@ -58,10 +83,25 @@
return true;
}
+ /**
+ * Get the hash code of this qualified name. Equal to the return value of {@link Arrays#hashCode(Object[]) Arrays.hashCode(segments)}
+ * where {@code segments} is the array of decoded segment strings.
+ *
+ * @return the hash code
+ */
public int hashCode() {
return Arrays.hashCode(segments);
}
+ /**
+ * Compare this qualified name to another. Each segment is compared in turn; if they are equal then the comparison
+ * carries on to the next segment. If all leading segments are equal but one qualified name has more segments,
+ * then the longer name is said to come after the shorter name.
+ *
+ * @param o the other name
+ * @return {@code 0} if the elements are equal, {@code -1} if this name comes before the given name, or {@code 1} if
+ * this name comes after the given name
+ */
public int compareTo(final QualifiedName o) {
if (this == o) return 0;
String[] a = segments;
@@ -83,6 +123,12 @@
}
}
+ /**
+ * Get the string representation of this qualified name. The root name is "{@code /}"; all other names are comprised
+ * of one or more consecutive character sequences of a forward slash followed by one or more URL-encoded characters.
+ *
+ * @return the string representation of this name
+ */
public String toString() {
StringBuilder builder = new StringBuilder();
if (segments.length == 0) {
@@ -99,6 +145,14 @@
return builder.toString();
}
+ /**
+ * Parse a qualified name. A qualified name must consist of either a single forward slash ("{@code /}") or else
+ * a series of path components, each comprised of a single forward slash followed by a URL-encoded series of non-forward-slash
+ * characters.
+ *
+ * @param path the path
+ * @return the qualified name
+ */
public static QualifiedName parse(String path) {
List<String> decoded = new ArrayList<String>();
final int len = path.length();
@@ -130,6 +184,11 @@
return new QualifiedName(decoded.toArray(new String[decoded.size()]));
}
+ /**
+ * Get an iterator over the sequence of strings.
+ *
+ * @return an iterator
+ */
public Iterator<String> iterator() {
return new Iterator<String>() {
int i;
@@ -152,6 +211,11 @@
};
}
+ /**
+ * Get the number of segments in this name.
+ *
+ * @return the number of segments
+ */
public int length() {
return segments.length;
}
16 years, 4 months
JBoss Remoting SVN: r4695 - remoting3/trunk/api/src/main/java/org/jboss/remoting/spi.
by jboss-remoting-commits@lists.jboss.org
Author: david.lloyd(a)jboss.com
Date: 2008-11-14 20:52:25 -0500 (Fri, 14 Nov 2008)
New Revision: 4695
Modified:
remoting3/trunk/api/src/main/java/org/jboss/remoting/spi/NamedServiceRegistry.java
Log:
Logger should be private
Modified: remoting3/trunk/api/src/main/java/org/jboss/remoting/spi/NamedServiceRegistry.java
===================================================================
--- remoting3/trunk/api/src/main/java/org/jboss/remoting/spi/NamedServiceRegistry.java 2008-11-15 01:50:12 UTC (rev 4694)
+++ remoting3/trunk/api/src/main/java/org/jboss/remoting/spi/NamedServiceRegistry.java 2008-11-15 01:52:25 UTC (rev 4695)
@@ -38,7 +38,7 @@
* source instance; this handle is owned by the registry, so closing the handle will remove the entry.
*/
public final class NamedServiceRegistry {
- public static final Logger log = Logger.getLogger("org.jboss.remoting.named-registry");
+ private static final Logger log = Logger.getLogger("org.jboss.remoting.named-registry");
private final ConcurrentMap<QualifiedName, Handle<RequestHandlerSource>> map = new ConcurrentHashMap<QualifiedName, Handle<RequestHandlerSource>>();
16 years, 4 months