jcsp-1.1-rc4.orig/ 0000755 0000000 0000000 00000000000 11410045055 010620 5 ustar jcsp-1.1-rc4.orig/overview.html 0000644 0000000 0000000 00000022771 11113671251 013370 0 ustar
This document is the specification for the JCSP core API.JCSP provides a complete library for building complex functionality through layered networks of communicating processes. It conforms to the CSP model of cummunicating systems so that twenty years of theory, tools and practical experience can be brought to bear in the support of Java multi-threaded applications. Newcomers to JCSP should start with the documentation on the {@link org.jcsp.lang.CSProcess CSProcess} interface, which outlines and motivates the notion of components as communicating processes and the process oriented design pattern.
Processes interact solely via CSP synchronising primitives, such as {@link org.jcsp.lang.Channel channels} ({@link org.jcsp.lang.One2OneChannel one-to-one}, {@link org.jcsp.lang.Any2OneChannel any-to-one}, {@link org.jcsp.lang.One2AnyChannel one-to-any}, {@link org.jcsp.lang.Any2AnyChannel any-to-any}), {@link org.jcsp.lang.One2OneCallChannel CALL channels}, {@link org.jcsp.lang.CSTimer timers}, {@link org.jcsp.lang.Crew crews}, {@link org.jcsp.lang.Barrier barriers}, {@link org.jcsp.lang.AltingBarrier alting barriers}, {@link org.jcsp.lang.Bucket buckets} or other well-defined modes of access to shared passive objects. Processes do not invoke each other's methods. Processes may be combined to run in {@link org.jcsp.lang.Sequence sequence} or {@link org.jcsp.lang.Parallel parallel}. Processes may be combined to wait passively on a number of {@link org.jcsp.lang.Alternative alternative} events, with one of them trigered into action only by the external generation of that event. Such collections of events may be serviced either {@link org.jcsp.lang.Alternative#fairSelect() fairly} (guaranteeing no starvation of one event by the repeated arrival of its siblings), by any user-defined {@link org.jcsp.lang.Alternative#priSelect() priority} or in an {@link org.jcsp.lang.Alternative#select() arbitrary} manner.
JCSP is an alternative to the built-in monitor model for Java threads. JCSP primitives should not normally be mixed into designs with synchronized method declarations, instances of the java.lang.Runnable interface or java.lang.Thread class, or invocations of the wait/notify/notifyAll methods from java.lang.Object.
However, JCSP is compatible with the built-in model and, with care, can be mixed safely and profitably. In particular, process communication via wait-free synchronized method invocations on a shared passive object directly implements a common CSP server idiom (see {@link org.jcsp.awt.DisplayList DisplayList} for an example). Further, existing libraries that interact with user software via listener registration and callback (such as the standard AWT and Swing) can be easily tailored to operate as processes with channel-based interfaces (for example, see {@link org.jcsp.awt org.jcsp.awt}).
Finally, we note that the JCSP library reflects the occam-pi realisation of CSP and pi-calculus., An occam-pi PROC declaration maps simply into a class implementing {@link org.jcsp.lang.CSProcess CSProcess}, whose constructor parameters mirror the PROC parameters and whose run method mirrors the PROC body.
This is the original exposition of CSP. Presentation is largely from the programmer's point of view. The Ada tasking model and the occam/transputer process model were derived from this work.`Communicating Sequential Processes', C.A.R. Hoare, Prentice Hall, 1985.
This is `the book'. Presentation is more abstract (i.e. mathematical) and a more general theory is given than in the original CACM paper. One crucial difference is that events (and channels) become concepts that are separate from the processes that engage in them. This difference was adopted in the occam/transputer model, but Ada missed out on it. The JCSP library follows the model presented in this book.`The Theory and Practice of Concurrency', A.W. Roscoe, Prentice Hall, ISBN 0-13-674409-5, 1997.
This brings CSP up to date with refinements developed over the past decade. It is `the new book'.`Communicating Sequential Processes and Deadlock' J.M.R.Martin, Chapter 1 from his Ph.D thesis ("The Design and Construction of Deadlock-Free Concurrent Systems"), University of Buckingham, UK, 1996.
This gives a crisp, amusing and accurate tour around all the CSP concepts, strongly recommended for beginners and experienced CSP users alike. [Actually only up to (and including) page 11 are for normal mortals - after that it starts to get scary. But those first few pages are a gem.]`A Classical Mind - Essays in Honour of C.A.R. Hoare', Edited by A.W. Roscoe, Prentice Hall, ISBN 0-13-294844-3, 1994.
Serious bedtime reading.`Parallel Processing with Communicating Process Architecture', I.R.East, UCL press, ISBN 1-85728-239-6, 1995.
This is an excellent text on how to design and program with the CSP model - many higher level design issues are addressed.`occam 2 -- including occam 2.1', John Galletly, UCL press, ISBN 1-85728-362-7, 1996.
This is a good textbook on the occam version of the CSP model. A knowledge of occam gives insight that makes multithreading in Java simpler and, hence, safer to manage ;-) ...`Parallel and Distributed Computing in Education', P.H.Welch, in Proceedings of VecPar'98, Lecture Notes in Computer Science #1573, Springer-Verlag, April 1999.
This is a tutorial introduction to CSP from the point of view of the programmer/designer. JCSP bindings to key examples are given in an appendix. See Abstract.`Java Threads in the Light of occam/CSP', P.H.Welch, in Architectures, Languages and Patterns for Parallel and Distributed Applications, Proceedings of WoTUG-21, pp. 259-284, IOS Press (Amsterdam), ISBN 90 5199 391 9, April 1998.
This is a tutorial introduction to the Java monitor model. It raises concern over its ease of use and the safety of its standard design patterns, but shows how it may be used to build the CSP primitives. Finally, it revisits those concerns and shows how they fade in the light of CSP. See Abstract.
jcsp-1.1-rc4.orig/README.txt 0000644 0000000 0000000 00000045213 11113671251 012326 0 ustar
=============================================================================
CSP for Java : JCSP 1.1 Release Candidate 1 (rc4)
=============================================================================
This file contains:
o the manifest list of files/directories in this release;
o installation notes;
o incremental change list since JCSP 0.5.
Please read the GNU-LGPL-2.1.txt file. Retention of these files is
assumed to imply acceptance of the terms in that license.
This release is licenced under the Lesser GNU Public Licence, version 2.1
(LGPL 2.1). A copy is included with the distribution, or you can read an online
version at:
http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
There are rather a lot of deprecated items now in the library. Most of
these will be removed in JCSP 1.2. This vew version will contain
a completely re-written networking support (org.jcsp.lang.channel).
Peter Welch and Neil Brown.
(28th. November, 2008)
=============================================================================
JCSP 1.1 (rc4) Manifest
=============================================================================
jcsp.jar (class library containing all features, both net
and core - add either this, or jcsp-core.jar,
to your CLASSPATH)
jcsp-core.jar (class library containing just the core features
- add either this or jcsp.jar to your CLASSPATH)
Note: jcsp-core excludes the networking mechanisms (and some other things)
contained within jcsp.jar. It is a smaller library for applications running
in a single JVM. It efficiently exploits multicore processors.
jcsp-demos/ (directory with sources for lots of demos)
jcsp-demos-util.jar (addtional class library - needed for the demos)
jcsp-doc/ (javadoc HTML tree for jcsp.jar)
jcsp-core-doc/ (javadoc HTML tree for jcsp-core.jar)
Note: the jcsp-core-doc folder is included so that jcsp-core users are not
overloaded with materials they do not use. For either of the above trees,
point your browser at the index.html file at their top level.
GNU-LGPL-2.1 (open source licence agreement)
README-JCSP-1.1-rc4.txt (this file)
L-GPL open sources are available from the subversion repository:
svn checkout http://projects.cs.kent.ac.uk/projects/jcsp/svn/jcsp/tags/jcsp-1.1-rc4/
You will need the JDK1.3 libraries (or any later JDK) installed to work
with the JCSP library.
=============================================================================
Installation Notes
=============================================================================
Put the file jcsp.jar (or jcsp-core.jar) in your CLASSPATH.
You do *not* need to unpack these files.
Point your web browser at (and, maybe, bookmark):
jcsp-doc/index.html or jcsp-core-doc/index.html
for the documentation to the JCSP library.
The jcsp-demos directory contains many JCSP demonstration applications
and applets. These are not embedded in any Java packages. Each demo
is contained in a single sub-directory. To run one, change to that
directory, compile (javac *java) and run the main program (which
usually has the word "Main" as part of its name).
=============================================================================
Change List
=============================================================================
Changes since JCSP 1.1 (rc3) release
------------------------------------
At last, the documentation has been changed to conform to the API changes
introduced in version 1.1. Many minor bugs fixed. Some new demos added.
The documentation of org.jcsp.lang.Channel (from which all channels should
be made) and org.jcsp.lang.Poisonable (for simplifying network shut-down)
has been finished.
There are rather a lot of deprecated items now in the library. Most of
these will be removed in JCSP 1.2. This vew version will contain
a completely re-written networking support (org.jcsp.lang.channel).
Peter Welch and Neil Brown.
(28th. November, 2008)
Changes since JCSP 1.1 (rc2) release
------------------------------------
Deprecated the remaining old methods of channel creation and fixed some
public visibility mistakes.
Neil Brown and Peter Welch.
(3rd. March, 2008).
Changes since JCSP 1.1 (rc1) release
------------------------------------
Deprecated some of the channel factories, and updated the overview of the
documentation and this README file.
Neil Brown and Peter Welch.
(9th. October, 2007).
Changes since JCSP 1.0 (rc8) release
------------------------------------
The library has been merged with the old Quickstone version, which includes
a great many changes. The channels are now interfaces with hidden
implementations, and must be created using methods in the Channel class.
The networking aspects from Quickstone's JCSP.NET have been included.
Poisonable channels are now included. Many Quickstone classes have been
removed (from JCSP.NET; JCSP core users will not notice any difference) or
deprecated ready for future removal. Symmetric Object channels have been
added.
Neil Brown and Peter Welch.
(5th. October, 2007).
Changes since JCSP 1.0 (rc7) release
------------------------------------
Symmetric channels (One2OneChannelSymmetricInt) added, with demo added to
CommsTime (to run with symmetric channels) and a new output-guards demo
folder.
Peter Welch.
(16th. August, 2007)
Changes since JCSP 1.0 (rc6) release
------------------------------------
One correction to AltingBarrier. Lots more documentation and examples for
AltingBarrier. Minor documentation improvements elsewhere.
Some Framed* classes added to jcsp.plugNplay. These wrap some jcsp.awt
Active* widgets (buttoms and scrollbars) in frames for immediate use.
They are useful for quick demonstrations (and used in the documentation
of AltingBarrier).
The Parallel class has a new contructor taking a 2D-array of processes.
Spurious wakeup protection/logging has been added to the Bucket and Stop
classes. These has been overlooked when preparing the rc6 version.
Peter Welch.
(19th. December, 2006)
Changes since JCSP 1.0 (rc5) release
------------------------------------
The introduction of an (experimental) AltingBarrier class. This is a Guard
useable for Alternative selections. It implements multiway synchronisation
(i.e. a CSP 'event'), allowing all parties to back off choice operations.
One party to the AltingBarrier will select it if and only if *all* parties
select it. Prioritised choice is not allowed if the choice includes an
AltingBarrier, since conflicting priorities would be easy to set up and
impossible to resolve. Fair choice is allowed, but only on the understanding
that a completed AltingBarrier takes precedence over other typse of Guard
(because of the necessity for all parties to the choice making the same one).
The Alternative class has had to be modified to support AltingBarriers. This
should have negligeable overhead on its operation without AltingBarriers.
An AlternativeError class has been added, which is thrown in the attempt to
make a prioritised choice over a set of Guards including an AltingBarrier.
A JCSP_InternalError class has been added. This is thrown if an internal
inconsistency is detected. Currently, this is used for defensive programming
only of the AltingBarrier (which, we stress, is experimental).
Spurious wakeup protection has been added to all blocking methods (channel
communications, barrier synchronisation, alting, etc.). These are implemented
with invocations of "Object.wait()". The Java specification has always
included a footnote that those calls may "spuriously" return for no proper
reason (where "proper" means being released through an "Object.notify()",
"Object.notifyAll()", an "InterruptedException" or a timeout)! There was
no mention of this danger in the (javadoc) documentation in JDK 1.3 and
earlier versions. The danger is heavily emphasised in the documentation
for JDK 1.5, so we thought we should take it seriously.
Spurious wakeup protection requires a few extra fields in some of the classes
and extra work (and ugly code) at run-time -- but these overheads are pretty
slight. Optional logging of detected spurious wakeups is provided (see the
"SpuriousLog"). Running stress tests on Sun's JVMs, with logging switched
on, has *never* shown any!
It has long been known that "early" timeouts (from "Object.wait(long)") occur
and JCSP has always allowed them. The above logging mechanism also reports
counts of these -- and they occur frequently. The acceptable margin for
"early" timeouts may be set by "SpuriousLog.setEarlyTimeout(long)"; by default,
that margin is set to 9 milliseconds (which covers most of those encountered
using Sun's JVMs). Timeouts returning earlier than the acceptable margin are
treated as spurious wakeups and the timeout is reset. A margin of zero may be
defined, but that would lead to many re-timeouts that are not really needed
-- note that JCSP running on standard JVMs should not be used for critical
("hard") real-time applications.
Peter Welch.
(6th. January, 2006) and (19th. December, 2006)
Changes since JCSP 1.0 (rc4) release
------------------------------------
First, many apologies for the long interval sine the last release. We are very
positive about this work, but have been concentrating our time on developing
the occam-pi language and supporting infrastructure. occam-pi and JCSP are
closely related - common goals, differing technologies. Anyone interested in
finding more about occam-pi, please check out:
http://www.cs.kent.ac.uk/projects/ofa/kroc/ (motivation and download)
http://frmb.org/occ21-extensions.html (summary of extensions over
occam2.1)
http://rmox.net/prelude/ (experimental OS)
Back to JCSP! This release is mostly just maintenance over rc4, with several
sets of classes re-implemented for better efficiency and security (i.e. no
semantic change).
Some changes have been made though:
o several more items have been deprecated:
interfaces: jcsp.lang.Channel, jcsp.lang.ChannelInt.
Note: these are just the union of their separate input/output classes:
jcsp.lang.Channel = jcsp.lang.ChannelInput union
jcsp.lang.ChannelOutput
jcsp.lang.ChannelInt = jcsp.lang.ChannelInputInt union
jcsp.lang.ChannelOutputInt
They are never needed! Such interfaces are used for the parameters
of CSProcess class constructors and should only hold one end (either
input ot output, but not both!) of the channel plugged in to any given
instance. Any other use is misconceived.
We are afraid that some pieces of JCSP documentation incorrectly used
these interfaces. This have been corrected in this release.
abstract classes: jcsp.lang.AltingChannel, jcsp.lang.AltingChannelInt.
Note: these are deprecated for exactly the same reasons as above. Use
AltingChannelInput, respectively AltingChannelInputInt, instead for input
channels that need to support ALTing - or ChannelOutput, respectively
ChannelOutputInt, for output channels.
General note about the above deprecated items: THEY WILL BE REMOVED from the
final 1.0 release! That will be a merger with the full JCSP Network Edition i
from Quickstone (http://www.quickstone.com/xcsp/jcspnetworkedition/). This has
a cleaner (more systematic) way for creating the wide variety of channels
supported and we want the name "Channel" as the right name for the class of
static `factory' methods.
Other changes:
o a bunch of deprecated items have now been removed:
methods: jcsp.lang.Alternative.select (AltingChannelInput[], ...) etc..
Note: Alternative classes *must* now be constructed bound to their Guard
arrays - so there is no need to suppy those to their select methods.
constructors: jcsp.lang.Alternative ().
Note: use jcsp.lang.Alternative (Guard[] guard) instead - see above.
constructors: jcsp.lang.Any2AnyChannel(ChannelDataStore) etc..
Note: all deprecated channel constructors taking ChannelDataStore or
ChannelDataStoreInt have been removed. Use the static create methods
instead. This removal was needed for technical reasons for improving
the efiiciency of default channels (i.e. those without ChannelDataStore
buffers). As mentioned in the "General note" above, all channel
creation in future releases will be via the Channel static create
methods.
o a bug fix:
class: jcsp.lang.Stop.
Note: this simple class was included for completeness - it is one of
the primitives of CSP. It never occurred to us that anyone would need
to use it and it was never tested! But someone did use it. It carried
a very stupid bug - now exterminated.
Peter Welch
(5th. September, 2005)
Changes since JCSP 1.0 (rc3) release
------------------------------------
o Minor corrections and changes to a (very) few of the documentation files.
o A new demo - MultiPong :-)
o A modified demo - Infection. This has more controls and interaction. See
how hard it is fighting (say) Foot-and-Mouth by culling neighbouring animals
when the effectiveness of the cull is only 99% ...
Peter Welch.
(13th. July, 2001)
Changes since JCSP 1.0 (rc2) release
------------------------------------
o Fixed bug in jcsp.util.Buffer and jcsp.util.ints.BufferInt. When we tried
to create a buffered channel of size n, we used to get one of size (n+1).
The channel buffer is now created correctly with the requested size.
o Fixed bug in jcsp.awt.GraphicsCommand.DrawArc and jcsp.awt.GraphicsCommand.FillArc.
A typing error had omitted startAngle and arcAngle from the constructor's
parameter list. It compiled OK under JDK1.2 (but couldn't work correctly).
The JDK1.3 compiler was more thorough and, quite properly, rejected it.
All is well now.
o Several additions to the documentation. In particular, the top-level javadoc
page points new users to the documentation in the jcsp.lang.CSProcess interface
- where there is an overview of (Communicating Sequential) Process Oriented Design
and the implementation pattern for a JCSP process.
o Modified Binary Code License (that explicitly allows redistribution of JCSP
classes as part of users' applications/applets).
Peter Welch.
(7th. February, 2001)
Changes since JCSP 1.0 (rc1) release
------------------------------------
o Change of name of the "Timer" class in jcsp.lang to "CSTimer".
This has been caused by the JDK1.3 release from Sun introducing their own
classes called "Timer" in packages java.util and javax.swing. Without this
name change, applications importing both jcsp.lang.* and java.util.* (or
javax.swing*) would have to qualify declarations and constructions of
"Timer" variables and objects - e.g:
jcsp.lang.Timer tim = new jcsp.lang.Timer ();
With this name change, even if both jcsp.lang.* and java.util.* are imported,
we may declare JCSP timers without qualification - e.g:
CSTimer tim = new CSTimer tim ();
Note that the JDK1.3 java.util.Timer is a very different class from CSTimer.
Warning: the old jcsp.lang.Timer has been deleted from this release - not
deprecated. If it had just been deprecated, importing java.util.*
would still require full qualification for references to its Timers.
This means existing JCSP applications using JCSP timers will have
to change all occurrences of "Timer" to "CSTimer" - many apologies.
Aside: avoidance of a name clash was the reason why JCSP has the "CSProcess"
interface, rather than just "Process". There has always been a "Process"
class defined in java.lang (again with a very different purpose from ours).
o Some improvements to various items in the documentation.
o Re-packaging of the release as a single JAR file.
o A new applet/application demo - Fireworks!
Peter Welch.
(11th. August, 2000)
Changes since JCSP 0.95 release
-------------------------------
o Change of name of the "Many2..." and "...2Many" channel classes. These
have been changed to "Any2..." and "...2Any" channels. The "Any" names
better reflect the semantics of these channels. ["Many" implied some kind
of broadcast - which is not what these channels do.]
This has been an outstanding request for some time. The old class names
have not simply been deprecated - they have been deleted! The jcsp.lang
section of the library would have become embarassingly top heavy with
deprecated classes if they had been retained. Apologies to those who
may need to make a lot of edits. I have a simple Unix cshell script that
will make these edits to all .java files in, or below, a named directory.
Please mail me (P.H.Welch@ukc.ac.uk) if you need it!
o The bucket synchronisation primitive;
o Generation of a jcsp.lang.ProcessInterruptedError if any process, blocked
on a JCSP synchonisation primitive, is interrupted. This is not allowed
(and is always a panic-induced design error). The error does not need to
be caught (and, indeed, should *not* be caught) with a try-catch clutter
surrounding the JCSP synchonisation.
o Minor tweaks to the documentation (as ever).
Peter Welch.
(3rd. November, 1999)
Changes since JCSP 0.94 release
-------------------------------
o Links to Sun's JDK1.2 documentation (from the JCSP documentation)
are now in place;
o Minor tightening up of the ChannelAccept interface (for CALL channels)
to enable the compiler to trap erroneous accepts - no effect on correct
programs;
o Minor tweaks to the documentation.
Peter Welch.
(28th. October, 1999)
Changes since JCSP 0.5 release
------------------------------
o A more flexible API for ALTing;
o Numerous new facilities (and some deprecated old ones);
o More and better (javadoc)umentation - including several mini-tutorials.
JCSP documentation is now produced using the JDK 1.2 javadoc tool;
o More demonstration applications and applets;
o (occam3) CALL channels;
o Barrier and CREW synchronisation primitives;
o Various pieces of maintenance.
A source release will be made available shortly under either the GPL
or Artistic open source licences. Please contact me (P.H.Welch@ukc.ac.uk).
I *hope* to freeze this into a JCSP 1.0 release *shortly* and update
the JCSP web pages suitably - at present, these offer only JCSP 0.5.
Peter Welch.
(28th. October, 1999)
jcsp-1.1-rc4.orig/.project 0000644 0000000 0000000 00000000602 11072626250 012273 0 ustar
* Ask.setOneTokenReply (false) specifies that multiple tokens are
* allowed, but that only the first will be processed.
*
* The false allows user input to be documented with comments (in the
* second and following tokens) explaining the meaning of the first token, which
* contains the actual data. This is useful when preparing user input as a file,
* from which the standard input stream will later be redirected, so that
* each line of input can be documented.
*
* @param b if true, the response must consist of a single token
* - otherwise, multiple tokens are allowed but only the first will be processed.
*/
public static void setOneTokenReply (boolean b) {
oneTokenReply = b;
}
/**
* Ask.getOneTokenReply returns whether multiple response tokens
* will be rejected.
*
* @return whether multiple response tokens will be rejected.
*/
public static boolean getOneTokenReply () {
return oneTokenReply;
}
}
jcsp-1.1-rc4.orig/src/org/jcsp/net/ 0000755 0000000 0000000 00000000000 11410045050 013716 5 ustar jcsp-1.1-rc4.orig/src/org/jcsp/net/NetChannelEndFactory.java 0000644 0000000 0000000 00000006115 11105701167 020573 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net;
/**
*
* This interface defines methods for constructing Networked
* channel ends.
*
* Constructs a
* Constructs a
* Constructs a
* Constructs a
* An interface that should be implemented by classes that
* are intended to be Node level JCSP.NET services.
*
* Services should be initialized, then started and then stopped.
* NetAltingChannelInput
object.
* NetAltingChannelInput
object.
*/
public NetAltingChannelInput createNet2One();
/**
* NetSharedChannelInput
object.
* NetSharedChannelInput
object.
*/
public NetSharedChannelInput createNet2Any();
/**
* NetChannelOutput
object.
* NetChannelOutput
object.
*/
public NetChannelOutput createOne2Net(NetChannelLocation loc);
/**
* NetSharedChannelOutput
object.
* NetSharedChannelOutput
object.
*/
public NetSharedChannelOutput createAny2Net(NetChannelLocation loc);
} jcsp-1.1-rc4.orig/src/org/jcsp/net/NodeUIImpl.java 0000644 0000000 0000000 00000012012 11105701167 016533 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net;
/**
* This is a default implementation for NodeUI
that is used if no
* other implementation is supplied.
*
* @author Quickstone Technologies Limited
*/
public class NodeUIImpl extends NodeUI
{
/** Constructor which is used as standard to create a new NodeUIImpl
* object.
*/
protected NodeUIImpl()
{
time = System.currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
hashCode = new Object().hashCode();
}
/**
* A constructor which takes a String
that should be in the
* format of that returned by the getImplStringForm()
method.
*
* @param s a String
used to construct the NodeUIImpl
object.
*/
public NodeUIImpl(String s)
{
try
{
int start = 0;
int nlPos = s.indexOf('\n');
if(nlPos < 0 || nlPos == s.length() - 1)
throw new IllegalArgumentException("Invalid String");
time = Long.parseLong(s.substring(0, nlPos));
start = nlPos + 1;
nlPos = s.indexOf('\n', start);
if(nlPos < 0 || nlPos == s.length() - 1)
throw new IllegalArgumentException("Invalid String");
mem = Long.parseLong(s.substring(start, nlPos));
start = nlPos + 1;
hashCode = Integer.parseInt(s.substring(start, s.length()));
}
catch (NumberFormatException e)
{
throw new IllegalArgumentException("Invalid String");
}
}
/**
* Returns a String
object that can be used with the constructor
* that takes a String
parameter.
*
* @return a String
that holds this object in "string form".
*/
public String getImplStringForm()
{
return time+"\n"+mem+"\n"+hashCode;
}
/** Compares another NodeUI
with this NodeUIImpl
.
*
* @param other another NodeUI
to compare with this object.
* @return true
iff the NodeUI
supplied is a NodeUIImpl
object that contains
* the same internal unique identifier as this object.
*/
public final boolean checkEqual(NodeUI other)
{
if(other == null || !(other instanceof NodeUIImpl))
return false;
NodeUIImpl aOther = (NodeUIImpl) other;
return (time == aOther.time) && (mem == aOther.mem) && (hashCode == aOther.hashCode);
}
/** Returns a String
that can be used by the superclass to compare
* two NodeUI
objects.
* @return a String
that follows the rules stated for this method in the
* NodeUI
class.
*/
protected String getComparisonString()
{
return time + "" + mem + "" + hashCode;
}
/** Returns a hash code for this object.
* @return an int
hash code for this object.
*/
public final int hashCode()
{
return hashCode;
}
private long time;
private long mem;
private int hashCode;
} jcsp-1.1-rc4.orig/src/org/jcsp/net/UnacknowledgedNetChannelEndFactory.java 0000644 0000000 0000000 00000006011 11105701167 023441 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net;
/**
* Extends the standard network channel factory to give unacknowledged channel output ends. Use these with caution
* as the lack of synchronization between sender and receiver can lead to potential problems.
*
* @author Quickstone Technologies Limited
*/
public class UnacknowledgedNetChannelEndFactory extends StandardNetChannelEndFactory
{
/**
* Creates a new factory object.
*/
public UnacknowledgedNetChannelEndFactory()
{
super();
}
/**
* Creates an unacknowledged output channel end suitable for use by a single writer.
*
* @param loc address of the input channel end to connect to.
*/
public NetChannelOutput createOne2Net(NetChannelLocation loc)
{
return new One2NetChannel(loc, false);
}
/**
* Creates an unacknowledged output channel end suitable for use by multiple writers.
*
* @param loc address of the input channel end to connect to.
*/
public NetSharedChannelOutput createAny2Net(NetChannelLocation loc)
{
return new Any2NetChannel(loc, false);
}
} jcsp-1.1-rc4.orig/src/org/jcsp/net/Service.java 0000644 0000000 0000000 00000006700 11105701167 016175 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net;
/**
* true
iff the service has successfully started.
*/
public boolean start();
/** Should stop the service and then return.
* @return true
iff the service has successfully stopped.
*/
public boolean stop();
/** Initialize the service with the specified service settings.
* @param settings The settings used by the service.
* @return true
iff the service has been initialized.
*/
public boolean init(ServiceSettings settings);
/**
* Indicates whether or not a service is running.
* @return true
iff the service is currently running.
*/
public boolean isRunning();
/**
* Obtains a ServiceUserObject
from a Service.
* This allows Services to expose functionality to users that
* it does not want to be able to access admin features.
*
* @return a ServiceUserObject
.
* @throws SecurityException if the calling Thread does not have
* access to the object.
*/
public ServiceUserObject getUserObject() throws SecurityException;
} jcsp-1.1-rc4.orig/src/org/jcsp/net/tcpip/ 0000755 0000000 0000000 00000000000 11410045050 015035 5 ustar jcsp-1.1-rc4.orig/src/org/jcsp/net/tcpip/TCPIPLink.java 0000644 0000000 0000000 00000045261 11105701167 017416 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net.tcpip;
import java.net.*;
import java.io.*;
import org.jcsp.lang.*;
import org.jcsp.net.*;
/**
* Implements a link running over TCP/IP sockets. See the definition of Link
for
* full details.
*
* @see org.jcsp.net.Link
*
* @author Quickstone Technologies Limited
*/
class TCPIPLink extends Link
{
/*----------------------Constructors------------------------------------------*/
/**
* Constructor for using an existing socket.
*
* @param socket The socket to the remote computer, which must already be
* open and active. You must not have transmitted anything
* over the socket.
*/
// package-private
TCPIPLink(Socket socket)
{
this(socket, true);
}
/**
* Constructor for using an existing socket.
*
* @param socket The socket to the remote computer, which must already be
* open and active. You must not have transmitted anything
* over the socket.
*
* @param client Tells the link whether to act as a client or a server
* during the handshake process
*/
// package-private - called from LinkServer with client false
TCPIPLink(Socket socket, boolean client)
{
super(new TCPIPProtocolID(), client, true);
this.socket = socket;
}
/**
* Constructor for connecting to a remote computer. The actual connect
* happens when you run the process using start().
*
* @param remoteTCPIPAddress The remote computer to connect to.
*/
// package-private - called from LinkManager
TCPIPLink(TCPIPAddressID remoteTCPIPAddress)
{
super(new TCPIPProtocolID(), true, false);
this.remoteTCPIPAddress = remoteTCPIPAddress;
}
/*-------------Implementations of Methods from Link---------------------------*/
/**
* Run the send and receive threads to marshall and unmarshall objects.
*/
protected void runTxRxLoop()
{
Parallel par = new Parallel( new CSProcess[] {new RxLoop(), new TxLoop()});
par.run();
par.releaseAllThreads();
}
/**
* Waits for numRepliesOutstanding
instances of LinkLost
* to arrive from the txChannel
.
*
* @param numRepliesOutstanding LinkLost
instances to wait for.
*/
protected void waitForReplies(int numRepliesOutstanding)
{
ChannelInput in = txChannel.in();
while (numRepliesOutstanding > 0)
{
Object obj = in.read();
if (obj instanceof LinkLost)
numRepliesOutstanding--;
}
}
/**
* Start this Link but allow the caller to continue in parallel.
* This is the similar to "new ProcessManager(this).start()" - except
* that Link no longer implements CSProcess, so you can't do
* that.
*/
// package-private - called from LinkManager & LinkServer
protected void start(boolean newProcess)
{
ProcessManager pm = new ProcessManager(this);
pm.setPriority(ProcessManager.PRIORITY_MAX);
if(newProcess)
pm.start();
else
pm.run();
}
/**
* Connect to remote host. Should only be called for client-side
* Links which have not yet been connected. (i.e. where
* socket==null and remoteAddress != null).
*
* @return true on success, false on failure.
*/
protected boolean connect()
{
try
{
socket = new Socket(remoteTCPIPAddress.getHost(), remoteTCPIPAddress.getPort());
}
catch (SecurityException ex)
{
ex.printStackTrace();
return false; // Give up
}
catch (ConnectException ex)
{
ex.printStackTrace();
return false; // Give up
}
catch (NoRouteToHostException ex)
{
ex.printStackTrace();
return false; // Give up
}
catch (IOException ex)
{
ex.printStackTrace();
return false; // Give up
}
return true;
}
/**
* Create the object streams used to communicate with the peer system. Called internally by
* the superclass.
*
* @return true on success, false on failure
*/
protected boolean createResources()
{
// Create the object streams and do the first part of the handshaking.
Parallel par = new Parallel( new CSProcess[] {
new CreateRxStream(),
new CreateTxStream(),
});
par.run();
par.removeAllProcesses();
par.releaseAllThreads();
// check whether it worked.
if ((rxStream == null) || (txStream == null))
{
// Object Stream creation failed.
Node.err.log(this, "Object Stream creation failed.");
destroyResources();
// We've already displayed an error message (or two), so just exit
return false;
}
// Ok
return true;
}
/**
* Performs the node exchange part of the handshaking process. Creates a process to
* send this NodeID
and a process to receive the peer node ID. Called internally
* by the superclass.
*
* @return true on success, false on failure
*/
protected boolean exchangeNodeIDs()
{
// Do the second part of the handshaking.
Parallel par = new Parallel(new CSProcess[] { new RxId(), new TxId() });
par.run();
par.releaseAllThreads();
// check whether it worked.
if ((rxStream == null) || (txStream == null))
{
Node.err.log(this, "Error during handshaking (stage2)");
return false;
}
return true;
}
/**
* Writes a test object to the output stream, flushing and resetting the stream afterwards.
* Called internally by the superclass during the testing stage to determine link speed. The parameter passed
* to this method must be returned by the readTestObject
method at the peer
* node.
*
* @param obj Object to be sent
*/
protected void writeTestObject(Object obj) throws Exception
{
txStream.writeObject(obj);
txStream.flush();
txStream.reset();
}
/**
* Reads a test object from the input stream. Called internally by the superclass during the testing stage to
* determine link speed. Returns the parameter passed to writeTestObject
at the
* peer node.
*
* @return the object received.
*/
protected Object readTestObject() throws Exception
{
return rxStream.readObject();
}
/**
* Writes a boolean link decision value to the output stream. Called internally by the superclass during the
* handshaking sequence. The parameter passed to this method must be returned by the
* readLinkDecision
method at the peer node.
*
* @param use boolean decision value to send.
*/
protected void writeLinkDecision(boolean use) throws Exception
{
txStream.writeObject(use ? Boolean.TRUE : Boolean.FALSE);
txStream.flush();
}
/**
* Reads a boolean link decision from the input stream. Called internally during the
* handshaking sequence by the superclass. Returns the parameter passed to writeLinkDecision
* at the peer node.
*
* @return the boolean decision.
*/
protected boolean readLinkDecision() throws Exception
{
return ((Boolean)rxStream.readObject()).booleanValue();
}
/**
* Closes the streams and the socket, if needed. Surpresses errors.
*/
protected void destroyResources()
{
if (txStream != null)
{
try
{
txStream.close();
}
catch (Exception ignored)
{
}
txStream = null;
}
closeRx();
}
/*-------------------Private Methods------------------------------------------*/
/**
* Closes the Rx stream and the socket, if needed. Surpresses errors.
*/
private void closeRx()
{
if (rxStream != null)
{
try
{
rxStream.close();
}
catch (Exception ignored)
{
}
rxStream = null;
}
closeSocket();
}
/**
* Closes the Tx stream and the socket, if needed. Surpresses errors.
*/
private void closeTx()
{
if (txStream != null)
{
try
{
txStream.close();
}
catch (Exception ignored)
{
}
txStream = null;
}
closeSocket();
}
/**
* Closes the socket, if needed. Surpresses errors.
*/
private void closeSocket()
{
if (socket != null)
{
try
{
socket.close();
}
catch (Exception ignored)
{
}
socket = null;
}
}
/*----------------------Attributes--------------------------------------------*/
/**
* The other computer's IP address and port.
*/
private TCPIPAddressID remoteTCPIPAddress;
/**
* The actual socket.
*/
private Socket socket;
/**
* The stream for reading from the socket.
*/
private ObjectInputStream rxStream;
/**
* The stream for reading from the socket.
*/
private ObjectOutputStream txStream;
/**
* Handshaking string.
*/
private static String PROTOCOL_IDENTIFIER = "JCSP.net version 0.1";
/**
* Size of Java buffers. Note that there are also OS buffers,
* set using {@link java.net.Socket#setReceiveBufferSize(int)} and
* {@link java.net.Socket#setSendBufferSize(int)}.
*/
private static final int BUFFER_SIZE = 8192;
/*----------------------Private Inner Classes---------------------------------*/
/**
* The process which creates txStream. It creates an object stream
* associated with the socket, and sends the Java object stream header
* and the PROTOCOL_IDENTIFIER. On success, it sets txStream in the
* outer class to a non-null value. If there is an exception, it
* closes the socket and returns without modifying txStream.
*
* @see #txStream
*/
private class CreateTxStream implements CSProcess
{
/**
* The run method.
*/
public void run()
{
// This is what we close() if we catch an exception.
OutputStream rawTxStream = null;
try
{
rawTxStream = socket.getOutputStream();
socket.setTcpNoDelay(true);
rawTxStream = new BufferedOutputStream(rawTxStream,BUFFER_SIZE);
ObjectOutputStream objTxStream = new ObjectOutputStream(rawTxStream);
objTxStream.writeObject(PROTOCOL_IDENTIFIER);
objTxStream.flush();
objTxStream.reset();
txStream = objTxStream;
return;
}
catch (Exception ex)
{
ex.printStackTrace();
if (rawTxStream != null)
{
try
{
rawTxStream.close();
}
catch (Exception ignored)
{
}
}
closeSocket();
}
}
}
/**
* The process which creates rxStream. It creates an object stream
* associated with the socket, and listens for the Java object stream
* header and the PROTOCOL_IDENTIFIER. On success, it sets rxStream in
* the outer class to a non-null value. If there is an exception, or
* if the object recieved is not PROTOCOL_IDENTIFIER, it closes the
* socket and returns without modifying rxStream.
*
* @see #rxStream
*/
private class CreateRxStream implements CSProcess
{
/**
* The run method.
*/
public void run()
{
// This is what we close() if we catch an exception.
InputStream rawRxStream = null;
try
{
rawRxStream = socket.getInputStream();
rawRxStream = new BufferedInputStream(rawRxStream, BUFFER_SIZE);
ObjectInputStream objRxStream = new ObjectInputStream(rawRxStream);
if (!PROTOCOL_IDENTIFIER.equals(objRxStream.readObject()))
{
// Wrong PROTOCOL_IDENTIFIER
}
else
{
rxStream = objRxStream;
return;
}
}
catch (Exception ex)
{
}
if (rawRxStream != null)
{
try
{
rawRxStream.close();
}
catch (Exception ignored)
{
}
}
closeSocket();
}
}
/**
* The process which sends our Id. On success, it doesn't change anything.
* If there is an exception, it closes the socket, sets txStream=null, and
* returns.
*/
private class TxId implements CSProcess
{
/**
* The run method.
*/
public void run()
{
NodeID localAddress = null;
if(sendNodeID)
localAddress = Node.getInstance().getNodeID();
try
{
txStream.writeObject(localAddress);
txStream.flush();
txStream.reset();
}
catch (Exception ex)
{
ex.printStackTrace();
closeTx();
}
}
}
/**
* The process which recieves the remote Id. On success, it sets
* remoteAddress. If there is an exception, it closes the socket, sets
* rxStream=null, and returns.
*/
private class RxId implements CSProcess
{
/**
* The run method.
*/
public void run()
{
try
{
remoteNodeID = (NodeID)rxStream.readObject();
}
catch (Exception ex)
{
ex.printStackTrace();
closeRx();
}
}
}
/**
* The process which does transmission to a socket.
*/
private class TxLoop implements CSProcess
{
/**
* The run method.
*/
public void run()
{
ChannelInput in = txChannel.in();
try
{
Object obj = in.read();
while (!(obj instanceof TxLoopPoison))
{
txStream.writeObject(obj);
txStream.flush();
txStream.reset();
obj = in.read();
}
closeTx();
}
catch (Exception ex)
{
if ((ex instanceof SocketException) || (ex instanceof EOFException))
{
// Probably because the other side closed it.
}
else
{
synchronized(System.err)
{
Node.err.log(this, "Error in TX:");
ex.printStackTrace();
}
}
closeTx();
// Need to wait for RxLoop to die (which it will do because we
// just closed the socket it's trying to read from) and then
// get the TxLoopPoison it sends us. Meanwhile, black-hole
// any incoming data.
Object obj = in.read();
while (!(obj instanceof TxLoopPoison))
obj = in.read();
}
}
}
/**
* The process which recieves from a socket.
*/
private class RxLoop implements CSProcess
{
/**
* The run method.
*/
public void run()
{
try
{
// Now enter demux loop
while (true)
deliverReceivedObject(rxStream.readObject());
}
catch (Exception ex)
{
if ((ex instanceof SocketException) || (ex instanceof EOFException))
{
// Probably because the other side closed it.
}
else
{
synchronized(System.err)
{
Node.err.log(this, "Error in RX:");
Node.err.log(this, ex);
}
}
closeRx();
// Now, need to carefully close TxLoop, making sure we don't
// deadlock.
txChannel.out().write(new TxLoopPoison());
}
}
}
/**
* An object of this type is used by RxLoop to poison TxLoop.
*/
private class TxLoopPoison
{
}
} jcsp-1.1-rc4.orig/src/org/jcsp/net/tcpip/TCPIPCNSServerNT.java 0000644 0000000 0000000 00000005670 11105701167 020575 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net.tcpip;
import org.jcsp.win32.*;
/**
* Wraps up the TCPIPCNSServer as a Windows NT service. To install the service, register the
* path java org.jcsp.net.tcpip.TCPIPCNSServerNT
with the service name
* JCSP.NET:TCPIPCNSServer
.
TCPIPCNSServer.main
.
*/
protected void startService()
{
TCPIPCNSServer2.main(new String[0]);
// will block
}
/**
* Stops the service.
*/
protected void stopService()
{
TCPIPCNSServer2.terminate.out().write(null);
}
/**
* Creates a new service instance.
*/
private TCPIPCNSServerNT()
{
super("JCSP.NET:TCPIPCNSServer");
}
/**
* Creates a new service instance and sets it running.
*/
public static void main(String[] args)
{
new TCPIPCNSServerNT().run();
}
} jcsp-1.1-rc4.orig/src/org/jcsp/net/tcpip/TCPIPCNSServer2.java 0000644 0000000 0000000 00000007406 11105701167 020414 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net.tcpip;
import java.io.*;
import org.jcsp.net.*;
import org.jcsp.net.cns.*;
import org.jcsp.lang.*;
/**
* Program to run a Channel Name Service. The service will listen on all locally available * addresses using either a default port of 7890 or a port specified in the XML file.
* * @author Quickstone Technologies Limited */ public class TCPIPCNSServer2 { /** * For use by other sub classes of this class to terminate the server. To terminate the server write a null * to this channel. This gets used in the NT service implementation to response to the STOP event. */ static final One2OneChannel terminate = Channel.one2one(); private TCPIPCNSServer2() { } /** * Main method, running the service. This will never terminate if the service can be started. */ public static void main(String[] args) { Node.info.log(TCPIPCNSServer2.class, "Starting CNS server"); try { NodeKey key = Node.getInstance().init(new XMLNodeFactory("JCSPNetCNSService.xml")); ServiceManager sm = Node.getInstance().getServiceManager(key); CNS cns = new CNS(key); if (sm.installService(cns, "Channel Name Server") && sm.startService("Channel Name Server")) Node.info.log(TCPIPCNSServer2.class, "CNS Started"); else Node.info.log(TCPIPCNSServer2.class, "CNS failed to start"); } catch (NodeInitFailedException e) { e.printStackTrace(); return; } catch (IOException e) { Node.info.log(TCPIPCNSServer2.class,"XML file not found"); return; } Node.info.log(TCPIPCNSServer2.class,"CNS server running on " + Node.getInstance().getNodeID()); // sleep forever (or until terminated) terminate.in().read(); } } jcsp-1.1-rc4.orig/src/org/jcsp/net/tcpip/TCPIPProtocolID.java 0000644 0000000 0000000 00000012341 11105701167 020530 0 ustar ////////////////////////////////////////////////////////////////////// // // // JCSP ("CSP for Java") Libraries // // Copyright (C) 1996-2008 Peter Welch and Paul Austin. // // 2001-2004 Quickstone Technologies Limited. // // // // This library 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 library 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 library; if not, write to the // // Free Software Foundation, Inc., 59 Temple Place, Suite 330, // // Boston, MA 02111-1307, USA. // // // // Author contact: P.H.Welch@kent.ac.uk // // // // // ////////////////////////////////////////////////////////////////////// package org.jcsp.net.tcpip; import java.net.*; import java.util.*; import org.jcsp.net.*; /** * Defines a protocol ID for the TCP/IP link implementation. * * @see org.jcsp.net.ProtocolID * * @author Quickstone Technologies Limited */ public class TCPIPProtocolID extends ProtocolID { /** * Compares two protocol IDs */ public boolean equals(Object o) { return o instanceof TCPIPProtocolID; } /** * Always returns true. */ public boolean isActive() { return true; } /** * Always returns false. */ public boolean requiresUserInteraction() { return false; } /** * Returns the factory builder for this protocol. */ protected LinkFactory.Builder getLinkBuilder(Hashtable settings) { return new LinkFactory.Builder(this) { public Link testAndBuild(NodeAddressID addressID) { if(!(addressID instanceof TCPIPAddressID)) throw new IllegalArgumentException("Argument not TCP/IP NodeAddressID"); TCPIPAddressID add = (TCPIPAddressID) addressID; return new TCPIPLink(add); } }; } /** * Starts the TCP/IP link server at this node using the given address ID. */ protected LinkServer startLinkServer(NodeAddressID addressID) throws IllegalArgumentException { if(addressID == null) throw new IllegalArgumentException("addressID is null"); return TCPIPLinkServer.create(addressID); } /** * Creates an address from a string form. */ protected NodeAddressID createAddressID(String stAddressID, boolean uniqueAddress) throws IllegalArgumentException { if(stAddressID == null) throw new IllegalArgumentException("addressID is null"); if(stAddressID == "") throw new IllegalArgumentException("Zero length String supplied"); int colonIndex = stAddressID.indexOf(':'); TCPIPAddressID addressID = null; if(colonIndex != -1) { //check that there are characters either side of the colon if(colonIndex > 0 && colonIndex < stAddressID.length() - 1) { String host = stAddressID.substring(0, colonIndex); String stPort = stAddressID.substring(colonIndex + 1, stAddressID.length()); try { int port = Integer.decode(stPort).intValue(); addressID = new TCPIPAddressID(host, port, uniqueAddress); } catch (NumberFormatException e) { throw new IllegalArgumentException("Port not a number"); } catch (UnknownHostException e) { throw new IllegalArgumentException("Unknown host supplied"); } } else { throw new IllegalArgumentException("host and port not fully specified"); } } else { //no port specified try { addressID = new TCPIPAddressID(stAddressID, 0, uniqueAddress); } catch (UnknownHostException e) { throw new IllegalArgumentException("Unknown host supplied"); } } return addressID; } } jcsp-1.1-rc4.orig/src/org/jcsp/net/tcpip/JCSPNetCNSService.xml 0000644 0000000 0000000 00000001371 10522104430 020655 0 ustarDefault factory for simple initialisations using the TCPIPv4 protocol package.
* *Other constructors can be used to specify a particular CNS server. The default behaviour will * extract a CNS server from the system property "org.jcsp.tcpip.DefaultCNSServer" with the server specified * as a name or IP address with optional port number.
* *If built with 1.4 or higher the user preferences will also be checked but only if a * runtime supporting the preferences is available. If not present the system preferences will then * be checked.
* * @author Quickstone Technologies Limited */ public class TCPIPNodeFactory implements NodeFactory { /** * Address of the CNS server. */ private final NodeAddressID cnsServer; /** * Port number to use for the local link server. By default will be system assigned. Call * setLocalPort prior to calling Node.init () to set a specific value. */ private int localPort = 0; /** * Optional security service to install. */ private SecurityService security = null; /** * Constructs an instance of this class. This method is provided so that a later implementation can * opt to pass construction to an alternative under certain conditions. This is for use by the * infrastructure only. Users should call the public constructors. */ public static NodeFactory instantiate() { return new TCPIPNodeFactory(); } /** * Construct the server address, assuming the local host if none is specified. * * @param cnsServerAddress address of CNS server or null to use the local host. * @param cnsServerPort port number */ private NodeAddressID construct(String cnsServerAddress, int cnsServerPort) { try { return new TCPIPAddressID((cnsServerAddress == null) ? InetAddress.getLocalHost().getHostName() : cnsServerAddress, cnsServerPort, true); } catch (UnknownHostException e) { throw new RuntimeException("Invalid host - " + cnsServerAddress); } } /** * Split the server string into a server and port component on the : character. If none is * present the default port is assumed and the request passed to the otherconstruct
* method.
*
* @param cnsServer server with optional port number
*/
private NodeAddressID construct(String cnsServer)
{
int cnsServerPort;
if (cnsServer != null)
{
int ix = cnsServer.indexOf(':');
if (ix < 0)
cnsServerPort = TCPIPCNSServer.DEFAULT_CNS_PORT;
else
{
cnsServerPort = Integer.parseInt(cnsServer.substring(ix + 1));
cnsServer = cnsServer.substring(0, ix);
}
}
else
cnsServerPort = TCPIPCNSServer.DEFAULT_CNS_PORT;
return construct(cnsServer, cnsServerPort);
}
/**
* This code was moved into this method from the constructor below
* in the hope that code would compile on 1.4 and still run on 1.3 and 1.2,
*
*/
private String getServerFromPrefs()
{
try
{
String svr = Preferences.userNodeForPackage(getClass()).get("DefaultCNSServer", null);
if (svr == null)
svr = Preferences.systemNodeForPackage(getClass()).get("DefaultCNSServer", null);
return svr;
}
catch (Exception e)
{
return null;
}
}
/**
* Default constructor, connecting to the local host on the default CNS port or to a host name
* in the system properties. The host name should be specified as name:port or
* just the host name to use the default CNS port.
*/
public TCPIPNodeFactory()
{
try
{
String svr = System.getProperty("org.jcsp.tcpip.DefaultCNSServer");
if (svr == null)
{
try
{
if (Class.forName("java.util.prefs.Preferences") != null)
svr = getServerFromPrefs();
}
catch (ClassNotFoundException e)
{
}
}
this.cnsServer = construct(svr);
}
catch (SecurityException e)
{
throw new RuntimeException("Invalid host");
}
}
/**
* Connect to the named host on the default CNS port. If the server name is given as null
* then the CNS service will not be loaded.
*
* @param cnsServer name of server
*/
public TCPIPNodeFactory(String cnsServer)
{
this.cnsServer = (cnsServer == null) ? null : construct(cnsServer);
}
/**
* Connect to a named host on a specific port.
*
* @param cnsServerAddress name of the server
* @param cnsServerPort port to connect to
*/
public TCPIPNodeFactory(String cnsServerAddress, int cnsServerPort)
{
cnsServer = construct(cnsServerAddress, cnsServerPort);
}
/**
* Initialise the node to listen on all local addresses, and start a CNS service.
*
* @param node the node to be initialized
* @param attribs access to the restricted node attributes
* @throws NodeInitFailedException if a problem occurs
*/
public NodeKey initNode(Node node, Node.Attributes attribs) throws NodeInitFailedException
{
// Get UI factory from system property; or use default
UIFactory uiFactory;
String uiFactoryClassName = System.getProperty("JCSP.UIFactoryClass");
if (uiFactoryClassName != null)
{
try
{
Class uiFactoryClass = Class.forName(uiFactoryClassName);
uiFactory = (UIFactory) uiFactoryClass.newInstance();
}
catch (Exception e)
{
Node.err.log(this, "Error trying to load UIFactory: " + uiFactoryClassName);
return null;
}
}
else
{
uiFactory = new UIFactory();
}
attribs.setUIFactory(uiFactory);
// Setup protocols ...
// Setup local addresses (defaults to all local addresses)
try
{
InetAddress[] allLocal = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
for (int i = 0; i < allLocal.length; i++)
{
try
{
TCPIPAddressID addr = new TCPIPAddressID(allLocal[i], localPort, true);
if (!attribs.getProtocolManager().installProtocolServer(addr, null))
throw attribs.exception("Unable to start LinkServer on " + addr);
if (!attribs.getProtocolManager().installProtocolClient(addr.getProtocolID(), null, null))
throw attribs.exception("Unable to install protocol " + addr.getProtocolID());
}
catch (Exception e)
{
if (e instanceof NodeInitFailedException)
throw e;
Node.err.log(this, "Cannot listen on " + allLocal[i]);
}
}
}
catch (Exception e)
{
if (e instanceof NodeInitFailedException)
throw attribs.exception(e.getMessage());
Node.err.log(this, "Error determining local addresses");
}
// Setup node specifications ...
// Setup profiles ...
// Node profiles ...
// Setup security service
if (security != null)
{
ServiceManager sm = attribs.getServiceManager();
if (sm.installService(security, "security") && security.init(null) && sm.startService("security"))
Node.info.log(this, "Security service started");
else
{
Node.info.log(this, "Security service failed to start");
return null;
}
}
// Start link manager
attribs.startLinkManager();
// Node is now initialized
attribs.setInitialized();
// Setup CNS service
if (cnsServer != null)
{
ServiceManager sm = attribs.getServiceManager();
CNSService cnsService = new CNSService(cnsServer, false);
if (sm.installService(cnsService, CNSService.CNS_DEFAULT_SERVICE_NAME)
&& cnsService.init(null)
&& sm.startService(CNSService.CNS_DEFAULT_SERVICE_NAME))
{
Node.info.log(this, "CNS Started");
}
else
{
Node.info.log(this, "CNS failed to start");
return null;
}
}
return attribs.getNodeKey();
}
/**
* Sets the port number that should be used. If this is not called then the system will allocate
* an arbitrary port.
*
* @param port the port number, 0 <= port < 65536.
*/
public void setLocalPort(int port)
{
localPort = port;
}
/**
* Sets the security service to be used.
*
* @param security the new security authority.
*/
public void setSecurityAuthority(SecurityService security)
{
this.security = security;
}
} jcsp-1.1-rc4.orig/src/org/jcsp/net/tcpip/TCPIPCNSServer.java 0000644 0000000 0000000 00000014052 11105701167 020325 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net.tcpip;
import java.io.*;
import java.net.*;
import org.jcsp.net.*;
import org.jcsp.net.cns.*;
import org.jcsp.lang.*;
/**
* Program to run a Channel Name Service. The service will listen on all locally available * addresses using either a default port of 7890 or a port specified by the first parameter on the * command line.
* * @author Quickstone Technologies Limited */ public class TCPIPCNSServer { /** * For use by other sub classes of this class to terminate the server. To terminate the server write a null * to this channel. This gets used in the NT service implementation to response to the STOP event. */ static final One2OneChannel terminate = Channel.one2one(); private TCPIPCNSServer() { } /** * Main method, running the service. This will never terminate if the service can be started. */ public static void main(String[] args) { // Parse args int port = DEFAULT_CNS_PORT; if (args.length == 1) { try { port = Integer.parseInt(args[0]); if ((port > 0) && (port <= 0xFFFF)) // Valid port args = new String[0]; } catch (NumberFormatException ex) { // do nothing } } if (args.length > 0) { System.err.println("Usage: java org.jcsp.net.tcpip.TCPIPCNSServer [port]\n" + "where 0* * This is a package-private implementation class. * * @author Quickstone Technologies Limited */ // package-private. class TCPIPLinkServer extends LinkServer implements CSProcess { /*----------------------Constructors------------------------------------------*/ /** * Private constructor. To make life easier for you, you don't have to * call this. Just use the static start() method in this class and a * process will be created and executed for you. * * @see #start(ServerSocket) * * @param socket The ServerSocket to accept from */ private TCPIPLinkServer(ServerSocket serverSocket, boolean uniqueAddress) { super(new TCPIPProtocolID(), new TCPIPAddressID(serverSocket.getInetAddress(), serverSocket.getLocalPort(),uniqueAddress)); this.serverSocket = serverSocket; } /*----------------------Public Methods----------------------------------------*/ /** * Start accepting links and dealing with them. * This method runs forever. */ public void run() { try { Node.info.log(this, "TCP/IP V4 LinkServer listening on " + getLinkServerAddressID() + " Started"); while (true) { // Accept an incoming link Socket incoming = serverSocket.accept(); // Create a Link object to represent it. TCPIPLink link = new TCPIPLink(incoming, false); // spawn off the Link object to deal with it, but // let us continue in parallel. new ProcessManager(link).start(); } } catch (Exception ex) { // Will be IOException // warn but otherwise ignore Node.err.log(this, ex); } try { serverSocket.close(); } catch (Exception ignored) { } Node.info.log(this, "TCP/IP V4 LinkServer listening on " + getLinkServerAddressID() + " Ended"); } /*----------------------Non-public Methods------------------------------------*/ /** * Create a server on a specified NodeAddressID, and start it. The server * is spawned off in parallel, so this call returns immediately. * * This NEEDS to be overridden. * * @param addressID The NodeAddressID to accept from */ // package-private protected static LinkServer create(NodeAddressID addressID) { if(!(addressID instanceof TCPIPAddressID)) throw new IllegalArgumentException("Unable to start TCPIPLinkServer, wrong type of address."); TCPIPAddressID add = (TCPIPAddressID) addressID; InetAddress ipAdd = add.getHost(); int port = add.getPort(); TCPIPLinkServer ls; try { ServerSocket serverSocket = new ServerSocket(port, QUEUE_LENGTH, ipAdd); ls = new TCPIPLinkServer(serverSocket, addressID.isGloballyUnique()); new ProcessManager(ls).start(ProcessManager.PRIORITY_MAX); } catch(IOException e) { Node.info.log(TCPIPLinkServer.class, e.getMessage()); ls = null; } return ls; } /** * Stops the LinkServer. * * This NEEDS to be overridden. */ protected boolean stop() { try { Node.info.log(this, "Trying to stop TCP/IP V4 LinkServer listening on " + getLinkServerAddressID()); serverSocket.close(); } catch(IOException e) { e.printStackTrace(); } return true; } /*----------------------Attributes--------------------------------------------*/ /** * The socket to accept from. */ private final ServerSocket serverSocket; private static int QUEUE_LENGTH = 10; } jcsp-1.1-rc4.orig/src/org/jcsp/net/tcpip/TCPIPAddressID.java 0000644 0000000 0000000 00000017512 11105701167 020321 0 ustar ////////////////////////////////////////////////////////////////////// // // // JCSP ("CSP for Java") Libraries // // Copyright (C) 1996-2008 Peter Welch and Paul Austin. // // 2001-2004 Quickstone Technologies Limited. // // // // This library 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 library 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 library; if not, write to the // // Free Software Foundation, Inc., 59 Temple Place, Suite 330, // // Boston, MA 02111-1307, USA. // // // // Author contact: P.H.Welch@kent.ac.uk // // // // // ////////////////////////////////////////////////////////////////////// package org.jcsp.net.tcpip; import java.net.*; import org.jcsp.net.*; /** *
Provides a concrete implementation of the abstract NodeAddressID
for use with the
* TCP/IP link protocol. A TCP/IP node address consists of an internet host address (IP address)
* and 16bit IP port number.
createAddressID
* method of TCPIPProtocolID
.
*/
protected String getStringForm()
{
return stringForm;
}
/**
* Returns the ProtocolID for this address
*/
public ProtocolID getProtocolID()
{
return protocolID;
}
/**
* Returns the computer's IP address
*
* @return IP address of server.
*/
public final InetAddress getHost()
{
return host;
}
/**
* Returns the computer's port number for incoming link requests.
*
* @return Port number of server.
*/
public final int getPort()
{
return port;
}
/**
* Compares two TCPIPAddressID for equality.
*
* @return true iff obj is a non-null TCPIPAddressID for the same port &
* host, false otherwise.
*/
public final boolean equals(Object obj)
{
if ((obj == null) || !(obj instanceof TCPIPAddressID))
return false;
TCPIPAddressID other = (TCPIPAddressID)obj;
return (other.port == port) && (host.equals(other.host));
}
/**
* Returns a hashCode for this TCPIPAddressID
*
*/
public final int hashCode()
{
return host.hashCode() + (port << 16);
}
public boolean isGloballyUnique()
{
return isUnique;
}
/**
* Returns a string representation of this TCPIPAddressID, in the form
* "123.45.67.234:5678".
*
* @return A string representation of this ComputerID.
*/
public final String toString()
{
return host.getHostAddress() + ":" + port;
}
/*----------------------Attributes--------------------------------------------*/
private InetAddress host;
private final int port;
private ProtocolID protocolID = new TCPIPProtocolID();
private String stringForm;
private boolean isUnique = false;
} jcsp-1.1-rc4.orig/src/org/jcsp/net/Specification.java 0000644 0000000 0000000 00000007075 11105701167 017363 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net;
import java.io.*;
/**
*
* @author Quickstone Technologies Limited.
*/
class Specification implements Serializable
{
Specification(String name, int intValue)
{
this.name = name;
this.intValue = intValue;
strValue = "";
dblValue = -1;
booValue = false;
type = Integer.TYPE;
}
Specification(String name, String strValue)
{
this.name = name;
this.strValue = strValue;
intValue = -1;
dblValue = -1;
booValue = false;
type = String.class;
}
Specification(String name, double dblValue)
{
this.name = name;
this.dblValue = dblValue;
intValue = -1;
strValue = "";
booValue = false;
type = Double.TYPE;
}
Specification(String name, boolean booValue)
{
this.name = name;
this.booValue = booValue;
intValue = -1;
strValue = "";
dblValue = -1;
type = Boolean.TYPE;
}
public boolean equals(Object o)
{
if(o == null || !(o instanceof Specification))
return false;
Specification other = (Specification) o;
return type.equals(other.type)
&& name.equals(other.name)
&& intValue == other.intValue
&& strValue.equals(other.strValue)
&& dblValue == other.dblValue
&& booValue == other.booValue;
}
public int hashCode()
{
return name.hashCode();
}
final Class type;
final String name;
final int intValue;
final String strValue;
final double dblValue;
final boolean booValue;
} jcsp-1.1-rc4.orig/src/org/jcsp/net/LinkLostException.java 0000644 0000000 0000000 00000005474 11105701167 020222 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net;
/**
* An exception caused by a link underlying a channel breaking.
*
* @author Quickstone Technologies Limited.
*/
public class LinkLostException extends RuntimeException
{
/**
* The object which threw this exception.
*/
Object source;
/**
* Get the object which threw this exception. This could be a channel
* or any other distributed construct.
*
* @return The object which broke.
*/
Object getSource()
{
return source;
}
/**
* Constructor.
*/
public LinkLostException(Object source)
{
this.source = source;
}
/**
* Constructor.
*
* @param description Description of the error.
*/
public LinkLostException(Object source, String description)
{
super(description);
this.source = source;
}
} jcsp-1.1-rc4.orig/src/org/jcsp/net/NetBufferedChannelEndFactory.java 0000644 0000000 0000000 00000005455 11105701167 022244 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net;
import org.jcsp.util.ChannelDataStore;
/**
* This interface defines methods for constructing buffered
* Networked ChannelInput
objects.
*
* @author Quickstone Technologies Limited
*/
public interface NetBufferedChannelEndFactory
{
/**
* Constructs a NetAltingChannelInput
object.
*
* @param buffer the ChannelDataStore
to use as a buffer.
* @return the constructed NetAltingChannelInput
object.
*/
public NetAltingChannelInput createNet2One(ChannelDataStore buffer);
/**
* Constructs a NetSharedChannelInput
object.
*
* @param buffer the ChannelDataStore
to use as a buffer.
* @return the constructed NetSharedChannelInput
object.
*/
public NetSharedChannelInput createNet2Any(ChannelDataStore buffer);
} jcsp-1.1-rc4.orig/src/org/jcsp/net/ProtocolID.java 0000644 0000000 0000000 00000014371 11105701167 016616 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net;
import java.io.*;
import java.util.*;
/**
*
* Abstract class that identifies a protocol.
* Provides methods for obtaining the protocol's Builder
to be
* installed in the LinkFactory, starting a LinkServer
for this
* protocol and for creating a NodeAddressID
for this protocol
* from a String.
*
* Protocols must not make use of the NodeID so that protocols can be installed before the node ID * is determined. The current definition of TCPIPv4 protocol meets this criteria. Such a change * will allow the UIFactory or other initialisation details to be obtained from a central server. *
* * @author Quickstone Technologies Limited */ public abstract class ProtocolID implements Serializable { /** * This tests whether another object is equal to this object. * TwoProtocolID
objects are equal if their classes are the same.
* This is a default implementation, it is probably more efficient to
* override this with an implementation that uses the instanceof operator.
* @param o an object to compare with this object.
* @return true
iff the supplied object's class is the same as
* the class of this object.
*/
public boolean equals(Object o)
{
Class thisClass = this.getClass();
Class otherClass = o.getClass();
return thisClass.equals(otherClass);
}
/**
* Returns a hash code for this object.
*
* @return the hash code for the object.
*/
public final int hashCode()
{
return this.getClass().hashCode();
}
/**
* * Not currently used. *
** This is envisaged to be used if a protocol that is in use and needs to be * removed sometime in the future. This will stop any further use of the * protocol. *
* * @return boolean indicating whether protocol is active. */ public abstract boolean isActive(); /** ** Returns whether the protocol requires user interaction in order for * data to be delivered. There could be a protocol that writes data * out to floppy disk or CD-R (see Tanenbaum's example of bandwidth and * lorry!). *
* * @return boolean indicating whether user interaction is required. */ public abstract boolean requiresUserInteraction(); /** * Sets the position of this protocol in the order of general preference. * * @param position the position of this protocol in the order. */ final void setPosition(int position) { this.position = position; } /** * Gets the position of this protocol in the order of preference. * * @return the order of preference as anint
.
*/
public final int getPosition()
{
return position;
}
/**
* Obtains the Builder for this protocol. Provides a Hashtable that can
* can contain settings needed to construct the Link.
*
* @param settings Hashtable
containing settings.
* @return the Builder
for constructing Links.
*/
protected abstract LinkFactory.Builder getLinkBuilder(Hashtable settings);
/**
*
* Constructs, starts and returns a LinkServer
on a
* specified NodeAddressID
.
*
LinkServer
* @param addressID The address for the server to listen on.
* @throws IllegalArgumentException if the supplied NodeAddressID
is invalid.
*/
protected abstract LinkServer startLinkServer(NodeAddressID addressID) throws IllegalArgumentException;
/**
* Constructs a NodeAddressID
from a String
.
*
* @return the constructed NodeAddressID
* @param stAddressID The address in String form.
* @param uniqueAddress boolean indicating whether address is unique.
* @throws IllegalArgumentException if the String
supplied is invalid.
*/
protected abstract NodeAddressID createAddressID(String stAddressID, boolean uniqueAddress) throws IllegalArgumentException;
/**
* The position in the order of preference of protocols.
*/
private int position = 0;
} jcsp-1.1-rc4.orig/src/org/jcsp/net/NetConnectionFactory.java 0000644 0000000 0000000 00000006566 11105701167 020705 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net;
/**
*
* This class should be implemented by classes wishing to act
* as factories for creating Networked ConnectionServer
* and ConnectionClient
objects.
*
* An implementation is provided, see
* {@link StandardNetConnectionFactory}
.
*
* Constructs a NetAltingConnectionServer
object.
*
NetAltingConnectionServer
object.
*/
public NetAltingConnectionServer createNet2One();
/**
*
* Constructs a NetSharedConnectionServer
object.
*
NetSharedConnectionServer
object.
*/
public NetSharedConnectionServer createNet2Any();
/**
*
* Constructs a NetAltingConnectionClient
object.
*
NetAltingConnectionClient
object.
*/
public NetAltingConnectionClient createOne2Net(NetChannelLocation serverLoc);
/**
*
* Constructs a NetSharedAltingConnectionClient
object.
*
NetSharedAltingConnectionClient
object.
*/
public NetSharedAltingConnectionClient createAny2Net(NetChannelLocation serverLoc);
} jcsp-1.1-rc4.orig/src/org/jcsp/net/ApplicationID.java 0000644 0000000 0000000 00000010736 11105701167 017261 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net;
import java.io.*;
/**
* * A Class whose instances represent a unique identifier for a JCSP.NET application. * An application is defined as being a process network that forms a complete program. * Applications have a parent Node which is the Node on which the application was started. *
*
* For a full explanation, see {@link AbstractID}
.
*
* Returns a String
representation of this object.
* The current implemenation returns a human readable
* String
which shows the application's home
* NodeID
and the integer application id.
*
String
representing this Application ID.
*/
public String toString()
{
return "Application " + " " + nodeID + " " + appID;
}
/**
*
* Compares the supplied Object
with this
* ApplicationID
.
*
Object
to compare with
* this ApplicationID
.
* @return true
iff the parameter o is an
* ApplicationID
that represents the
* same application as this object.
*/
public boolean equals(Object o)
{
if (o == null || !(o instanceof ApplicationID))
return false;
ApplicationID other = (ApplicationID)o;
if (nodeID.equals(other.nodeID))
return appID == other.appID;
return false;
}
/**
*
* Returns a hash code for this Object. Two equal
* ApplicationID
objects return the same hash code.
*
int
hash code.
*/
public int hashCode()
{
return nodeID.hashCode() + appID;
}
boolean onSameBranch(AbstractID abstractID)
{
if (abstractID == null)
return false;
if (abstractID instanceof ApplicationID)
return this.equals(abstractID);
return nodeID.onSameBranch(abstractID);
}
/**
* Returns the parent NodeID
of this
* object.
*
* @return the parent NodeID
.
*/
public AbstractID getParentID()
{
return nodeID;
}
} jcsp-1.1-rc4.orig/src/org/jcsp/net/LinkManager.java 0000644 0000000 0000000 00000066463 11105701167 017001 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net;
import org.jcsp.lang.*;
import org.jcsp.util.*;
import java.util.*;
/**
* This class manages the list of open links. It ensures that there is
* only ever one link between two given JCSP servers.
*
* @author Quickstone Technologies Limited.
*/
// package-private
class LinkManager implements CSProcess
{
/*-------------------Singleton Class Instance---------------------------------*/
private static LinkManager instance = new LinkManager();
/*-------------------Private Constructor--------------------------------------*/
LinkManager()
{
ProcessManager pm = new ProcessManager(loopbackLink);
pm.setPriority(ProcessManager.PRIORITY_MAX);
pm.start();
}
/*----------------------Attributes--------------------------------------------*/
/**
* The active links. This is a hashtable where the key is a
* NodeID and the value is a Link.
*
* @see NodeID
* @see Link
*/
private Hashtable linkHolders = new Hashtable();
/**
* This maps Link objects to a channel that is used to receive notification
* that the link has been established. This is necessary for when
* links are created to Nodes where the NodeID is not known. This means that
* a link holder cannnot be created as they are identified by the remote
* NodeID of the links they hold.
*
* This would typically be used when establishing a connection to the
* CNS Server as the NodeID would not be known until after the connection is
* made.
*/
//private Hashtable synchChannels = new Hashtable();
/**
* The LoopBackLink used for local connections.
*
*/
private LoopbackLink loopbackLink = new LoopbackLink();
private final Any2OneConnection registerConn = Connection.createAny2One();
private final Any2OneChannel requestLink = Channel.any2one();
private final Any2OneChannel lostLinkChan = Channel.any2one();
private final Any2OneChannel linkFailureChan = Channel.any2one();
private final Any2OneChannel checkForLink = Channel.any2one();
private final Any2OneChannel getNodeIDChan = Channel.any2one();
private final Any2OneChannel registerEventChannel = Channel.any2one();
private static final int ALT_LOST_LINK = 0;
private static final int ALT_LINK_FAIL = 1;
private static final int ALT_REG_CHAN = 2;
private static final int ALT_REQ_LINK = 3;
private static final int ALT_CHECK_FOR_LINK = 4;
/*----------------------Methods-----------------------------------------------*/
/** Used to run the
* Message to be transmitted. This is an abstract class containing
* only header information - you must subclass it to use it.
*
* This is a package-private implementation class.
*
* Creates an anonymous input channel.
*
* To create writers that write to this channel, you need to call
* getChannelName() to get a valid name for this channel. You
* will need to use some other means (e.g. a named channel) to pass
* the channel name to the writing computer.
*
* Creates an anonymous, buffered input channel.
*
* To create writers that write to this channel, you need to call
* getChannelName() to get a valid name for this channel. You
* will need to use some other means (e.g. a named channel) to pass
* the channel name to the writing computer.
* LinkManager
.
*/
public void run()
{
Node.info.log(this, "Running");
//Start a process to hand event channel registration and
//distribution of events
final Any2OneChannel sendEvent = Channel.any2one(new Buffer(10));
CSProcess eventProc = new CSProcess()
{
public void run()
{
Alternative alt = new Alternative(new Guard[] {registerEventChannel.in(), sendEvent.in()});
Vector eventChans = new Vector();
while (true)
{
switch(alt.fairSelect())
{
case 0:
eventChans.add(registerEventChannel.in().read());
break;
case 1:
final ChannelOutput[] chans = new ChannelOutput[eventChans.size()];
final Object eventToSend = sendEvent.in().read();
eventChans.toArray(chans);
new ProcessManager(new CSProcess()
{
public void run()
{
//the channels have infinite buffers
//so ok to just use one thread.
for (int i=0; iLinkManager
and returns.
*/
public void start()
{
new ProcessManager(this).start();
}
/**
* Get the singleton instance of LinkManager.
*
* @return The singleton LinkManager object.
*/
// package-private
static LinkManager getInstance()
{
return instance;
}
/**
* Register a Link in the database. Prevents duplicates.
* Returns true if there was no prior entry for that NodeID, and one
* was added. (In that case it has also notified any waiting processes).
* Returns false (and does not change the database) if there is an
* existing entry.
*
* @return true iff there was no prior entry for that NodeID
*/
//package-private - only called from Link.
boolean registerLink(Link conn)
{
Node.info.log(this, "register link " + conn);
ConnectionClient cc = registerConn.client();
cc.request(conn);
return ((Boolean)cc.reply()).booleanValue();
}
void registerFailure(Link conn)
{
Node.err.log(this, "Link failed to be established: " + conn);
linkFailureChan.out().write(conn);
}
/**
* Get a channel to use to send to a remote PC. Will block (possibly
* forever) while the link is being established.
*
* @param target The system to connect to.
* @return The Channel to use to send to the requested computer.
* @throws IllegalStateException If init() has not been called.
*/
// package-private
ChannelOutput getTxChannel(NodeID target)
{
return getLink(target, null).getTxChannel();
}
ChannelOutput getTxChannel(NodeID target, Profile linkProfile)
{
return getLink(target, linkProfile).getTxChannel();
}
/**
* This is used to get a Link when no details are known about the other
* Node except for one of its addresses. A typical situation when this
* would be used is to connect to the CNS.
*
* @param targetAddress The address to which to create a link.
* @return the ChannelOuput that writes to the link.
*/
ChannelOutput getTxChannel(NodeAddressID targetAddress)
{
Node.getInstance().checkInitialized();
Link link = LinkFactory.getInstance().makeLink(targetAddress);
if(link != null)
{
NodeID remoteNodeID = link.obtainNodeID();
if(remoteNodeID != null)
{
return getTxChannel(remoteNodeID);
}
}
return null;
}
/**
* Get a Link to a remote PC. Will block (possibly forever) while
* the link is being established.
*
* @param target The system to connect to.
* @return The Link to the requested computer.
* @throws IllegalStateException If init() has not been called.
*/
private Link getLink(NodeID target, Profile linkProfile)
{
Node.getInstance().checkInitialized();
if(Node.getInstance().isThisNode(target))
//attempt to get a link to the local Node - return the LoopbackLink
return loopbackLink;
One2OneChannel channel = Channel.one2one(new InfiniteBuffer());
requestLink.out().write(new LinkRequest(channel.out(), target, linkProfile));
Link conn = null;
Object obj = channel.in().read();
if(obj instanceof Link)
conn = (Link) obj;
else if(obj instanceof ProfileMatchFailureException)
throw new IllegalStateException("No matching link exists.");
else
throw new IllegalStateException("No matching link exists.");
return conn;
}
/**
* Called by a Link to indicate the link broke.
*
* @param conn The broken link.
*/
int lostLink(Link conn)
{
lostLinkChan.out().write(conn);
return IndexManager.getInstance().broadcastLinkLost(new LinkLost(conn));
}
/**
* This method tests whether a link exists to
* a specified remote Node in this LinkManager
.
*
* @param otherNode The NodeID
of a remote Node to check
* the existance
* @return true
iff a link currently exists to
* the specified remote Node.
*/
boolean linkExists(NodeID otherNode)
{
Node.getInstance().checkInitialized();
One2OneChannel channel = Channel.one2one(new InfiniteBuffer());
checkForLink.out().write(new LinkCheck(channel.out(), otherNode));
return (channel.in().read() != null);
}
AltingChannelInput getLinkLostEventChannel()
{
Node.getInstance().checkInitialized();
final One2OneChannel eventChan = Channel.one2one(new InfiniteBuffer());
registerEventChannel.out().write(eventChan.out());
//this should be a Safe channel
return eventChan.in();
}
/*----------------------Inner Classes-----------------------------------------*/
private static class LinksToNodeHolder
{
public LinksToNodeHolder(NodeID target)
{
this.target = target;
}
public Link getLink(Profile profile)
{
if(profile == null)
{
if(linkWithNoSpecifiedFacilities != null)
return linkWithNoSpecifiedFacilities;
}
else
{
Iterator it = links.iterator();
while(it.hasNext())
{
Link l = (Link) it.next();
//test whether the link meets the profile's requirements
Specification[] linkSpecs = l.getSpecifications();
int matches = profile.matches(linkSpecs);
//if so, return it
if(matches == 1)
return l;
else if(!profile.requiresExactMatch() && matches == 0)
return l;
}
}
return null;
}
public NodeID getTarget()
{
return target;
}
/**
* This sends the supplied link to any processes that are waiting for
* matching link. If there were some processes waiting or the
* addIfNoQueue
parameter was true, then the link is
* added to this link manager.
*
* @param link the Link to add.
* @param addIfNoQueue boolean inidicating whether to add the link
* if there were no queued processes.
*
* @return the number of processes to which this link was sent.
*/
public int addLink(Link link, boolean addIfNoQueue)
{
Specification[] specs = link.getSpecifications();
int noNotified = notifyQueuedProcesses(specs, link);
if(noNotified > 0 || addIfNoQueue)
{
//if link has not specs or it uses the favoured protocol
//set it as the the link with no specified facilities
if(specs == null || specs.length == 0 || link.getProtocolID().getPosition() == 0)
linkWithNoSpecifiedFacilities = link;
links.add(link);
}
return noNotified;
}
public int notifyQueuedProcesses(Profile profile, Object toSend)
{
if(profile == null)
profile = Profile.getAlwaysMatchProfile();
Object queue = waiting.get(profile);
int notifyCount = 0;
if (queue != null)
{
if (queue instanceof Vector)
{
Vector v = (Vector) queue;
for (int i = 0; i < v.size(); i++)
{
ChannelOutput ch = ((ChannelOutput)v.elementAt(i));
ch.write(toSend);
}
}
else
{
ChannelOutput ch = ((ChannelOutput)queue);
ch.write(toSend);
}
notifyCount++;
waiting.remove(profile);
}
return notifyCount;
}
/**
* This takes a set of link specifications, looks through the set of
* queues, checks whether the specifications meet requirements of
* the profile of a queue, and if so, sends the supplied Link to the
* processes in that queue.
*
* The method returns the number of queues that were notified.
*
* @param specs an array of Specifcation objects that
* the link provides.
* @param linkToSend the link to send to the queued processes.
*
* @return the number of queues that were notified.
*/
public int notifyQueuedProcesses(Specification[] specs, Link linkToSend)
{
int notifyCount = 0;
Iterator it = waiting.keySet().iterator();
while(it.hasNext())
{
Profile profile = (Profile) it.next();
//check whether the specs match the profile
int matchValue = 0;
if (profile != null)
matchValue = profile.matches(specs);
Object toSend = null;
if(profile == null || matchValue == 1 ||(matchValue == 0 && !profile.requiresExactMatch()))
{
notifyCount++;
toSend = linkToSend;
}
else if(profile != null)
{
if(linkToSend.getProfile().equals(profile))
toSend = new ProfileMatchFailureException();
}
if(toSend != null)
{
//the profile matches the specs
if(profile == null)
profile = Profile.getAlwaysMatchProfile();
Object queue = waiting.get(profile);
if (queue != null)
{
if (queue instanceof Vector)
{
Vector v = (Vector) queue;
for (int i = 0; i < v.size(); i++)
{
ChannelOutput ch = ((ChannelOutput)v.elementAt(i));
ch.write(toSend);
}
}
else
{
ChannelOutput ch = ((ChannelOutput)queue);
ch.write(toSend);
}
}
it.remove();
}
}
return notifyCount;
}
public void removeLink(Link conn)
{
links.remove(conn);
}
/**
* This method allows processes to join a queue waiting for a link
* to a Node (with a known NodeID) to be established. An infinite
* buffered channel is supplied. When it is known that a link has
* been created or failed to be created, notification can be sent down
* the supplied channel to the waiting process.
*
* There is one queue per link required matching matching a given
* profile. When a link is established, the profile of each queue
* is tested against the link and, if the profile matches, then all
* queued processes are notified. This can mean that multiple links to
* a remote Node might be established but by the time a link has been
* established, there may be no processes waiting for it as other links
* may have met their requirements.
*
* @param channel the channel to put in the queue.
* @param profile the profile that the required link must meet.
*
* @return a boolean inidicating whether the channel is the first
* in the queue and hence the link needs to be initiated.
*/
public boolean joinQueue(ChannelOutput channel, Profile profile)
{
boolean initiate = false;
Link link = getLink(profile);
if(profile == null)
profile = Profile.getAlwaysMatchProfile();
if(link != null)
channel.write(link);
else if (waiting.containsKey(profile))
{
Object o = waiting.get(profile);
Vector v;
if (o instanceof Vector)
v = (Vector) o;
else
{
v = new Vector();
v.add(o);
}
v.add(channel);
waiting.put(profile, v);
initiate = false;
}
else
{
waiting.put(profile, channel);
initiate = true;
}
return initiate;
}
private NodeID target;
private HashSet links = new HashSet();
/**
* A link with no special facilities. This is so that if no features
* are required then no iteration will be needed.
*
*/
private Link linkWithNoSpecifiedFacilities = null;
/**
* The processes waiting for a link.
* The key is the FacilitiesRequired of the link we're waiting for,
* the value is the channel to the waiting process
* (or a Vector of these). When the link is available, we notify the
* process(es) by sending the Link down the channel(s).
*/
private Hashtable waiting = new Hashtable();
}
private static class ProfileMatchFailureException extends Exception
{
public ProfileMatchFailureException()
{
}
public ProfileMatchFailureException(String msg)
{
super(msg);
}
}
public static class LinkEstablishmentException extends RuntimeException
{
private LinkEstablishmentException(String msg, LinksToNodeHolder lh,
Profile profile)
{
super(msg);
this.lh = lh;
this.profile = profile;
}
private LinksToNodeHolder lh;
private Profile profile;
}
private static class LinkRequest
{
LinkRequest(ChannelOutput replyChan, NodeID target, Profile linkProfile)
{
this.replyChan = replyChan;
this.target = target;
this.linkProfile = linkProfile;
}
final ChannelOutput replyChan;
final NodeID target;
final Profile linkProfile;
}
private static class LinkCheck
{
LinkCheck(ChannelOutput replyChan, NodeID target)
{
this.replyChan = replyChan;
this.target = target;
}
final ChannelOutput replyChan;
final NodeID target;
}
} jcsp-1.1-rc4.orig/src/org/jcsp/net/Message.java 0000644 0000000 0000000 00000007520 11105701167 016162 0 ustar //////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2008 Peter Welch and Paul Austin. //
// 2001-2004 Quickstone Technologies Limited. //
// //
// This library 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 library 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 library; if not, write to the //
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, //
// Boston, MA 02111-1307, USA. //
// //
// Author contact: P.H.Welch@kent.ac.uk //
// //
// //
//////////////////////////////////////////////////////////////////////
package org.jcsp.net;
import java.io.Serializable;
import org.jcsp.lang.ChannelOutput;
/**
*