diff options
Diffstat (limited to 'java')
539 files changed, 0 insertions, 58598 deletions
diff --git a/java/ChangeLog b/java/ChangeLog deleted file mode 100644 index 47a572138e8..00000000000 --- a/java/ChangeLog +++ /dev/null @@ -1,122 +0,0 @@ -Tue Aug 24 13:09:15 1999 Everett Anderson <eea1@cs.wustl.edu> - - * src/*, tests/*, netsvcs/*: Implemented major changes to the - package system. Now all files descend from the JACE directory - under the main archive level. All files are further grouped by - their subpackage names. This is the way Java usually wants it, - and makes JACE javadoc friendly. - - Rewrote and added javadoc comments throughout JACE. - - Changed all concurrency mechanisms to inherit from AbstractLock, - obeying all its requirements such as not releasing the lock - unless the accessing thread is the owner. - - Added the token service. - - Added and rewrote tests for Concurrency mechs and ServiceConfig. - - Rewrote network services to inherit from JACE.netsvcs.Server and - JACE.netsvcs.Handler, abstracting much of the work out to these - base classes. - - Debugging is now OFF by default. - -Wed Aug 18 19:43:23 1999 Everett Anderson <eea1@cs.wustl.edu> - - * src/GetOpt.java: Added another constructor to GetOpt with an - option to return args even if not in the optstring. This is - useful for the default case in a switch (for printUsage - and exit). - -Wed Aug 18 13:35:46 1999 Everett Anderson <eea1@cs.wustl.edu> - - * src/TimerQueue.java: Now when createInternalThread is specified - in the constructor, it is set to be a daemon thread. Thus, if a - TimerQueue thread is the only one executing, the VM exits. - -Wed Jul 14 11:27:47 1999 Everett Anderson <eea1@cs.wustl.edu> - - * src/StrategyAcceptor.java, AcceptStrategy.java - StrategyAcceptor now inherits from Acceptor. AcceptStrategy - can now delegate to an Acceptor, rather than having its own - SOCKAcceptor. Its default is to delegate to a generic - Acceptor instance (that uses a SOCKAcceptor). - -Fri Jul 09 13:58:42 1999 Everett Anderson <eea1@cs.wustl.edu> - - * src/Acceptor.java, TimeValue.java - Solved a few javadoc warnings. - -Fri Jul 09 11:08:32 1999 Everett Anderson <eea1@cs.wustl.edu> - - * src/TimedWait.java, Stream*.java, Token.java - Fixed a bug in TimedWait from the recent changes. Made - Streams (and Modules) use absolute times for timeouts. - -Thu Jul 08 14:54:36 1999 Everett Anderson <eea1@cs.wustl.edu> - - * src/Condition.java, TimedWait.java, EventHandler.java, - MessageQueue.java, ServiceObject.java, SvcHandler.java, - Task.java, Mutex.java, Semaphore.java, Token.java, - TimerQueue.java - - Changed the semantics of Condition, TimedWait, MessageQueue, - Task, Mutex, Semaphore, and Token to use absolute times for - their timeouts. - - Changed the semantics of EventHandler, ServiceObject, and - SvcHandler such that handleTimeout receives a TimeValue - representing when the event occured. - - Changed TimerQueue internally to reflect the above changes. - - Also made better checks in Token and Mutex so that non-owners - can call release without adverse effects. I plan to try to - do this with Semaphore and RWMutex as well. - -Thu Jul 08 11:20:17 1999 Everett Anderson <eea1@cs.wustl.edu> - - * src/TimeValue.java: Added relativeTimeOfDay(offsets) - methods which return TimeValues. These should help people - since many classes will be changed to use - absolute TimeValues shortly to correspond to ACE's versions. - -Wed Jul 07 22:42:27 1999 Everett Anderson <eea1@cs.wustl.edu> - - * src/Token.java: Fixed several bugs in tryacquire and renew. - Specifying a null TimeValue in acquire or renew now means to wait - until the lock is obtained. Specifying TimeValue.zero in acquire - means just to poll and don't call sleepHook(). In renew, it is - the same as specifying a requePosition of 0 -- doesn't give up - the token. - -Wed Jul 07 21:54:35 1999 Everett Anderson <eea1@cs.wustl.edu> - - * src/TimedWait.java: Fixed the semantics of - timedWait(TimeValue tv). Now when tv represents zero, it has - polling semantics, checking the condition once and returning - on success or throwing a TimeoutException on failure. Before, - it blocked until notified. (Also affects synch mechanisms) - -Wed May 20 14:37:48 CDT 1998 Everett Anderson <eea1@cs.wustl.edu> - -Reset the ChangeLog file for future users. If anyone wants more complete -file by file changes, they can be provided with the CVS log command. - -Updated the JACE page at http://www.cs.wustl.edu/~eea1/JACE.html to reflect -the Version 1.4.4 changes, which included: - -* Removed CUP and JLex from JACE. The java_cup directory is still in CVS, - but won't be included in future versions. This means that the option to - load C++ ACE ServiceConfigurator files is gone. - -* Changed the SOCKStream system so it uses DataInputStream and DataOutputStream - to maintain compatibility with other languages and remove the deprecation - warnings from using PrintStream. (Can't use Reader/Writers since they - write 16-bit chars not 8-bit bytes) - -* Made lots of modifications to comments and code to remove javadoc warnings - and deprecation warnings. They were all straight-forward changes such as - making sure a @throws line was in the comments for all exceptions a method - had, etc. diff --git a/java/ImageProcessing/ImageProcessing.dsp b/java/ImageProcessing/ImageProcessing.dsp deleted file mode 100644 index 897cf304526..00000000000 --- a/java/ImageProcessing/ImageProcessing.dsp +++ /dev/null @@ -1,253 +0,0 @@ -# Microsoft Developer Studio Project File - Name="ImageProcessing" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=ImageProcessing - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "ImageProcessing.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "ImageProcessing.mak"\
- CFG="ImageProcessing - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "ImageProcessing - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "ImageProcessing - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "ImageProcessing - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "ImageProcessing - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "ImageProcessing - Java Virtual Machine Release"
-# Name "ImageProcessing - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\filters\Assert.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\BaseButton.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\BenchmarkApplet.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\BleachFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\BlurFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\DarkenFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\DeSpeckleFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\DialogManager.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\DialogType.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\DissolveFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\EdgeDetectFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\EmbossFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\FileBrowser.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\FilePanel.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\GifEncoder.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\GIFHandler.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\Hierarchy.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\HierarchyAdapter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\Icon.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\ImageApp.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\ImageByteCounter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\ImageCanvas.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\ImageEncoder.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\ImageProcessor.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\ImageSender.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\IntHashtable.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\ListFiles.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\LoadURLFrame.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\MedFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\OilPaintFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\Options.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\PixelizeFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\RandomizeFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\RotateFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\SaveURLFrame.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\Separator.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\ServerHandler.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\ServerTest.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\SharpenFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\SpatialFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\SpreadFilter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\StatusDisplay.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\StatusIndicator.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\Tester.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\framework\TestHandler.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\filters\Timer.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/ImageProcessing/ImageProcessing.dsw b/java/ImageProcessing/ImageProcessing.dsw deleted file mode 100644 index 672fddb912b..00000000000 --- a/java/ImageProcessing/ImageProcessing.dsw +++ /dev/null @@ -1,29 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00
-# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
-
-###############################################################################
-
-Project: "ImageProcessing"=.\ImageProcessing.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Global:
-
-Package=<5>
-{{{
-}}}
-
-Package=<3>
-{{{
-}}}
-
-###############################################################################
-
diff --git a/java/ImageProcessing/filters/Assert.java b/java/ImageProcessing/filters/Assert.java deleted file mode 100644 index c83f9ca94c0..00000000000 --- a/java/ImageProcessing/filters/Assert.java +++ /dev/null @@ -1,33 +0,0 @@ -package imaging.filters; - -/** - * A simple assertion mechanism for asserting validity of - * arguments.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - */ -class Assert { - static public void notFalse(boolean b) - throws IllegalArgumentException { - if(b == false) - throw new IllegalArgumentException( - "boolean expression false"); - } - static public void notNull(Object obj) - throws IllegalArgumentException { - if(obj == null) - throw new IllegalArgumentException("null argument"); - } - - static public void notFalse(boolean b, String s) - throws IllegalArgumentException { - if(b == false) - throw new IllegalArgumentException(s); - } - static public void notNull(Object obj, String s) - throws IllegalArgumentException { - if(obj == null) - throw new IllegalArgumentException(s); - } -} diff --git a/java/ImageProcessing/filters/BleachFilter.java b/java/ImageProcessing/filters/BleachFilter.java deleted file mode 100644 index e9d6a0b9e0e..00000000000 --- a/java/ImageProcessing/filters/BleachFilter.java +++ /dev/null @@ -1,65 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; - -/** - * A derivation of RGBImageFilter that bleaches an image.<p> - * - * Extent of the bleaching effect is controlled by the only - * constructor argument: an integer representing the percentage - * of bleaching. The percentage of bleaching may also be - * controlled after instantiation by invoking the - * void percent(int) method.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see RGBImageFilter - */ -public class BleachFilter extends RGBImageFilter implements MedFilter -{ - private int percent; - - public BleachFilter() - { - this(25); - } - - public BleachFilter(int percent) - { - Assert.notFalse(percent >= 0 && percent <= 100); - this.percent = percent; - canFilterIndexColorModel = true; - } - - public String info () - { - return "Bleaches/Lightens an image"; - } - - public int percent() { return percent; } - public void percent(int percent) { percent = percent; } - - public int filterRGB(int x, int y, int rgb) { - DirectColorModel cm = - (DirectColorModel)ColorModel.getRGBdefault(); - - int alpha = cm.getAlpha(rgb); - int red = cm.getRed (rgb); - int green = cm.getGreen(rgb); - int blue = cm.getBlue (rgb); - double percentMultiplier = (double)percent/100; - - red = Math.min((int) - (red + (red * percentMultiplier)), 255); - green = Math.min((int) - (green + (green * percentMultiplier)), 255); - blue = Math.min((int) - (blue + (blue * percentMultiplier)), 255); - - alpha = alpha << 24; - red = red << 16; - green = green << 8; - - return alpha | red | green | blue; - } -} diff --git a/java/ImageProcessing/filters/BlurFilter.java b/java/ImageProcessing/filters/BlurFilter.java deleted file mode 100644 index e071324e491..00000000000 --- a/java/ImageProcessing/filters/BlurFilter.java +++ /dev/null @@ -1,95 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; - -public class BlurFilter extends SpatialFilter -{ - private int[][] mean_filter; - private int degree_ = 3; - - public BlurFilter() - { - } - - public BlurFilter(int degree) - { - degree_ = degree; - } - - public void imageComplete(int status) - { - if (status == IMAGEERROR || status == IMAGEABORTED) - { - consumer.imageComplete(status); - System.out.println("Image Error"); - return; - } - - System.gc(); - - int[] pixels = new int[columns_*rows_]; - int pixel = 0, count = 0; - int red, green, blue, index; - int alpha, n2 = degree_/2; - - profile_timer_.start(); - - for (int z = SpatialFilter.iterations_; z-- > 0;) - { - - for (int y = 0, i = 0; y < rows_; y++) - { - for (int x = 0; x < columns_; x++, i++) - { - red = 0; green = 0; blue = 0; count = 0; - alpha = (raster_[i] >> 24) & 0xff; - - for (int y1 = y - n2; y1 < y + n2; y1++) - { - index = y1*columns_; - if (y1 >= 0 && y1 < rows_) - { - for (int x1 = x - n2; x1 < x + n2; x1++) - { - if (x1 >= 0 && x1 < columns_) - { - pixel = raster_[index + x1]; - - red += (pixel >> 16) & 0xff; - green += (pixel >> 8) & 0xff; - blue += (pixel) & 0xff; - count++; - } - } - } - } - - red /= count; - green /= count; - blue /= count; - - if (red < 0) red = 0; - if (green < 0) green = 0; - if (blue < 0) blue = 0 ; - - if (red > 255) red = 255; - if (green > 255) green = 255; - if (blue > 255) blue = 255; - - pixels[i] = (alpha << 24) | (red << 16) | (green << 8) | blue; - } - } - } - - profile_timer_.stop(); - - System.out.println("Finished altering image"); - consumer.setPixels(0, 0, columns_, rows_, defaultRGB_, pixels, 0, columns_); - consumer.imageComplete(status); - } - - public String info () - { - return "Blurs an image."; - } -} diff --git a/java/ImageProcessing/filters/DarkenFilter.java b/java/ImageProcessing/filters/DarkenFilter.java deleted file mode 100644 index ea20d15a46b..00000000000 --- a/java/ImageProcessing/filters/DarkenFilter.java +++ /dev/null @@ -1,48 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; - -public class DarkenFilter extends RGBImageFilter implements MedFilter -{ - private int percent_; - - public DarkenFilter () - { - percent_ = 50; - canFilterIndexColorModel = true; - } - - public DarkenFilter(int percent) - { - Assert.notFalse(percent >= 0 && percent <= 100); - percent_ = percent; - canFilterIndexColorModel = true; - } - - public String info () - { - return "Darkens an image."; - } - - public int filterRGB(int x, int y, int rgb) - { - DirectColorModel cm = - (DirectColorModel)ColorModel.getRGBdefault(); - - int alpha = cm.getAlpha(rgb); - int red = cm.getRed (rgb); - int green = cm.getGreen(rgb); - int blue = cm.getBlue (rgb); - double percentMultiplier = (double)((double)1.0 - (double)percent_/100); - - red *= percentMultiplier; - blue *= percentMultiplier; - green *= percentMultiplier; - - alpha = alpha << 24; - red = red << 16; - green = green << 8; - - return alpha | red | green | blue; - } -} diff --git a/java/ImageProcessing/filters/DeSpeckleFilter.java b/java/ImageProcessing/filters/DeSpeckleFilter.java deleted file mode 100644 index d9bff1de3b5..00000000000 --- a/java/ImageProcessing/filters/DeSpeckleFilter.java +++ /dev/null @@ -1,123 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; - -public class DeSpeckleFilter extends SpatialFilter -{ - private int degree_ = 3; - - public DeSpeckleFilter() - { - } - - public DeSpeckleFilter(int degree) - { - degree_ = degree; - } - - public String info () - { - return "Removes speckles from an image."; - } - - public void imageComplete(int status) - { - if (status == IMAGEERROR || status == IMAGEABORTED) - { - consumer.imageComplete(status); - System.out.println("DeSpeckleFilter Image Error: " + status); - return; - } - - System.gc(); - - int rsum, bsum, gsum, r, g, b, a; - int count, n2, nsq, c2, lcv, lcv2, index; - int[] rtab, gtab, btab; - int[] pixels = new int[columns_*rows_]; - - profile_timer_.start(); - - n2 = degree_/2; - nsq = degree_ * degree_; - - rtab = new int[nsq]; - gtab = new int[nsq]; - btab = new int[nsq]; - - for (int z = SpatialFilter.iterations_; z-- > 0;) - { - for (int y = 0, k = 0; y < rows_; y++) - { - lcv = y + n2; - for (int x = 0; x < columns_; x++, k++) - { - rsum = gsum = bsum = 0; - count = 0; - - lcv2 = x + n2; - for (int y1 = y - n2; y1 < lcv; y1++) - { - index = y1*columns_; - if (y1 >= 0 && y1 < rows_) - { - for (int x1 = x - n2; x1 < lcv2; x1++) - { - if (x1 >= 0 && x1 < columns_) - { - int pixel = raster_[index + x1]; - rtab[count] = (pixel >> 16) & 0xff; - gtab[count] = (pixel >> 8) & 0xff; - btab[count] = (pixel) & 0xff; - count++; - } - } - } - } - - for (int d = count >> 1; d > 0; d >>= 1) - { - for (int i = d; i < count; i++) - { - for (int j = i - d; j >= 0 && rtab[j] > rtab[j+d]; j -= d) - { - int t = rtab[j]; - rtab[j] = rtab[j + d]; - rtab[j + d] = t; - } - - for (int j = i - d; j >= 0 && gtab[j] > gtab[j+d]; j -= d) - { - int t = gtab[j]; - gtab[j] = gtab[j + d]; - gtab[j + d] = t; - } - - for (int j = i - d; j >= 0 && btab[j] > btab[j+d]; j -= d) - { - int t = btab[j]; - btab[j] = btab[j + d]; - btab[j + d] = t; - } - } - } - - c2 = count >> 1; - - a = (raster_[k] >> 24) & 0xff; - r = ( (count % 2 == 0) ? (rtab[c2] + rtab[c2 - 1]) >> 1 : rtab[c2]); - g = ( (count % 2 == 0) ? (gtab[c2] + gtab[c2 - 1]) >> 1 : gtab[c2]); - b = ( (count % 2 == 0) ? (btab[c2] + btab[c2 - 1]) >> 1 : btab[c2]); - - pixels[k] = (a << 24) | (r << 16) | (g << 8) | b; - } - } - } - - profile_timer_.stop(); - - consumer.setPixels(0, 0, columns_, rows_, defaultRGB_, pixels, 0, columns_); - consumer.imageComplete(status); - } - -} diff --git a/java/ImageProcessing/filters/DissolveFilter.java b/java/ImageProcessing/filters/DissolveFilter.java deleted file mode 100644 index 0225aad6ad1..00000000000 --- a/java/ImageProcessing/filters/DissolveFilter.java +++ /dev/null @@ -1,52 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; - -/** - * A derivation of RGBImageFilter that partially or wholly - * dissolves an image.<p> - * - * Extent of dissolving is set by the setOpacity(int) method, - * which is passed an integer between 0 and 255 (inclusive). - * The integer represents the alpha value to be applied to - * every color in the image.<p> - * - * An alpha value of 255 signifies an opaque color, while an - * alpha value of 0 signifies a translucent color.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see RGBImageFilter - */ -public class DissolveFilter extends RGBImageFilter implements MedFilter -{ - private int opacity; - - public DissolveFilter() { - this(0); - } - public DissolveFilter(int opacity) { - canFilterIndexColorModel = true; - setOpacity(opacity); - } - public String info () - { - return "Dissolves an image"; - } - public void setOpacity(int opacity) { - Assert.notFalse(opacity >= 0 && opacity <= 255); - this.opacity = opacity; - } - public int filterRGB(int x, int y, int rgb) { - DirectColorModel cm = - (DirectColorModel)ColorModel.getRGBdefault(); - int alpha = cm.getAlpha(rgb); - int red = cm.getRed (rgb); - int green = cm.getGreen(rgb); - int blue = cm.getBlue (rgb); - - alpha = opacity; - - return alpha << 24 | red << 16 | green << 8 | blue; - } -} diff --git a/java/ImageProcessing/filters/EdgeDetectFilter.java b/java/ImageProcessing/filters/EdgeDetectFilter.java deleted file mode 100644 index 87cc88d475d..00000000000 --- a/java/ImageProcessing/filters/EdgeDetectFilter.java +++ /dev/null @@ -1,250 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; - -public class EdgeDetectFilter extends SpatialFilter -{ - public EdgeDetectFilter() - { - } - - public String info () - { - return "Edge detection filter."; - } - - public void imageComplete(int status) - { - if (status == IMAGEERROR || status == IMAGEABORTED) - { - consumer.imageComplete(status); - System.out.println("Image Error"); - return; - } - - System.gc(); - - int[] pixels = new int[columns_*rows_]; - int pixel = 0; - int red, green, blue; - int row1, row2, row3; - int new_red1 = 0, new_green1 = 0, new_blue1 = 0, - new_red2 = 0, new_green2 = 0, new_blue2 = 0; - int ul, um, ur, ll, lm, lr, ml, mr; - int alpha, lcv, lcv2; - - profile_timer_.start(); - - for (int z = SpatialFilter.iterations_; z-- > 0;) - { - lcv = rows_ - 1; - lcv2 = columns_ - 1; - for (int x = 1, index = 0; x < lcv; x++, index += columns_) - { - for (int y = 1; y < lcv2; y++) - { - row1 = index + y; - row2 = row1 + columns_; - row3 = row2 + columns_; - - ul = raster_[row1 - 1]; - um = raster_[row1]; - ur = raster_[row1 + 1]; - ml = raster_[row2 - 1]; - mr = raster_[row2 + 1]; - ll = raster_[row3 - 1]; - lm = raster_[row3]; - lr = raster_[row3 + 1]; - - alpha = (raster_[row2] >> 24) & 0xff; - - new_red1 = - (((ul >> 16) & 0xff) - + (((um >> 16) & 0xff) << 1) - + ((ur >> 16) & 0xff) - - ((ll >> 16) & 0xff) - - (((lm >> 16) & 0xff) << 1) - - ((lr >> 16) & 0xff)); - - new_green1 = - (((ul >> 8) & 0xff) - + (((um >> 8) & 0xff) << 1) - + ((ur >> 8) & 0xff) - - ((ll >> 8) & 0xff) - - (((lm >> 8) & 0xff) << 1) - - ((lr >> 8) & 0xff)); - - new_blue1 = - (((ul) & 0xff) - + (((um) & 0xff) << 1) - + ((ur) & 0xff) - - ((ll) & 0xff) - - (((lm) & 0xff) << 1) - - ((lr) & 0xff)); - - new_red2 = - (- ((ul >> 16) & 0xff) - + ((ur >> 16) & 0xff) - - (((ml >> 16) & 0xff) << 1) - + (((mr >> 16) & 0xff) << 1) - - ((ll >> 16) & 0xff) - + ((lr >> 16) & 0xff)); - - new_green2 = - (- ((ul >> 8) & 0xff) - + ((ur >> 8) & 0xff) - - (((ml >> 8) & 0xff) << 1) - + (((mr >> 8) & 0xff) << 1) - - ((ll >> 8) & 0xff) - + ((lr >> 8) & 0xff)); - - new_blue2 = - (- ((ul) & 0xff) - + ((ur) & 0xff) - - (((ml) & 0xff) << 1) - + (((mr) & 0xff) << 1) - - ((ll) & 0xff) - + ((lr) & 0xff)); - - - new_red1 = (int)Math.sqrt(new_red1*new_red1 + new_red2*new_red2); - new_green1 = (int)Math.sqrt(new_green1*new_green1 + new_green2*new_green2); - new_blue1 = (int)Math.sqrt(new_blue1*new_blue1 + new_blue2*new_blue2); - - if (new_red1 < 0) red = 0; - if (new_green1 < 0) green = 0; - if (new_blue1 < 0) blue = 0 ; - - - if (new_red1 > 255) - new_red1 = 255; - - if (new_green1 > 255) - new_green1 = 255; - - if (new_blue1 > 255) - new_blue1 = 255; - - pixels[row2] = (alpha << 24) | (new_red1 << 16) | (new_green1 << 8) | new_blue1; - } - } - } - - profile_timer_.stop(); - - consumer.setPixels(0, 0, columns_, rows_, defaultRGB_, pixels, 0, columns_); - consumer.imageComplete(status); - } - - /* - public void imageComplete(int status) - { - if (status == IMAGEERROR || status == IMAGEABORTED) - { - consumer.imageComplete(status); - System.out.println("Image Error"); - return; - } - - int[][] pixels = new int[rows_*columns_]; - int pixel = 0; - int red, green, blue; - int row1, row2, row3, row4, row5; - int a, b, c, d, rsum, gsum, bsum, v, maxv = 0; - int ul, um, ur, ml, mr, ll, lm, lr, lcv, lcv2; - int alpha; - - lcv = rows_ -1; - for (int y = 1; y < lcv; y++) - { - lcv2 = columns_ -1; - for (int x = 1; x < lcv2; x++) - { - row1 = columns_*(y-1) + x; - row2 = row1 + columns_; - row3 = row2 + columns_; - ul = raster_[row1 - 1]; - um = raster_[row1]; - ur = raster_[row1 + 1]; - ml = raster_[row2 - 1]; - mr = raster_[row2 + 1]; - ll = raster_[row3 - 1]; - lm = raster_[row3]; - lr = raster_[row3 + 1]; - - alpha = defaultRGB_.getAlpha(raster_[row2]); - - a = ((lr >> 16) & 0xff) - ((ul >> 16) & 0xff); - b = ((mr >> 16) & 0xff) - ((ml >> 16) & 0xff); - c = ((ur >> 16) & 0xff) - ((ll >> 16) & 0xff); - d = ((um >> 16) & 0xff) - ((lm >> 16) & 0xff); - - rsum = a + b + c; - if (rsum < 0) rsum = -rsum; - a = a - c - d; - if (a < 0) a = -a; - if (rsum > a) rsum = a; - rsum /= 3; - - a = ((lr >> 8) & 0xff) - ((ul >> 8) & 0xff); - b = ((mr >> 8) & 0xff) - ((ml >> 8) & 0xff); - c = ((ur >> 8) & 0xff) - ((ll >> 8) & 0xff); - d = ((um >> 8) & 0xff) - ((lm >> 8) & 0xff); - - gsum = a + b + c; - if (gsum < 0) gsum = -gsum; - a = a - c - d; - if (a < 0) a = -a; - if (gsum > a) gsum = a; - gsum /= 3; - - a = ((lr) & 0xff) - ((ul) & 0xff); - b = ((mr) & 0xff) - ((ml) & 0xff); - c = ((ur) & 0xff) - ((ll) & 0xff); - d = ((um) & 0xff) - ((lm) & 0xff); - - bsum = a + b + c; - if (bsum < 0) bsum = -bsum; - a = a - c - d; - if (a < 0) a = -a; - if (bsum > a) bsum = a; - bsum /= 3; - - pixels[row2] = (alpha << 24) | (rsum << 16) | (gsum << 8) | bsum; - - v = (((int)(rsum)*11 + ((int)(gsum) << 4) + (int)(bsum)*5) >> 5); - - if (maxv < v) - maxv = v; - } - - } - - for (int y = 1; y < rows_ - 1; y++) - { - for (int x = 1; x < columns_ - 1; x++) - { - pixel = pixels[y][x]; - alpha = (pixel >> 24) & 0xff; - red = (((pixel >> 16) & 0xff) * 255) / maxv; - green = (((pixel >> 8) & 0xff) * 255) / maxv; - blue = ((pixel & 0xff) * 255) / maxv; - - if (red < 0) red = 0; - if (green < 0) green = 0; - if (blue < 0) blue = 0 ; - - if (red > 255) red = 255; - if (green > 255) green = 255; - if (blue > 255) blue = 255; - - pixels[y*x] = (alpha << 24) | (red << 16) | (green << 8) | blue; - } - - consumer.setPixels(0, y, columns_, 1, defaultRGB_, pixels[y], 0, columns_); - } - - consumer.imageComplete(status); - } - */ -} diff --git a/java/ImageProcessing/filters/EmbossFilter.java b/java/ImageProcessing/filters/EmbossFilter.java deleted file mode 100644 index e6d5833ee39..00000000000 --- a/java/ImageProcessing/filters/EmbossFilter.java +++ /dev/null @@ -1,86 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; - -public class EmbossFilter extends SpatialFilter -{ - - public EmbossFilter() - { - } - - public String info () - { - return "Embosses an image."; - } - - public void imageComplete(int status) - { - if (status == IMAGEERROR || status == IMAGEABORTED) - { - consumer.imageComplete(status); - System.out.println("Emboss: Image Error: " + status); - return; - } - - System.out.println("Beginning to emboss an image."); - System.gc(); - - int[] pixels = new int[columns_*rows_]; - int pixel = 0; - int red, green, blue; - int row1, row2, row3, ul, um, ml, mr, lm, lr; - int new_grey = 0, lcv, lcv2; - int alpha; - - profile_timer_.start(); - - for (int z = SpatialFilter.iterations_; z-- > 0;) - { - lcv = rows_ -1; - for (int x = 1, index = 0; x < lcv; x++, index += columns_) - { - lcv2 = columns_ - 1; - for (int y = 1; y < lcv2; y++) - { - - row1 = index + y; - row2 = row1 + columns_; - row3 = row2 + columns_; - - ul = raster_[row1 - 1]; - um = raster_[row1]; - ml = raster_[row2 - 1]; - mr = raster_[row2 + 1]; - lm = raster_[row3]; - lr = raster_[row3 + 1]; - - alpha = (raster_[row2] >> 24) & 0xff; - - red = ((- (((ul >> 16) & 0xff) << 1) - ((um >> 16) & 0xff) - - ((ml >> 16) & 0xff) + ((mr >> 16) & 0xff) + - ((lm >> 16) & 0xff) + (((lr >> 16) & 0xff) << 1)) >> 3) + 128; - - green = ((- (((ul >> 8) & 0xff) << 1) - ((um >> 8) & 0xff) - - ((ml >> 8) & 0xff) + ((mr >> 8) & 0xff) + - ((lm >> 8) & 0xff) + (((lr >> 8) & 0xff) << 1)) >> 3) + 128; - - blue = ((- ((ul & 0xff) << 1) - (um & 0xff) - - (ml & 0xff) + (mr & 0xff) + - (lm & 0xff) + ((lr & 0xff) << 1)) >> 3) + 128; - - new_grey = (((int)(red)*11 + ((int)(green) << 4) + (int)(blue)*5) >> 5); - - pixels[row2] = (alpha << 24) | (new_grey << 16) | (new_grey << 8) | new_grey; - - } - } - } - - profile_timer_.stop(); - - consumer.setPixels(0, 0, columns_, rows_, defaultRGB_, pixels, 0, columns_); - // System.out.println(timer); - consumer.imageComplete(status); - } -} diff --git a/java/ImageProcessing/filters/Makefile b/java/ImageProcessing/filters/Makefile deleted file mode 100644 index 253bc9b5c22..00000000000 --- a/java/ImageProcessing/filters/Makefile +++ /dev/null @@ -1,36 +0,0 @@ -# Makefile - -.SUFFIXES: .java .class - -JACE_WRAPPER = ../.. -CLASSDIR = $(JACE_WRAPPER)/classes -DOCDIR = $(JACE_WRAPPER)/doc - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: - javac -d ${JACE_WRAPPER}/classes $(files) - -clean: - rm -rf *~ - -realclean: clean - rm -rf $(JACE_WRAPPER)/classes/imaging/filters/*.class - -files = MedFilter.java \ - Assert.java \ - BleachFilter.java \ - BlurFilter.java \ - DarkenFilter.java \ - DeSpeckleFilter.java \ - DissolveFilter.java \ - EdgeDetectFilter.java \ - EmbossFilter.java \ - OilPaintFilter.java \ - PixelizeFilter.java \ - RotateFilter.java \ - SharpenFilter.java \ - SpatialFilter.java \ - SpreadFilter.java \ - Timer.java - diff --git a/java/ImageProcessing/filters/MedFilter.java b/java/ImageProcessing/filters/MedFilter.java deleted file mode 100644 index def0bd2075a..00000000000 --- a/java/ImageProcessing/filters/MedFilter.java +++ /dev/null @@ -1,6 +0,0 @@ -package imaging.filters; - -public interface MedFilter -{ - String info (); -} diff --git a/java/ImageProcessing/filters/OilPaintFilter.java b/java/ImageProcessing/filters/OilPaintFilter.java deleted file mode 100644 index 68bcf79e5c2..00000000000 --- a/java/ImageProcessing/filters/OilPaintFilter.java +++ /dev/null @@ -1,97 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; - -public class OilPaintFilter extends SpatialFilter -{ - private int degree_ = 3; - - public OilPaintFilter() - { - } - - public OilPaintFilter(int degree) - { - degree_ = degree; - } - - public String info () - { - return "Converts an image into an oil painting."; - } - - public void imageComplete(int status) - { - if (status == IMAGEERROR || status == IMAGEABORTED) - { - consumer.imageComplete(status); - System.out.println("Oil Paint FilterImage Error: " + status); - return; - } - - System.gc(); - - int[] pixels = new int[columns_*rows_]; - int[] nnrect = new int[degree_*degree_]; - int offset = degree_/2, cnt = 0, maxcnt = 0, col = 0, tmp; - int lcv1 = rows_, - lcv2 = columns_, - lcv3 = degree_*degree_; - - profile_timer_.start(); - - for (int z = SpatialFilter.iterations_; z-- > 0;) - { - for (int y = 0, index = 0; y < lcv1; y++) - { - for (int x = 0; x < lcv2; x++, index++) - { - cnt = 0; - for (int i = y - offset; i < y + offset; i++) - { - tmp = i*columns_; - for (int j = x - offset; j < x + offset; j++, cnt++) - { - if (i >= 0 && i < lcv1 && j >= 0 && j < lcv2) - nnrect[cnt] = raster_[tmp + j]; - else - nnrect[cnt] = -1; - } - } - - maxcnt = 0; - col = 0; - cnt = 0; - for (int i = 0; i < lcv3; i++) - { - if (nnrect[i] != -1) - { - cnt = 1; - - for (int j = i+1; j < lcv3; j++) - { - if (nnrect[i] == nnrect[j]) - cnt++; - } - - if (cnt > maxcnt) - { - col = nnrect[i]; - maxcnt = cnt; - } - } - } - - pixels[index] = col; - } - } - } - - System.err.println("Oil Paint should be finished."); - - profile_timer_.stop(); - - consumer.setPixels(0, 0, columns_, rows_, defaultRGB_, pixels, 0, columns_); - consumer.imageComplete(status); - } -} diff --git a/java/ImageProcessing/filters/PixelizeFilter.java b/java/ImageProcessing/filters/PixelizeFilter.java deleted file mode 100644 index cdfe768789a..00000000000 --- a/java/ImageProcessing/filters/PixelizeFilter.java +++ /dev/null @@ -1,117 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; - -public class PixelizeFilter extends SpatialFilter -{ - private int pwidth_ = 4; - private int pheight_ = 4; - - public PixelizeFilter() - { - } - - public PixelizeFilter(int pwidth, int pheight) - { - pwidth_ = pwidth; - pheight_ = pheight; - } - - public String info () - { - return "Pixelizes the image."; - } - - public void imageComplete(int status) - { - if (status == IMAGEERROR || status == IMAGEABORTED) - { - consumer.imageComplete(status); - System.out.println("Pixelize Image Error: " + status); - return; - } - - System.gc(); - - int pixel; - int nsum, asum, rsum, gsum, bsum, nwide, nhigh, stx, sty, x, y; - int x_offset, y_offset, x_extent, y_extent, lcv, lcv2, lcv3, index; - int[] results = new int[rows_*columns_]; - - profile_timer_.start(); - - for (int z = SpatialFilter.iterations_; z-- > 0;) - { - lcv3 = pwidth_*pheight_; - nwide = (columns_ + pwidth_ - 1) / pwidth_; - nhigh = (rows_ + pheight_ - 1) / pheight_; - - stx = -(nwide*pwidth_ - columns_)/2; - sty = -(nhigh*pheight_ - rows_)/2; - - y = sty; - for (int i = 0; i < nhigh; i++, y += pheight_) - { - x = stx; - for (int j = 0; j < nwide; j++, x += pwidth_) - { - nsum = asum = rsum = bsum = gsum = 0; - - lcv = y + pheight_; - lcv2 = x + pwidth_; - for (int y1 = y; y1 < lcv; y1++) - { - index = y1*columns_; - for (int x1 = x; x1 < lcv2; x1++) - { - if (x1 >= 0 && y1 >= 0 && x1 < columns_ && y1 < rows_) - { - nsum++; - pixel = raster_[index + x1]; - - asum += (pixel >> 24) & 0xff; - rsum += (pixel >> 16) & 0xff; - gsum += (pixel >> 8 ) & 0xff; - bsum += pixel & 0xff; - } - } - } - - if (nsum > 0) - { - rsum /= nsum; - gsum /= nsum; - bsum /= nsum; - - if (asum < 0) asum = 0; - if (rsum < 0) rsum = 0; - if (gsum < 0) gsum = 0; - if (bsum < 0) bsum = 0; - - if (asum > 255) asum = 255; - if (rsum > 255) rsum = 255; - if (gsum > 255) gsum = 255; - if (bsum > 255) bsum = 255; - - } - - for (int y1 = y; y1< lcv; y1++) - { - index = y1*columns_; - for (int x1 = x; x1 < lcv2; x1++) - { - if (x1 >= 0 && y1 >= 0 && x1 < columns_ && y1 < rows_) - results[index + x1] - = (asum << 24) | (rsum << 16) | (gsum << 8) | bsum; - } - } - } - } - } - - profile_timer_.stop(); - - consumer.setPixels(0, 0, columns_, rows_, defaultRGB_, results, 0, columns_); - consumer.imageComplete(status); - } -} diff --git a/java/ImageProcessing/filters/RandomizeFilter.java b/java/ImageProcessing/filters/RandomizeFilter.java deleted file mode 100644 index 438f79e01c0..00000000000 --- a/java/ImageProcessing/filters/RandomizeFilter.java +++ /dev/null @@ -1,36 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; -import java.util.Random; - -public class RandomizeFilter extends RGBImageFilter implements MedFilter -{ - private static Random rand = new Random(System.currentTimeMillis()); - - public RandomizeFilter () - { - canFilterIndexColorModel = true; - } - - public String info () - { - return "Randomizes an image."; - } - - public int filterRGB(int x, int y, int rgb) - { - DirectColorModel cm = - (DirectColorModel)ColorModel.getRGBdefault(); - - int alpha = cm.getAlpha(rgb); - int red = rand.nextInt() % 255; - int green = rand.nextInt() % 255; - int blue = rand.nextInt() % 255; - - alpha = alpha << 24; - red = red << 16; - green = green << 8; - - return alpha | red | green | blue; - } -} diff --git a/java/ImageProcessing/filters/RotateFilter.java b/java/ImageProcessing/filters/RotateFilter.java deleted file mode 100644 index 39551017a4b..00000000000 --- a/java/ImageProcessing/filters/RotateFilter.java +++ /dev/null @@ -1,358 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; - -public class RotateFilter extends SpatialFilter -{ - private double angle_; - private int rotx_, roty_; - private int rotheight_, rotwidth_; - - public RotateFilter () - { - this.angle_ = 90.0; - } - - public RotateFilter(double angle) - { - this.angle_ = angle; - } - - public String info () - { - return "Rotates an image"; - } - - public void setDimensions(int width, int height) - { - DoublePoint temp; - - rows_ = height; - columns_ = width; - - // Convert the angle into radians - double rotrad = angle_ * Math.PI / (double)180.0; - - // Compute the corner points after rotation - double center_x = (double)(columns_ - 1) / (double)2.0; - double center_y = (double)(rows_ - 1) / (double)2.0; - - // The new top left corner - temp = rotatePoint(0, 0, center_x, center_y, rotrad); - int rtl_x = (int)(temp.x_ + ((temp.x_ < 0) ? -0.5 : 0.5)); - int rtl_y = (int)(temp.y_ + ((temp.y_ < 0) ? -0.5 : 0.5)); - - // the new top right corner - temp = rotatePoint(0, rows_, center_x, center_y, rotrad); - int rtr_x = (int)(temp.x_ + ((temp.x_ < 0) ? -0.5 : 0.5)); - int rtr_y = (int)(temp.y_ + ((temp.y_ < 0) ? -0.5 : 0.5)); - - // the new bottom left corner - temp = rotatePoint(columns_, 0, center_x, center_y, rotrad); - int rbl_x = (int)(temp.x_ + ((temp.x_ < 0) ? -0.5 : 0.5)); - int rbl_y = (int)(temp.y_ + ((temp.y_ < 0) ? -0.5 : 0.5)); - - // the new bottom right corner - temp = rotatePoint(columns_, rows_, center_x, center_y, rotrad); - int rbr_x = (int)(temp.x_ + ((temp.x_ < 0) ? -0.5 : 0.5)); - int rbr_y = (int)(temp.y_ + ((temp.y_ < 0) ? -0.5 : 0.5)); - - //System.out.println(" ( " + center_x + "," + center_y + " ) "); - //System.out.println(" ( " + rtl_x + "," + rtl_y + " ) "); - //System.out.println(" ( " + rtr_x + "," + rtr_y + " ) "); - //System.out.println(" ( " + rbr_x + "," + rbr_y + " ) "); - //System.out.println(" ( " + rbl_x + "," + rbl_y + " ) "); - - // rotated bounding box - int rbbx1, rbby1; - int rbbx = rbbx1 = rtl_x; - int rbby = rbby1 = rtl_y; - - if (rtr_x < rbbx) rbbx = rtr_x; - if (rtr_x > rbbx1) rbbx1 = rtr_x; - if (rtr_y < rbby) rbby = rtr_y; - if (rtr_y > rbby1) rbby1 = rtr_y; - - if (rbl_x < rbbx) rbbx = rbl_x; - if (rbl_x > rbbx1) rbbx1 = rbl_x; - if (rbl_y < rbby) rbby = rbl_y; - if (rbl_y > rbby1) rbby1 = rbl_y; - - if (rbr_x < rbbx) rbbx = rbr_x; - if (rbr_x > rbbx1) rbbx1 = rbr_x; - if (rbr_y < rbby) rbby = rbr_y; - if (rbr_y > rbby1) rbby1 = rbr_y; - - int rbbw = rbbx1 - rbbx; - int rbbh = rbby1 - rbby; - - //System.out.println("(rbbx, rbby): " + rbbx + " " + rbby); - //System.out.println("(rbbx1, rbby1): " + rbbx1 + " " + rbby1); - //System.out.println("(rbbw, rbbh): " + rbbw + " " + rbbh); - - - //rbbx--; rbby--; rbbw+=2; rbbh+=2; - - - // Ensure we haven't increased the size of the image - - /* - int x = rbbx + rbbw - 1, y = rbby + rbbh - 1; - if (rbbx < 0) rbbx = 0; - if (rbbx > columns_ - 1 ) rbbx = columns_ - 1; - if (rbby < 0) rbby = 0; - if (rbby > rows_ - 1) rbby = rows_ - 1; - */ - - /* - - if (x < 0) x = 0; - if (x > columns_ - 1) x = columns_ - 1; - if (y < 0) y = 0; - if (y > rows_ - 1) y = rows_ - 1; - - if (x < rbbx) x = rbbx; - if (y < rbby) y = rbby; - rbbw = (x - rbbx) + 1; - rbbh = (y - rbby) + 1; - - */ - - rotx_ = rbbx; - roty_ = rbby; - rotheight_ = rbbh; - rotwidth_ = rbbw; - - //System.out.println("(rotx,roty): " + rotx_ + " " + - // roty_); - //System.out.println("(rotwidth,rotheight): " + rotwidth_ + " " + - // rotheight_); - //System.out.println("(columns,rows): " + columns_ + - // " " + rows_); - - - raster_ = new int[columns_*rows_]; - consumer.setDimensions(rotwidth_, rotheight_); - } - - - public void imageComplete(int status) - { - if (status == IMAGEERROR || status == IMAGEABORTED) - { - consumer.imageComplete(status); - System.out.println("Image Error: " + status); - return; - } - - // For each pixel in the dimensions of the rotated image, if the - // inverse rotation falls in the bounds of the original image. If - // it does, compute and store an appropriate color, otherwise skip - // it. - - System.gc(); - - double xf, yf, px, py, apx, apy; - int[] pixels = new int[rotwidth_*rotheight_]; - int ox, oy, ox1, oy1, index, pixel; - double cx = (columns_ - 1) / 2; - double cy = (rows_ - 1) / 2; - double rotrad = angle_ * Math.PI / 180.0, ang, d; - int p0r = 0, p0g = 0, p0b = 0, - p1r = 0, p1g = 0,p1b = 0, - p2r = 0, p2g = 0, p2b = 0, - p3r = 0, p3g = 0, p3b = 0, lcv, lcv2; - int rv,gv,bv, alpha; - double rd,gd,bd, p0wgt = 0, - p1wgt = 0, p2wgt = 0, p3wgt = 0, xfrac, yfrac; - - profile_timer_.start(); - - lcv = roty_ + rotheight_; - lcv2 = rotx_ + rotwidth_; - for (int y = roty_, i = 0; y < lcv; y++) - { - for (int x = rotx_; x < lcv2; x++, i++) - { - // Inverse rotate the point (x,y) - // Inlining the call to rotatePoint - xf = (double)x; - yf = (double)y; - d = Math.sqrt((xf - cx) * (xf - cx) + (yf - cy) * (yf - cy)); - - if ((xf - cx) != 0.0) - { - ang = Math.atan((cy-yf)/(xf-cx)); - if ((xf - cx) < 0) - ang += Math.PI; - } - else - { - if ((yf - cy) > 0.0) - ang = (Math.PI * 3.0) / 2; - else - ang = Math.PI / 2; - } - - xf = cx + (d * Math.cos(ang - rotrad)); - yf = cy - (d * Math.sin(ang - rotrad)); - // end inline - - // Cheat a little - if (xf < 0.0 && xf > -0.5) xf = 0.0; - if (yf < 0.0 && yf > -0.5) yf = 0.0; - - ox = (int)Math.floor(xf); - oy = (int)Math.floor(yf); - - if ((ox >= 0) && (oy >= 0) && - (ox < columns_) && (oy < rows_) ) - { - // The color will be a linear combination of the colors of - // the center pixel, its left or right neighbor, its top - // or bottom neighbor, and its corner neighbor. Which - // neighbors are used is determined by the position of - // the fractional part of xf, xy within the 1-unit square - // of the pixel. - - /* compute px,py: fractional offset from center of pixel (x.5,y.5) */ - xfrac = xf - ox; /* 0 - .9999 */ - yfrac = yf - oy; - px = ((xfrac >= .5) ? (xfrac - .5) : (-.5 + xfrac)); - py = ((yfrac >= .5) ? (yfrac - .5) : (-.5 + yfrac)); - apx = ((px < 0) ? -px : px); - apy = ((py < 0) ? -py : py); - - /* get neighbor colors: p0col, p1col, p2col, p3col */ - ox1 = ox + ((px < 0.0) ? -1 : 1); - oy1 = oy + ((py < 0.0) ? -1 : 1); - - index = oy * columns_ + ox; - pixel = raster_[index]; - alpha = (pixel >> 24) & 0xff; - p0r = (pixel >> 16) & 0xff; - p0g = (pixel >> 8) & 0xff; - p0b = pixel & 0xff; - - if (ox1 >= 0 && ox1 < columns_) - { - index = oy*columns_ + ox1; - pixel = raster_[index]; - p1r = (pixel >> 16) & 0xff; - p1g = (pixel >> 8) & 0xff; - p1b = pixel & 0xff; - p1wgt = apx * (1.0 - apy); - } - else { p1r=p1g=p1b=0; p1wgt = 0.0; } - - if (oy1 >= 0 && oy1 < rows_) - { - index = oy1*columns_ + ox; - pixel = raster_[index]; - p2r = (pixel >> 16) & 0xff; - p2g = (pixel >> 8) & 0xff; - p2b = pixel & 0xff; - p2wgt = apx * (1.0 - apy); - } - else { p2r=p2g=p2b=0; p2wgt = 0.0; } - - if (ox1 >= 0 && ox1 < columns_ && - oy1 >= 0 && oy1 < rows_) - { - index = oy1 * columns_ + ox1; - pixel = raster_[index]; - p3r = (pixel >> 16) & 0xff; - p3g = (pixel >> 8) & 0xff; - p3b = pixel & 0xff; - p3wgt = apx * (1.0 - apy); - } - else { p3r=p3g=p3b=0; p3wgt = 0.0; } - - p1wgt = p1wgt * .7; /* black art */ - p2wgt = p2wgt * .7; - p3wgt = p3wgt * .7; - - p0wgt = 1.0 - (p1wgt + p2wgt + p3wgt); - - /* okay, compute and store resulting color */ - rd = p0r * p0wgt + p1r * p1wgt + p2r * p2wgt + p3r * p3wgt; - gd = p0g * p0wgt + p1g * p1wgt + p2g * p2wgt + p3g * p3wgt; - bd = p0b * p0wgt + p1b * p1wgt + p2b * p2wgt + p3b * p3wgt; - - rv = (int) (rd + 0.5); - gv = (int) (gd + 0.5); - bv = (int) (bd + 0.5); - - if (rv < 0) rv = 0; - if (gv < 0) gv = 0; - if (bv < 0) bv = 0 ; - - if (rv > 255) rv = 255; - if (gv > 255) gv = 255; - if (bv > 255) bv = 255; - - pixels[i] = (alpha << 24) | (rv << 16) | (gv << 8) | bv; - } - } - } - - profile_timer_.stop(); - - consumer.setPixels(0, 0, rotwidth_, rotheight_, defaultRGB_, - pixels, 0, rotwidth_); - - consumer.imageComplete(status); - } - - private final static DoublePoint rotatePoint(int x, int y, - double cx, double cy, double rad) - { - /* rotate point x, y 'rad' radians around cx, cy, return rx, ry */ - double d, xf, yf, ang, rx, ry; - - xf = (double)x; - yf = (double)y; - - // d = distance from the point to the center - d = Math.sqrt((xf - cx) * (xf - cx) + (yf - cy) * (yf - cy)); - - if ((xf - cx) != 0.0) - { - // Compute the angle between the axis and the point in radians - // using the inverse tangent function. - ang = Math.atan((cy-yf)/(xf-cx)); - - // If the x value falls below the axis the angle is between - // PI and 2*PI. - if ((xf - cx) < 0) - ang += Math.PI; - } - else - { - // The point is on the positive y-axis so its angle is 3/2*PI - // I'm guessing this the cooridnate system is flipped in - // screen graphics. - if ((yf - cy) > 0.0) - ang = (Math.PI * 3.0) / 2; - else - ang = Math.PI / 2; - } - - rx = cx + (d * Math.cos(ang + rad)); - ry = cy - (d * Math.sin(ang + rad)); - - return new DoublePoint(rx, ry); - } -} - -class DoublePoint -{ - public double x_; - public double y_; - - DoublePoint(double x, double y) - { - x_ = x; - y_ = y; - } -} diff --git a/java/ImageProcessing/filters/SharpenFilter.java b/java/ImageProcessing/filters/SharpenFilter.java deleted file mode 100644 index fcb6f03c7ac..00000000000 --- a/java/ImageProcessing/filters/SharpenFilter.java +++ /dev/null @@ -1,272 +0,0 @@ -package imaging.filters; - -import java.awt.Color; -import java.awt.image.*; -import java.util.*; - -public class SharpenFilter extends SpatialFilter -{ - float percentage_ = (float)75.0; - - public SharpenFilter() - { - } - - public SharpenFilter(float percentage) - { - percentage_ = percentage; - } - - public String info () - { - return "Sharpens an image."; - } - - - public void imageComplete(int status) - { - System.out.println("Image Complete called"); - - if (status == IMAGEERROR || status == IMAGEABORTED) - { - consumer.imageComplete(status); - System.out.println("Image Error"); - return; - } - - System.gc(); - - float[] hsv = new float[3]; - int rgb, red, green, blue; - int pixel, alpha, lcv, lcv2, lcv3; - int[] pixels = new int[columns_*rows_]; - float fact, ifact, hue, sat, val, vsum; - float[] line0 = new float[columns_], - linep1 = new float[columns_], - linem1 = new float[columns_], - tmpptr; - - profile_timer_.start(); - - for (int z = 0; z < SpatialFilter.iterations_; z++) - { - fact = percentage_/(float)100.0; - ifact = (float)1.0 - fact; - - for (int x = 0; x < columns_; x++) - { - pixel = raster_[x]; - hsv = getHSV(((pixel >> 16) & 0xff), ((pixel >> 8) & 0xff), (pixel & 0xff),hsv); - line0[x] = hsv[2]; - } - - lcv = columns_ << 1; - for (int x = columns_, index = 0; x < lcv; x++, index++) - { - pixel = raster_[x]; - hsv = getHSV(((pixel >> 16) & 0xff), ((pixel >> 8) & 0xff), (pixel & 0xff),hsv); - linep1[index] = hsv[2]; - } - - lcv = columns_ - 1; - lcv2 = rows_ - 1; - for (int y = 1, i = columns_; y < lcv2; y++) - { - tmpptr = linem1; - linem1 = line0; - line0 = linep1; - linep1 = tmpptr; - - lcv3 = columns_*(y+2); - for (int x = columns_*(y+1), index= 0; x < lcv; x++, index++) - { - pixel = raster_[x]; - // Note hsv is only instantiated once - hsv = getHSV(((pixel >> 16) & 0xff), ((pixel >> 8) & 0xff), (pixel & 0xff), hsv); - linep1[index] = hsv[2]; - } - - i++; - for (int x = 1; x < lcv; x++, i++) - { - vsum = (float)0.0; - vsum = linem1[x-1] + linem1[x] + linem1[x+1] + - line0[x-1] + line0[x] + line0[x + 1] + - linep1[x-1] + linep1[x] + linep1[x + 1]; - - pixel = raster_[i]; - alpha = (pixel >> 24) & 0xff; - hsv = getHSV(((pixel >> 16) & 0xff), ((pixel >> 8) & 0xff), (pixel & 0xff), hsv); - - val = ((hsv[2] - (fact * vsum) / 9) / ifact); - if (val < 1.0) - { - if (val < 0.0) - val = (float)0.0; - } - else - val = (float)1.0; - - hsv[2] = val; - rgb = getRGB(hsv[0], hsv[1], hsv[2]); - - red = (rgb >> 16) & 0xff; - green = (rgb >> 8) & 0xff; - blue = rgb & 0xff; - - if (red < 0) red = 0; - if (green < 0) green = 0; - if (blue < 0) blue = 0 ; - - if (red > 255) red = 255; - if (green > 255) green = 255; - if (blue > 255) blue = 255; - - pixels[i] = - (alpha << 24) | (red << 16) | (green << 8) | blue; - } - i++; - } - } - - profile_timer_.stop(); - - consumer.setPixels(0, 0, columns_, rows_, defaultRGB_, pixels, 0, columns_); - - System.out.println("Finished altering image"); - consumer.imageComplete(status); - } - - - static private float[] getHSV(int red, int green, int blue, float[] hsv) - { - float rd, gd, bd, max, min, del, rc, gc, bc, hue, sat; - if (hsv == null) - hsv = new float[3]; - - /* convert RGB to HSV */ - rd = red / (float)255.0; /* rd,gd,bd range 0-1 instead of 0-255 */ - gd = green / (float)255.0; - bd = blue / (float)255.0; - - /* compute maximum of rd,gd,bd */ - if (rd >= gd) - { - if (rd >= bd) - max = rd; - else - max = bd; - } - else - { - if (gd >= bd) - max = gd; - else - max = bd; - } - - /* compute minimum of rd,gd,bd */ - if (rd<=gd) - { - if (rd<=bd) - min = rd; - else - min = bd; - } - else - { - if (gd<=bd) - min = gd; - else - min = bd; - } - - del = max - min; - hsv[2] = max; - - if (max != 0.0) - sat = (del) / max; - else - sat = (float)0.0; - - hue = -1; - - if (sat != 0.0) - { - rc = (max - rd) / del; - gc = (max - gd) / del; - bc = (max - bd) / del; - - if (rd == max) - hue = bc - gc; - else - if (gd == max) - hue = 2 + rc - bc; - else - if (bd == max) - hue = 4 + gc - rc; - - hue *= 60; - if (hue<0) - hue += 360; - } - - hsv[0] = hue; - hsv[1] = sat; - return hsv; - } - - static private int getRGB(float hue, float sat, float val) - { - int j, r, g, b; - float rd, gd, bd; - float f, p, q, t; - - /* convert HSV back to RGB */ - if (hue == -1 || sat == 0.0) - { - rd = val; gd = val; bd = val; - } - else - { - if (hue==(float)360.0) hue = (float)0.0; - hue = hue / (float)60.0; - j = (int) hue; - if (j<0) j=0; /* either hue or floor seem to go neg on some sys */ - f = hue - j; - p = val * (1-sat); // val - sat* val - q = val * (1 - (sat*f)); // val - val*sat*f - t = val * (1 - (sat*(1 - f))); - - switch (j) { - case 0: rd = val; gd = t; bd = p; break; - case 1: rd = q; gd = val; bd = p; break; - case 2: rd = p; gd = val; bd = t; break; - case 3: rd = p; gd = q; bd = val; break; - case 4: rd = t; gd = p; bd = val; break; - case 5: rd = val; gd = p; bd = q; break; - default: rd = val; gd = t; bd = p; break; /* never happen */ - } - } - r = (int)(rd * 255.0 + 0.5); - g = (int)(gd * 255.0 + 0.5); - b = (int)(bd * 255.0 + 0.5); - - return 0xff000000 | (r << 16) | (g << 8) | b; - } -} - - - - - - - - - - - - - - - diff --git a/java/ImageProcessing/filters/SpatialFilter.java b/java/ImageProcessing/filters/SpatialFilter.java deleted file mode 100644 index ad56164819e..00000000000 --- a/java/ImageProcessing/filters/SpatialFilter.java +++ /dev/null @@ -1,213 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; -import JACE.Timers.ProfileTimer; - -public class SpatialFilter extends ImageFilter implements MedFilter -{ - public SpatialFilter() - { - } - - public SpatialFilter(int[][] matrix, int degree) - { - this(matrix, degree, 1, 0); - } - - public SpatialFilter(int[][] matrix, int degree, int div_factor, int offset) - { - matrix_ = matrix; - div_factor_ = div_factor; - offset_ = offset; - degree_ = degree; - } - - public void setFilter(int[][] matrix, int degree, int div_factor) - { - matrix_ = matrix; - degree_ = degree; - div_factor_ = div_factor; - } - - public String info () - { - return "Base Filter class. Doesn't do much"; - } - - public long filterTime() - { - return profile_timer_.elapsedTime(); - } - - public static void setTimer(int internal_iterations) - { - iterations_ = internal_iterations; - } - - public void setDimensions(int width, int height) - { - rows_ = height; - columns_ = width; - raster_ = new int[width * height]; - consumer.setDimensions(width, height); - } - - public void setPixels(int x, int y, int w, int h, ColorModel model, - byte pixels[], int off, int scansize) - { - int source_offset = off; - int dest_offset = y * columns_ + x; - - for (int y_ind = 0; y_ind < h; y_ind++) - { - for (int x_ind = 0; x_ind < w; x_ind++) - { - raster_[dest_offset] = model.getRGB(pixels[source_offset] & 0xff); - dest_offset++; - source_offset++; - } - - source_offset += (scansize - w); - dest_offset += (columns_ - w); - } - } - - public void setPixels(int x, int y, int w, int h, ColorModel model, - int pixels[], int off, int scansize) - { - int source_offset = off; - int dest_offset = y * columns_ + x; - - if (model == defaultRGB_) - { - for (int yc = 0; yc < h; yc++) - { - System.arraycopy(pixels, source_offset, raster_, dest_offset, w); - source_offset += scansize; - dest_offset += columns_; - } - } - else - { - - for (int yc = 0; yc < h; yc++) - { - for (int xc = 0; xc < w; xc++) - { - raster_[dest_offset] = model.getRGB(pixels[source_offset]); - dest_offset++; - source_offset++; - } - source_offset += (scansize - w); - dest_offset += (columns_ - w); - } - } - } - - public void setColorModel(ColorModel model) - { - consumer.setColorModel(defaultRGB_); - } - - public void setHints(int hintflags) - { - consumer.setHints(TOPDOWNLEFTRIGHT - | COMPLETESCANLINES - | SINGLEPASS - | (hintflags & SINGLEFRAME)); - } - - - public void imageComplete(int status) - { - System.out.println("Image Complete called"); - - if (status == IMAGEERROR || status == IMAGEABORTED) - { - consumer.imageComplete(status); - System.out.println("Image Error"); - return; - } - - int[] pixels = new int[columns_]; - int[][] new_raster= expandRaster(); - int pixel = 0; - int red, green, blue; - int new_red = 0, new_green = 0, new_blue = 0; - int alpha; - - for (int x = raster_offset_; x < rows_; x++) - { - for (int y = raster_offset_; y < columns_; y++) - { - new_red = 0; new_green = 0; new_blue = 0; - alpha = defaultRGB_.getAlpha(new_raster[x][y]); - for (int i = 0; i < degree_; i++) - { - for (int j = 0; j < degree_; j++) - { - pixel = new_raster[x + (i - raster_offset_)][y + (j - raster_offset_)]; - - red = defaultRGB_.getRed(pixel) * matrix_[i][j]; - blue = defaultRGB_.getBlue(pixel) * matrix_[i][j]; - green = defaultRGB_.getGreen(pixel) * matrix_[i][j]; - - new_red += red; - new_green += green; - new_blue += blue; - } - } - - new_red /= div_factor_; - new_green /= div_factor_; - new_blue /= div_factor_; - - new_red = Math.min(Math.abs(new_red), 255); - new_green = Math.min(Math.abs(new_green), 255); - new_blue = Math.min(Math.abs(new_blue), 255); - - pixels[y - raster_offset_] = - (alpha << 24) | (new_red << 16) | (new_green << 8) | new_blue; - } - - consumer.setPixels(0, x - raster_offset_, columns_, 1, defaultRGB_, pixels, 0, columns_); - } - - System.out.println("Finished altering image"); - consumer.imageComplete(status); - } - - protected int[][] expandRaster() - { - int[][] new_raster; - int index = 0; - - raster_offset_ = degree_ / 2; - new_raster = new int[rows_ + raster_offset_*2][columns_ + raster_offset_*2]; - - for (int x = 0; x < rows_; x++) - { - for (int y = 0; y < columns_; y++) - { - new_raster[x + raster_offset_][y + raster_offset_] = raster_[index]; - index++; - } - } - - return new_raster; - } - - protected static final int intensity(int rd, int gn, int bl) - { - return (((int)(rd)*11 + (int)(gn)*16 + (int)(bl)*5) >> 5); - } - - protected static int iterations_ = 1; - protected static final ColorModel defaultRGB_ = ColorModel.getRGBdefault(); - protected int[][] matrix_; - protected int[] raster_; - protected int rows_ = 0, columns_ = 0; - protected int div_factor_ = 1, offset_, degree_; - protected int raster_offset_ = 0; - protected final ProfileTimer profile_timer_ = new ProfileTimer(); -} diff --git a/java/ImageProcessing/filters/SpreadFilter.java b/java/ImageProcessing/filters/SpreadFilter.java deleted file mode 100644 index c78790c9235..00000000000 --- a/java/ImageProcessing/filters/SpreadFilter.java +++ /dev/null @@ -1,130 +0,0 @@ -package imaging.filters; - -import java.awt.image.*; -import java.util.Random; - -public class SpreadFilter extends SpatialFilter -{ - private int pwidth_ = 5; - private int pheight_ = 5; - - public SpreadFilter() - { - } - - public SpreadFilter(int pwidth, int pheight) - { - pwidth_ = pwidth; - pheight_ = pheight; - } - - public String info () - { - return "Spreads an image (an effect of being under water)."; - } - - public void imageComplete(int status) - { - if (status == IMAGEERROR || status == IMAGEABORTED) - { - consumer.imageComplete(status); - System.out.println("Spread Image Error: " + status); - return; - } - - System.gc(); - - Random rand = new Random(); - int[] pixels = new int[columns_*rows_]; - int d, dx, dy, x1, y1, xrng, xoff, yrng, yoff; - int minx, maxx, miny, maxy, rdist, tmp; - - profile_timer_.start(); - - for (int z = 0; z < SpatialFilter.iterations_; z++) - { - for (int y = 0, i=0; y < rows_; y++) - { - for (int x = 0; x < columns_; x++, i++) - { - if (pwidth_ < 0) - { - d = (pwidth_ < 0 ? -pwidth_ : pwidth_); - - minx = x - d; - if (minx < 0) - minx = 0; - - maxx = x + d; - if (maxx >= columns_) - maxx = columns_ - 1; - - tmp = rand.nextInt(); - tmp = (tmp < 0 ? -tmp : tmp); - x1 = minx + tmp % ((maxx - minx) + 1); - - miny = y - d; - if (miny < 0) - miny = 0; - - maxy = y + d; - if (maxy >= rows_) - maxy = rows_ - 1; - - rdist = d - (x1 < x ? -(x1 - x) : x1 - x); - if (y - miny > rdist) - miny = (y - rdist); - if (maxy - y > rdist) - maxy = (y + rdist); - - tmp = rand.nextInt(); - tmp = (tmp < 0 ? -tmp : tmp); - y1 = miny + tmp % ((maxy - miny) + 1); - } - else - { - minx = x - pwidth_; - if (minx < 0) - minx = 0; - - maxx = x + pwidth_; - if (maxx >= columns_) - maxx = columns_ - 1; - - tmp = rand.nextInt(); - tmp = (tmp < 0 ? -tmp : tmp); - x1 = minx + tmp % ((maxx - minx) + 1); - - miny = y - pheight_; - if (miny < 0) - miny = 0; - - maxy = y + pheight_; - if (maxx >= columns_) - maxx = columns_ - 1; - - tmp = rand.nextInt(); - tmp = (tmp < 0 ? -tmp : tmp); - y1 = miny + tmp % ((maxy - miny) + 1); - } - - if (x1 >= 0 && y1 >= 0 && x1 < columns_ && y1 < rows_) - { - int pixel = raster_[i]; - int alpha = (pixel >> 24) & 0xff; - int red = (pixel >> 16) & 0xff; - int green = (pixel >> 8) & 0xff; - int blue = pixel & 0xff; - - pixels[i] = (alpha << 24) | (red << 16) | (green << 8) | blue; - } - } - } - } - - profile_timer_.stop(); - - consumer.setPixels(0, 0, columns_, rows_, defaultRGB_, pixels, 0, columns_); - consumer.imageComplete(status); - } -} diff --git a/java/ImageProcessing/filters/Timer.java b/java/ImageProcessing/filters/Timer.java deleted file mode 100644 index 609ec8aa366..00000000000 --- a/java/ImageProcessing/filters/Timer.java +++ /dev/null @@ -1,23 +0,0 @@ -package imaging.filters; - -public class Timer -{ - long start_time_; - long stop_time_; - - public void start() - { - start_time_ = System.currentTimeMillis(); - } - - public void stop() - { - stop_time_ = System.currentTimeMillis(); - } - - public String toString() - { - long total = stop_time_ - start_time_; - return "Total Time:" + total + " ms"; - } -} diff --git a/java/ImageProcessing/framework/BaseButton.java b/java/ImageProcessing/framework/BaseButton.java deleted file mode 100644 index 794670b2f3f..00000000000 --- a/java/ImageProcessing/framework/BaseButton.java +++ /dev/null @@ -1,234 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import imaging.filters.*; - -public class BaseButton extends Panel -{ - public BaseButton (String title, String description, ImageApp parent) - { - this.setLayout (new BorderLayout ()); - this.button_ = new Button (title); - this.add ("Center", this.button_); - this.resize (100, 100); - this.description_ = description; - this.parent_ = parent; - } - - public boolean mouseEnter(Event evt, int x, int y) - { - this.parent_.displayStatus (this.description_); - return true; - } - - public boolean mouseExit(Event evt, int x, int y) - { - this.parent_.displayStatus (""); - return true; - } - - protected ImageApp parent_; - private String description_; - private Button button_; -} - -class URLDialogButton extends BaseButton -{ - public URLDialogButton (String title, String desc, ImageApp parent) - { - super (title, desc, parent); - this.openURLFrame_ = new LoadURLFrame ("Open URL <2>", this.parent_); - } - - public boolean action (Event e, Object arg) - { - this.openURLFrame_.show (); - return true; - } - private LoadURLFrame openURLFrame_; -} - -// ****************** -// Should continue to remember the password -// ****************** -class SaveButton extends BaseButton -{ - public SaveButton (String title, String desc, ImageApp parent) - { - super (title, desc, parent); - this.openURLFrame_ = new SaveURLFrame ("Save Image <2>", this.parent_); - } - - public boolean action (Event e, Object arg) - { - this.openURLFrame_.show (); - return true; - } - private SaveURLFrame openURLFrame_; -} - -class ReloadButton extends BaseButton -{ - public ReloadButton (String title, String desc, ImageApp parent) - { - super (title, desc, parent); - } - - public boolean action (Event e, Object arg) - { - this.parent_.reloadFilters (); - return true; - } -} - -class ApplyButton extends BaseButton -{ - public ApplyButton (String title, String desc, ImageApp parent) - { - super (title, desc, parent); - } - - public boolean action (Event e, Object arg) - { - this.parent_.apply (); - return true; - } -} - -class ResetButton extends BaseButton -{ - public ResetButton (String title, String desc, ImageApp parent) - { - super (title, desc, parent); - } - - public boolean action (Event e, Object arg) - { - this.parent_.resetImage (); - return true; - } -} - -class ZoomInButton extends BaseButton -{ - public ZoomInButton (String title, String desc, ImageApp parent) - { - super (title, desc, parent); - } - - public boolean action (Event e, Object arg) - { - this.parent_.zoomFactor (1.6); - return true; - } -} - -class ZoomOutButton extends BaseButton -{ - public ZoomOutButton (String title, String desc, ImageApp parent) - { - super (title, desc, parent); - } - - public boolean action (Event e, Object arg) - { - this.parent_.zoomFactor (0.625); - return true; - } -} - - -class AboutButton extends BaseButton -{ - public AboutButton (String title, String desc, ImageApp parent) - { - super (title, desc, parent); - } - - public boolean action (Event e, Object arg) - { - DialogManager.popDialog (DialogType.ABOUT, null); - return true; - } -} - -class HelpButton extends BaseButton -{ - public HelpButton (String title, String desc, ImageApp parent) - { - super (title, desc, parent); - } - - public boolean action (Event e, Object arg) - { - DialogManager.popDialog (DialogType.HELP, null); - return true; - } -} - -class ChoicePanel extends Panel -{ - public ChoicePanel (String desc, ImageApp parent) - { - this.description_ = desc; - this.parent_ = parent; - - this.loadFilters (); - // Set the layout of the Choice Panel. Note that the Choice Panel - // holds the choice button of filters. - this.setLayout (new FlowLayout ()); - this.resize (150, 100); - } - - public void choice (Choice choice) - { - this.choice_ = choice; - } - - public Choice choice () - { - return this.choice_; - } - - public void loadFilters () - { - // First remove all components of the panel including the - // choices of filters - this.removeAll (); - - // Now create new choices - this.choice_ = this.parent_.getFilters (); - - // Add the choices to our choice panel - this.add (this.choice_); - } - - public boolean mouseEnter(Event evt, int x, int y) - { - MedFilter filter = null; - String displayString = null; - String filterName = this.choice_.getSelectedItem (); - - if (filterName.compareTo ("Filters:") == 0) - displayString = "No filter selected"; - else - { - filter = (MedFilter) this.parent_.getFilter (filterName); - displayString = filter.info (); - } - this.parent_.displayStatus (displayString); - // this.parent_.displayStatus (this.description_); - return true; - } - - public boolean mouseExit(Event evt, int x, int y) - { - this.parent_.displayStatus (""); - return true; - } - - private Choice choice_; - private ImageApp parent_; - String description_; -} - diff --git a/java/ImageProcessing/framework/BenchmarkApplet.java b/java/ImageProcessing/framework/BenchmarkApplet.java deleted file mode 100644 index ac125a1d9de..00000000000 --- a/java/ImageProcessing/framework/BenchmarkApplet.java +++ /dev/null @@ -1,622 +0,0 @@ -package imaging.framework; - -import JACE.Timers.ProfileTimer; -import imaging.filters.*; -import java.awt.*; -import java.awt.image.*; -import java.applet.*; -import java.net.*; -import java.util.*; -import java.io.*; -import gjt.*; - -public class BenchmarkApplet extends Applet implements Runnable -{ - public static final Font GLOBAL_FONT = new Font("Dialog", Font.BOLD, 10); - private static final String NEW_LINE = System.getProperty("line.separator"); - private static final String WELCOME = "Welcome to MedJava Image Processing Benchmarking Tool"; - private static final String COPYRIGHT = "(c) 1997 Distributed Object Computing Group, Washington Univesity"; - private static final String ABORT = "Image Processing Tests Aborted"; - private static final String STOP = "Stop"; - private static final String START= "Start"; - private static final String CLEAR= "Clear"; - private static final String RANDOM= "Create Random Image"; - private static final int INTERNAL_ITERATIONS = 10; - private static final int TRIALS = 1; - - private List images_, filters_; - private TextArea console_; - private TextField new_image_; - private Button start_button_; - private Button stop_button_; - private Button clear_button_; - private Button random_button_; - private ButtonPanel button_panel_ = new ButtonPanel(); - private Hashtable filter_table_ = new Hashtable(); - private Hashtable image_table_ = new Hashtable(); - private Thread benchmarker_; - private long elapsed_time_; - private SpatialFilter filter_; - private Object monitor_ = new Object(); - - public void init() - { - Panel control_panel = new Panel(); - Panel sub_panel1 = new Panel(); - Panel filter_panel = new Panel(); - Panel image_panel = new Panel(); - Label image_panel_label = new Label("Images"); - Label filter_panel_label = new Label("Filters"); - - new_image_ = new TextField(); - console_ = new TextArea(); - images_ = new List(); - filters_ = new List(); - - console_.setEditable(false); - images_.setMultipleSelections(true); - filters_.setMultipleSelections(true); - console_.setFont(GLOBAL_FONT); - images_.setFont(GLOBAL_FONT); - filters_.setFont(GLOBAL_FONT); - image_panel_label.setFont(GLOBAL_FONT); - filter_panel_label.setFont(GLOBAL_FONT); - - console_.appendText(WELCOME + NEW_LINE); - console_.appendText(COPYRIGHT + NEW_LINE); - - image_panel.setLayout(new BorderLayout()); - image_panel.add("North", image_panel_label); - image_panel.add("Center", images_); - image_panel.add("South", new_image_); - - filter_panel.setLayout(new BorderLayout()); - filter_panel.add("North", filter_panel_label); - filter_panel.add("Center", filters_); - - sub_panel1.setLayout(new GridLayout(1, 2, 5, 5)); - sub_panel1.add(filter_panel); - sub_panel1.add(image_panel); - - control_panel.setLayout(new GridLayout(2, 1, 5, 5)); - control_panel.add(sub_panel1); - control_panel.add(console_); - - setLayout(new BorderLayout()); - - stop_button_ = button_panel_.add(STOP); - start_button_ = button_panel_.add(START); - clear_button_ = button_panel_.add(CLEAR); - random_button_ = button_panel_.add(RANDOM); - - stop_button_.disable(); - add("Center", control_panel); - add("South", button_panel_); - - getFilters(); - getImages(); - } - - synchronized public void run() - { - Image image; - String image_name, filter_name; - int image_height, image_width; - String[] image_list = images_.getSelectedItems(); - String[] filter_list = filters_.getSelectedItems(); - ImageProducer image_source; - FilteredImageSource filtered_image; - // BenchmarkFrame bframe = BenchmarkFrame.instance(); - - double cumulative_time; - double best_time; - - SpatialFilter.setTimer(INTERNAL_ITERATIONS); - console_.appendText(NEW_LINE); - console_.appendText("Benchmark tests: [mem=" + - Runtime.getRuntime().freeMemory() +"/" + - Runtime.getRuntime().totalMemory() +"]" - + NEW_LINE); - - for (int i = 0; i < image_list.length; i++) - { - - image_name = image_list[i]; - image = (Image)image_table_.get(image_name); - - image_width = image.getWidth(this); - image_height = image.getHeight(this); - - console_.appendText("Begining tests for image " + image_name); - console_.appendText(" (size " + image_width + "x" + image_height + - " = " + image_height*image_width*4 + " bytes )"); - console_.appendText(NEW_LINE); - - console_.appendText(NEW_LINE + " ********** " + NEW_LINE); - // bframe.init("Begining tests for image " + image_name, image, image_width, image_height); - - // if (! bframe.isShowing()) - // bframe.show(); - - for (int j = 0; j < filter_list.length; j++) - { - filter_name = filter_list[j]; - filter_ = (SpatialFilter)filter_table_.get(filter_name); - - if (filter_ == null) - System.err.println(filter_name + " is null"); - - best_time = Double.MAX_VALUE; - cumulative_time = 0; - image_source = image.getSource(); - filtered_image = new FilteredImageSource(image.getSource(), filter_); - - for (int l = 0; l < TRIALS; l++) - { - elapsed_time_ = 0; - prepareImage(createImage(filtered_image), this); - - try - { - // synchronized(monitor_) - // { - while (elapsed_time_ == 0) - { - System.out.println("Waiting for image loading to complete."); - // monitor_.wait(); - wait(); - } - - System.out.println("Image loading has completed."); - // } - } - catch(Exception excp) - { - System.out.println(excp); - stop(); - } - - cumulative_time = (double)elapsed_time_ / (double)INTERNAL_ITERATIONS; - System.out.println(image_name + " " + filter_name + " " + elapsed_time_); - - if (best_time > cumulative_time) - best_time = cumulative_time; - } - - console_.appendText(filter_name + ": best time from " + - TRIALS + " trials of " + INTERNAL_ITERATIONS + - " iterations equals: " + best_time + " ms"); - console_.appendText(NEW_LINE); - Thread.yield(); - } - - console_.appendText(NEW_LINE); - } - - console_.appendText("Tests concluded." + NEW_LINE); - - // if (bframe.isShowing()) - // bframe.hide(); - - stop_button_.disable(); - start_button_.enable(); - } - - synchronized public boolean imageUpdate(Image img, int infoflags, int x, int y, - int width, int height) - { - System.out.println("Image Update called"); - - boolean return_value = false; - try - { - if ((infoflags & ALLBITS) != 0 || - (infoflags & SOMEBITS) != 0) - { - System.out.println("notify called" + width + " " + height); - elapsed_time_ = filter_.filterTime(); - return_value = true; - // monitor_.notify(); - notifyAll(); - } - else if ((infoflags & ImageObserver.ABORT) != 0 || - (infoflags & ERROR) != 0) - { - System.out.println("image error!"); - // stop(); - return_value = true; - } - } - catch(SecurityException excp) - { - System.err.println(excp); - } - - return return_value; - } - - public void stop() - { - try - { - if (benchmarker_.isAlive()) - { - BenchmarkFrame bframe = BenchmarkFrame.instance(); - - if (bframe.isShowing()) - bframe.hide(); - - System.out.println("Stopping tests..."); - benchmarker_.stop(); - console_.appendText(NEW_LINE + ABORT + NEW_LINE); - } - - start_button_.enable(); - stop_button_.disable(); - } - catch(SecurityException exception) - { - console_.appendText(NEW_LINE + "Stop Failed." + NEW_LINE); - } - } - - public boolean action(Event evt, Object what) - { - if (what.equals(START)) - { - boolean proceed = ! (benchmarker_ != null && benchmarker_.isAlive()); - - stop_button_.enable(); - - if (proceed && - images_.getSelectedIndexes() != null && - filters_.getSelectedIndexes() != null) - { - System.out.println("Starting tests..."); - start_button_.disable(); - benchmarker_ = new Thread(this); - benchmarker_.setPriority(Math.min(Thread.currentThread().getPriority() + 2, - Thread.MAX_PRIORITY - 1)); - benchmarker_.start(); - } - } - else if (what.equals(STOP)) - { - stop(); - } - else if (what.equals(CLEAR)) - { - console_.setText(""); - console_.appendText(WELCOME + NEW_LINE); - console_.appendText(COPYRIGHT + NEW_LINE); - } - else if (what.equals(RANDOM)) - { - RandomImageDialog.instance(this).show(); - } - else if (evt.target == new_image_) - { - getSingleImage(new_image_.getText()); - } - - - return true; - } - - private void getSingleImage(String image_url) - { - Image image; - MediaTracker tracker = new MediaTracker(this); - - try - { - image = getImage(new URL(image_url)); - tracker.addImage(image, 0); - tracker.waitForID(0); - - if (image != null) - { - int index = image_url.lastIndexOf('/'); - - if (index != -1) - image_url = image_url.substring(index + 1); - - image_table_.put(image_url, image); - images_.addItem(image_url); - } - } - catch(MalformedURLException e) - { - System.err.println(e); - } - catch(InterruptedException excp) - { - System.err.println(excp); - } - - } - - private void getImages() - { - Image image; - String image_list = getParameter("images"), image_url; - StringTokenizer str_tok = new StringTokenizer(image_list, ","); - - while (str_tok.hasMoreTokens()) - { - image_url = str_tok.nextToken(); - getSingleImage(image_url); - } - } - - private void getFilters() - { - URL url; - Object download; - String config_file; - String configInfo= null; - Choice choice = new Choice (); - ImageFilter filter; - - config_file = getParameter ("configFile"); - - if (config_file == null) - config_file = "http://www.cs.wustl.edu/~pjain/java/ACE_wrappers/java/ImageProcessing/framework/filter.conf"; - - try - { - System.out.println ("Configuration File: " + config_file); - // Create a new URL - url = new URL (config_file); - - // Get the input stream and pipe it to a DataInputStream - DataInputStream iStream = new DataInputStream (url.openStream ()); - - // Create a buffer to hold all the data we get - StringBuffer tempBuf = new StringBuffer (); - // Keep reading the data until we are done - String tempString = iStream.readLine (); - while (tempString != null) - { - tempBuf.append (tempString); - tempBuf.append (" "); - tempString = iStream.readLine (); - } - - configInfo = tempBuf.toString (); - System.out.println(configInfo); - - if (configInfo != null) - { - StringTokenizer tokens = new StringTokenizer (configInfo); - String fullFilterName = null; - String filterName = null; - // Now parse the string, picking up filter names. Use these - // names to load the actual filters as well add new choices to - // the filter choices. - while (tokens.hasMoreTokens ()) - { - // Get the next token - fullFilterName = tokens.nextToken (); - filterName = this.extractFilterName (fullFilterName); - - System.out.println ("Loading: " + fullFilterName); - // Load the filter class - Class c = Class.forName (fullFilterName); - // Class c = this.filterRepository_.load (filter); - - filter = (ImageFilter)c.newInstance(); - - if (filter instanceof SpatialFilter) - { - // Add the filter to the Filter Repository - filter_table_.put(filterName, filter); - - // Add filter name to the list of filter choices - filters_.addItem (filterName); - } - } - } - } - catch (Exception e) - { - System.err.println ("Filter not found: " + e); - } - } - - private String extractFilterName (String s) - { - String filterName = null; - StringTokenizer tokens = new StringTokenizer (s, "."); - while (tokens.hasMoreTokens ()) - filterName = tokens.nextToken (); - return filterName; - } - - public void generateRandomImage(String name, int width, int height) - { - Image image = createImage(width, height); - Graphics g = image.getGraphics(); - FilteredImageSource filtered_image; - - if (g != null) - { - ImageFilter filter = new RandomizeFilter(); - g.fillRect(0, 0, width, height); - filtered_image = new FilteredImageSource(image.getSource(), filter); - image_table_.put(name, createImage(filtered_image)); - images_.addItem(name); - } - } -} - -class RandomImageDialog extends Frame -{ - private static String GENERATE = "Generate"; - private static String CANCEL = "Cancel"; - - private TextField name_ = new TextField(30), - width_ = new TextField(5), - height_= new TextField(5); - private BenchmarkApplet applet_; - private Button generate_button_; - private Button cancel_button_; - private ButtonPanel button_panel_ = new ButtonPanel(); - - private static RandomImageDialog instance_; - - public static RandomImageDialog instance(BenchmarkApplet applet) - { - if (instance_ == null) - instance_ = new RandomImageDialog(applet); - - return instance_; - } - - protected RandomImageDialog(BenchmarkApplet applet) - { - super("Generate Random Image"); - applet_ = applet; - - Panel controls = new Panel(); - GridBagLayout gb = new GridBagLayout(); - GridBagConstraints gc = new GridBagConstraints(); - Label width = new Label("Width: "), - height = new Label("Height: "), - name = new Label("Name: "); - - reshape (0, 0, 300, 200); - - controls.setLayout(gb); - gc.gridx = 0; - gc.gridy = 0; - gc.gridwidth = 1; - gc.insets = new Insets(5,5,5,5); - gc.anchor = GridBagConstraints.WEST; - width.setFont(BenchmarkApplet.GLOBAL_FONT); - gb.setConstraints(width, gc); - controls.add(width); - - gc.gridx = 1; - gc.anchor = GridBagConstraints.CENTER; - gc.fill = GridBagConstraints.HORIZONTAL; - gb.setConstraints(width_, gc); - controls.add(width_); - - gc.gridx = 2; - gc.anchor = GridBagConstraints.WEST; - gc.fill = GridBagConstraints.NONE; - height.setFont(BenchmarkApplet.GLOBAL_FONT); - gb.setConstraints(height, gc); - controls.add(height); - - gc.gridx = 3; - gc.anchor = GridBagConstraints.CENTER; - gc.fill = GridBagConstraints.HORIZONTAL; - gb.setConstraints(height_, gc); - controls.add(height_); - - gc.gridx = 0; - gc.gridy = 1; - gc.gridwidth = 1; - gc.fill = GridBagConstraints.NONE; - gc.anchor = GridBagConstraints.WEST; - name.setFont(BenchmarkApplet.GLOBAL_FONT); - gb.setConstraints(name, gc); - controls.add(name); - - gc.gridx = 1; - gc.gridwidth = GridBagConstraints.REMAINDER; - gc.anchor = GridBagConstraints.CENTER; - gc.fill = GridBagConstraints.HORIZONTAL; - gb.setConstraints(name_, gc); - controls.add(name_); - - setLayout(new BorderLayout()); - generate_button_ = button_panel_.add(GENERATE); - cancel_button_ = button_panel_.add(CANCEL); - add("Center", controls); - add("South", button_panel_); - - } - - public boolean action(Event evt, Object what) - { - if (what.equals(GENERATE)) - { - String width = width_.getText(), - height = height_.getText(), - name = name_.getText(); - - try - { - int width_num = Integer.parseInt(width), - height_num = Integer.parseInt(height); - - applet_.generateRandomImage(name, width_num, height_num); - dispose(); - } - catch(NumberFormatException nfe) - { - width_.setText(""); - height_.setText(""); - } - } - else if (what.equals(CANCEL)) - dispose(); - - return true; - } -} - -class BenchmarkFrame extends Frame -{ - private String desc_; - private Image image_; - private int height_, width_; - private static BenchmarkFrame instance_; - private static final Font FONT = new Font("Dialog", Font.BOLD, 12); - - public static BenchmarkFrame instance() - { - if (instance_ == null) - instance_ = new BenchmarkFrame(); - - return instance_; - } - - public void init(String desc, Image image, int width, int height) - { - reshape(0, 0, width, height + 50); - setImage(desc, image); - } - - public void setImage(String desc, Image image) - {/* - try - { - MediaTracker tracker = new MediaTracker(this); - tracker.addImage(image, 0); - tracker.waitForID(0); - } - catch(InterruptedException excp) - { - } - */ - desc_ = desc; - image_ = image; - } - - public void paint(Graphics g) - { - g.setColor(Color.black); - g.setFont(FONT); - g.drawImage(image_, 0, 50, this); - g.drawString(desc_, 5, 40); - } - - protected BenchmarkFrame() - { - super("Benchmark Frame"); - } -} diff --git a/java/ImageProcessing/framework/DialogManager.java b/java/ImageProcessing/framework/DialogManager.java deleted file mode 100644 index cca0c037af1..00000000000 --- a/java/ImageProcessing/framework/DialogManager.java +++ /dev/null @@ -1,277 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import java.awt.image.*; -import java.applet.*; -import java.util.*; -import java.io.*; -import java.net.*; - -class DialogManager -{ - public static void initialize (Applet parent) - { - codeBase_ = parent.getCodeBase ().toString (); - aboutFrame_ = new AboutFrame (); - helpFrame_ = new HelpFrame (codeBase_); - } - - public static void popDialog (int type, String message) - { - Frame frame = null; - - switch (type) - { - case DialogType.ABOUT: - aboutFrame_.show (); - break; - case DialogType.HELP: - helpFrame_.show (); - break; - case DialogType.MALFORMED_URL: - case DialogType.NOT_SUPPORTED: - case DialogType.URL_NOT_FOUND: - frame = new MessageFrame ("Error", message); - break; - case DialogType.NOT_YET_IMPLEMENTED: - frame = new MessageFrame ("", message); - break; - } - Dimension d = Toolkit.getDefaultToolkit ().getScreenSize (); - frame.move ((d.width - frame.size ().width)/2, - (d.height - frame.size ().height)/2); - frame.show (); - } - - private static String codeBase_ = ""; - private static AboutFrame aboutFrame_; - private static HelpFrame helpFrame_; -} - -class MessageFrame extends Frame -{ - public MessageFrame (String title, String message) - { - super (title); - - this.resize (message.length () * 8, 100); - this.setLayout (new BorderLayout ()); - - this.text_ = new TextField (message); - this.text_.setEditable (false); - - Panel okButtonPanel = new Panel (); - okButtonPanel.add (this.okButton_); - okButtonPanel.resize (100, 100); - - this.add ("Center", this.text_); - this.add ("South", okButtonPanel); - } - - public boolean handleEvent (Event evt) - { - if (evt.id == Event.WINDOW_DESTROY) - { - this.dispose (); - return true; - } - return super.handleEvent (evt); - } - - // Handle all action events - public boolean action (Event e, Object arg) - { - if (e.target instanceof Button) - { - if (e.target == this.okButton_) - { - this.dispose (); - } - return true; - } - else - return false; - } - - private Button okButton_ = new Button (" ok "); - private TextField text_ = null; -} - -class AboutFrame extends Frame -{ - public AboutFrame () - { - super ("About"); - this.resize (300,300); - this.setLayout (new BorderLayout ()); - - Panel okButtonPanel = new Panel (); - okButtonPanel.add (this.okButton_); - AboutFrameTextPanel textPanel = new AboutFrameTextPanel (); - - this.add ("Center", textPanel); - this.add ("South", okButtonPanel); - } - - // Handle window destroy events - public boolean handleEvent (Event evt) - { - if (evt.id == Event.WINDOW_DESTROY) - { - this.hide (); - return true; - } - return super.handleEvent (evt); - } - - // Handle all action events - public boolean action (Event e, Object arg) - { - if (e.target instanceof Button) - { - if (e.target == this.okButton_) - { - this.hide (); - } - return true; - } - else - return false; - } - private Button okButton_ = new Button (" ok "); -} - -class AboutFrameTextPanel extends Panel -{ - public void paint (Graphics g) - { - int width = this.size ().width; - int height = this.size ().height; - - g.clearRect (0, 0, width, height); - this.setBackground (Color.cyan); - - // First draw the title - g.setFont (new Font ("TimesRoman", Font.BOLD | Font.ITALIC, 48)); - FontMetrics fontMetrics = g.getFontMetrics (); - int x = (width - fontMetrics.stringWidth (title_))/2; - int y = 100; - - Color color = g.getColor (); - g.setColor (Color.orange); - g.drawString(title_, x+2, y+2); - g.setColor (color); - g.drawString(title_, x, y); - - // Then draw author's name - g.setFont (new Font ("TimesRoman", Font.ITALIC, 24)); - fontMetrics = g.getFontMetrics (); - x = (width - fontMetrics.stringWidth (by_))/2; - y += 50; - g.drawString(by_, x, y); - - x = (width - fontMetrics.stringWidth (author_))/2; - y += 50; - g.drawString(author_, x, y); - - // Finally draw other information -- version number etc. - g.setFont (new Font ("TimesRoman", Font.ITALIC, 18)); - fontMetrics = g.getFontMetrics (); - x = (width - fontMetrics.stringWidth (info_))/2; - y += 50; - g.drawString(info_, x, y); - } - - private String title_ = "MedJava"; - private String by_ = "by"; - private String author_ = "Prashant Jain"; - private String info_ = "Version 1.0"; -} - -class HelpFrame extends Frame -{ - public HelpFrame (String codeBase) - { - super ("Help"); - this.setBackground (Color.white); - this.text_.setEditable (false); - Font defaultFont = new Font ("TimesRoman", Font.PLAIN, 14); - this.text_.setFont (defaultFont); - - try - { - URL url = new URL (codeBase + "../ImageProcessing/framework/help.conf"); - String delim = "\n"; - - // Get the input stream and pipe it to a DataInputStream - DataInputStream iStream = new DataInputStream (url.openStream ()); - - // Keep reading the data until we are done - String tempString = iStream.readLine (); - while (tempString != null) - { - if (tempString.startsWith ("<START>")) - delim = ""; - else if (tempString.startsWith ("<END>")) - delim = "\n"; - else if (tempString.startsWith ("<TAB>")) - this.text_.appendText ("\t"); - else if (tempString.startsWith ("<P>")) - this.text_.appendText ("\n"); - else - { - this.text_.appendText (tempString); - this.text_.appendText (delim); - } - tempString = iStream.readLine (); - } - } - catch (MalformedURLException e) - { - System.err.println (e); - } - catch (IOException e) - { - System.err.println (e); - } - - this.resize (600,700); - this.setLayout (new BorderLayout ()); - - Panel okButtonPanel = new Panel (); - okButtonPanel.add (this.okButton_); - this.add ("South", okButtonPanel); - this.add ("Center", this.text_); - } - - // Handle window destroy events - public boolean handleEvent (Event evt) - { - if (evt.id == Event.WINDOW_DESTROY) - { - this.hide (); - return true; - } - return super.handleEvent (evt); - } - - // Handle all action events - public boolean action (Event e, Object arg) - { - if (e.target instanceof Button) - { - if (e.target == this.okButton_) - { - this.hide (); - } - return true; - } - else - return false; - } - - private Vector helpInfo_ = new Vector (); - private Button okButton_ = new Button (" ok "); - private TextArea text_ = new TextArea (); -} - diff --git a/java/ImageProcessing/framework/DialogType.java b/java/ImageProcessing/framework/DialogType.java deleted file mode 100644 index c95372c08e1..00000000000 --- a/java/ImageProcessing/framework/DialogType.java +++ /dev/null @@ -1,11 +0,0 @@ -package imaging.framework; - -public class DialogType -{ - public static final int ABOUT = 0; - public static final int MALFORMED_URL = 1; - public static final int URL_NOT_FOUND = 2; - public static final int NOT_SUPPORTED = 3; - public static final int HELP = 4; - public static final int NOT_YET_IMPLEMENTED = 10; -} diff --git a/java/ImageProcessing/framework/FileBrowser.java b/java/ImageProcessing/framework/FileBrowser.java deleted file mode 100644 index 27245b1f2f4..00000000000 --- a/java/ImageProcessing/framework/FileBrowser.java +++ /dev/null @@ -1,173 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import java.awt.image.*; -import java.net.*; -import java.applet.*; -import gjt.Separator; -import gjt.ComponentScroller; - -class FileNode extends HierarchyAdapter -{ - public FileNode (String name, - Icon icon, - boolean root, - ImageApp app) - { - super (name, icon, root); - this.app_ = app; - } - - public FileNode (String name, - Icon icon, - ListFiles list, - ImageApp app) - { - super (name, icon); - this.list_ = list; - this.app_ = app; - } - - public ImageApp app () - { - return this.app_; - } - - public void handleEvent () - { - String s = null; - String pString = ""; - Hierarchy p = this.getHierarchyParent (); - - while (p != null) - { - pString = p.getName () + pString; - p = p.getHierarchyParent (); - } - - if (pString.endsWith ("/")) - s = "http://" + pString + this.getName (); - else - s = "http://" + pString + "/" + this.getName (); - - System.out.println ("Opening: " + s); - - // If list is null, then it is a file, else it is a directory and - // use list to get the rest of the directory. - if (this.list_ == null) - this.app_.openURL (s); // It is a file - else - this.list_.listFiles (s, this); // It is a directory. - } - - private ListFiles list_ = null; - private ImageApp app_ = null; -} - -class BrowserPanel extends Panel -{ - public BrowserPanel (ImageApp parent) - { - this.resize (300, 300); - this.parent_ = parent; - this.setLayout (new BorderLayout ()); - } - - public int initialize (String url, ListFiles list) - { - String directory = null; - int index = -1; - - String pString = list.stripProtocolHeader (url); - if (!pString.endsWith ("/")) - pString = pString + "/"; - - try - { - Icon dirIcon = new Icon (this.parent_.getCodeBase () + - "../ImageProcessing/framework/" + - "file03.gif", (Applet) this.parent_); - System.out.println (this.parent_.getCodeBase () + - "../ImageProcessing/framework/" + - "file03.gif"); - this.root_ = new FileNode (pString, - dirIcon, true, this.parent_); - } - catch (MalformedURLException e) - { - } - - int count = list.listFiles (url, this.root_); - // System.out.println ("Count: " + count); - if (count > 0) - { - // Add the root to the component scroller and then add the - // component scroller to the panel. - this.scroller_ = new ComponentScroller (this.root_); - this.add ("Center", this.scroller_); - } - return count; - } - - private FileNode root_ = null; - private ImageApp parent_; - private ComponentScroller scroller_; -} - -class FileBrowser extends Frame -{ - public FileBrowser (String title, ImageApp parent) - { - super (title); - this.resize (300, 300); - this.browser_ = new BrowserPanel (parent); - this.setLayout (new BorderLayout ()); - - this.cancelButton_ = new Button (" cancel "); - Panel buttonPanel = new Panel (); - buttonPanel.add (this.cancelButton_); - buttonPanel.resize (100, 100); - - Panel southPanel = new Panel (); - southPanel.setLayout (new BorderLayout ()); - southPanel.add ("North", new Separator ()); - southPanel.add ("South", buttonPanel); - this.add ("South", southPanel); - this.add ("Center", this.browser_); - } - - public int initialize (String url, ListFiles list) - { - return this.browser_.initialize (url, list); - } - - // Handle window destroy events - public boolean handleEvent (Event evt) - { - if (evt.id == Event.WINDOW_DESTROY) - { - this.dispose (); - return true; - } - return super.handleEvent (evt); - } - - // Handle all action events - public boolean action (Event e, Object arg) - { - if (e.target instanceof Button) - { - if (e.target == this.cancelButton_) - { - this.dispose (); - } - validate (); - return true; - } - else - return false; - } - - private Button cancelButton_;; - private BrowserPanel browser_; -} diff --git a/java/ImageProcessing/framework/FilePanel.java b/java/ImageProcessing/framework/FilePanel.java deleted file mode 100644 index f8ffc7dbca8..00000000000 --- a/java/ImageProcessing/framework/FilePanel.java +++ /dev/null @@ -1,161 +0,0 @@ -package imaging.framework; - -import java.awt.*; - -// Create a panel for all the buttons -class FilePanel extends Panel -{ - FilePanel (ImageApp parent) - { - this.parent_ = parent; - - this.setLayout (new GridLayout (2, 1)); - - // First create all the buttons - this.URLDialogButton_ = new URLDialogButton ("Open URL", "Download an image", this.parent_); - this.saveButton_ = new SaveButton ("Save", "Upload an image", this.parent_); - - // Place the created buttons in the panel - this.add (this.URLDialogButton_); - this.add (this.saveButton_); - - // Disable the save button for now - this.disableSaveButton (); - this.resize (400, 400); - } - - public void enableSaveButton () - { - this.saveButton_.enable (); - } - - public void disableSaveButton () - { - this.saveButton_.disable (); - } - - // All the created buttons - private URLDialogButton URLDialogButton_; - private SaveButton saveButton_; - - private ImageApp parent_; -} - -// Create a panel for all the buttons -class ResetPanel extends Panel -{ - ResetPanel (ImageApp parent) - { - this.parent_ = parent; - - this.setLayout (new GridLayout (2, 1)); - - // First create all the buttons - this.reloadButton_ = new ReloadButton ("Reload Filters", "Reload all filters", this.parent_); - - // ********************** - // Disable this until it works - // ********************** - this.reloadButton_.disable(); - - - this.resetButton_ = new ResetButton ("Reset", "Reset the image", this.parent_); - - - // Place the created buttons in the panel - this.add (this.resetButton_); - this.add (this.reloadButton_); - - this.resize (400, 400); - } - - // All the created buttons - private ReloadButton reloadButton_; - private ResetButton resetButton_; - - private ImageApp parent_; -} - - -class ZoomPanel extends Panel -{ - ZoomPanel (ImageApp parent) - { - this.parent_ = parent; - - this.setLayout (new GridLayout (2, 1)); - - // First create the two zoom buttons - this.zoomInButton_ = new ZoomInButton ("<< Zoom in", "Zoom into the image", this.parent_); - this.zoomOutButton_ = new ZoomOutButton ("Zoom out >>", "Zoom out of the image", this.parent_); - - // Now add the buttons to the panel - this.add (this.zoomInButton_); - this.add (this.zoomOutButton_); - - this.resize (100, 100); - } - - private ZoomInButton zoomInButton_; - private ZoomOutButton zoomOutButton_; - - private ImageApp parent_; -} - - -class FilterPanel extends Panel -{ - FilterPanel (ImageApp parent) - { - this.parent_ = parent; - - this.setLayout (new GridLayout (2, 1)); - this.applyButton_ = new ApplyButton ("Apply", "Apply the selected filter", this.parent_); - - // Set the layout of the Choice Panel. Note that the Choice Panel - // holds the choice button of filters. - this.choicePanel_ = new ChoicePanel ("Select filter", this.parent_); - - this.add (this.applyButton_); - this.add (this.choicePanel_); - this.resize (200,200); - } - - public Choice choice () - { - return this.choicePanel_.choice (); - } - - public void loadFilters () - { - this.choicePanel_.loadFilters (); - } - - private ChoicePanel choicePanel_; - private ApplyButton applyButton_; - private ImageApp parent_; -} - -class HelpPanel extends Panel -{ - HelpPanel (ImageApp parent) - { - this.parent_ = parent; - - this.setLayout (new GridLayout (2, 1)); - - this.aboutButton_ = new AboutButton ("About", "About the applet", this.parent_); - this.helpButton_ = new HelpButton ("Help", "Help on how to use the applet", this.parent_); - - // Now add the buttons to the panel - this.add (this.aboutButton_); - this.add (this.helpButton_); - - this.resize (100, 100); - } - - private AboutButton aboutButton_; - private HelpButton helpButton_; - - private ImageApp parent_; -} diff --git a/java/ImageProcessing/framework/FilterTest.java b/java/ImageProcessing/framework/FilterTest.java deleted file mode 100644 index b1e33482be9..00000000000 --- a/java/ImageProcessing/framework/FilterTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import java.awt.image.*; -import imaging.filters.Timer; - -public class FilterTest -{ - public static void main(String[] args) - { - Timer timer = new Timer(); - ImageProcessor ip = new ImageProcessor(); - ImageFilterFactory iff = new ImageFilterFactory(); - Frame frame = new Frame("Rotate Example"); - Toolkit tk = Toolkit.getDefaultToolkit(); - Dimension d = tk.getScreenSize(); - Image old_image = tk.getImage("myphoto.gif"), image; - int image_x, image_y, x = 50, y = 50; - Graphics g; - - frame.reshape(d.width/4, d.height/8, d.width/2, 3*d.height/4); - frame.show(); - g = frame.getGraphics(); - d = frame.size(); - - MediaTracker tracker = new MediaTracker(frame); - tracker.addImage(old_image, 0); - try { tracker.waitForID(0); } catch(InterruptedException excp) {} - g.drawImage(old_image, x, y, frame); - x += old_image.getWidth(frame) + 50; - - timer.start(); - image = ip.processImage(old_image, iff.createMeanImageFilter(), frame); - timer.stop(); - System.out.println(timer); - g.drawImage(image, x, y, frame); - x += old_image.getWidth(frame) + 50; - - timer.start(); - image = ip.processImage(old_image, iff.createSobelFilter(), frame); - timer.stop(); - System.out.println(timer); - g.drawImage(image, x, y, frame); - x = 50; - y += old_image.getHeight(frame) + 50; - - timer.start(); - image = ip.processImage(old_image, iff.createEmbossFilter(), frame); - timer.stop(); - System.out.println(timer); - g.drawImage(image, x, y, frame); - x += old_image.getWidth(frame) + 50; - - image = ip.processImage(old_image, iff.createSharpenFilter(), frame); - g.drawImage(image, x, y, frame); - x = 50; - y += old_image.getHeight(frame) + 50; - - image = ip.processImage(old_image, iff.createRotateImageFilter(), frame); - g.drawImage(image, x, y, frame); - } -} diff --git a/java/ImageProcessing/framework/GIFHandler.java b/java/ImageProcessing/framework/GIFHandler.java deleted file mode 100644 index 3d099ba294c..00000000000 --- a/java/ImageProcessing/framework/GIFHandler.java +++ /dev/null @@ -1,75 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import java.io.*; -import JACE.OS.*; -import JACE.Connection.*; - - -public class GIFHandler extends BlobWriter -{ - public GIFHandler (String filename, Image image, int length) - { - super (null, length, 0, filename); - this.image_ = image; - } - - /****************************** - * Used for HTTP 1.1 PUT authorization - *****************************/ - public GIFHandler (String filename, Image image, int length, String authentication) - { - super (null, length, 0, filename, authentication); - this.image_ = image; - } - - protected int sendRequest () - { - if (this.sendHeader () == -1) - { - ACE.ERROR ("GIFHandler::sendHeader failed."); - return -1; - } - else - if (this.sendData () == -1) - { - ACE.ERROR ("GIFHandler::sendData failed."); - return -1; - } - return 0; - } - - // Send the data - protected int sendData () - { - - - try - { - if (this.length_ > 0) - { - OutputStream ostream = this.peer ().outputStream (); - - this.encoder_ = new GifEncoder (this.image_, ostream); - - this.encoder_.encode (); - - ostream.flush(); - - // this.encoder_ = new GIFEncoder (this.image_); - // this.encoder_.Write (ostream); - } - this.bytesWritten_ = this.length_; - - } - catch (IOException e) - { - ACE.ERROR ("Error writing to server"); - } - return 0; - } - - GifEncoder encoder_ = null; - // GIFEncoder encoder_ = null; - Image image_ = null; -} diff --git a/java/ImageProcessing/framework/GifEncoder.java b/java/ImageProcessing/framework/GifEncoder.java deleted file mode 100644 index 91a3927d95d..00000000000 --- a/java/ImageProcessing/framework/GifEncoder.java +++ /dev/null @@ -1,693 +0,0 @@ -// GifEncoder - write out an image as a GIF -// -// Transparency handling and variable bit size courtesy of Jack Palevich. -// -// Copyright (C) 1996 by Jef Poskanzer <jef@acme.com>. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -// SUCH DAMAGE. -// -// Visit the ACME Labs Java page for up-to-date versions of this and other -// fine Java utilities: http://www.acme.com/java/ - -package imaging.framework; - -import java.util.*; -import java.io.*; -import java.awt.Image; -import java.awt.image.*; - -/// Write out an image as a GIF. -// <P> -// <A HREF="/resources/classes/Acme/JPM/Encoders/GifEncoder.java">Fetch the software.</A><BR> -// <A HREF="/resources/classes/Acme.tar.Z">Fetch the entire Acme package.</A> -// <P> -// @see ToGif - -public class GifEncoder extends ImageEncoder - { - - private boolean interlace = false; - - /// Constructor from Image. - // @param img The image to encode. - // @param out The stream to write the GIF to. - public GifEncoder( Image img, OutputStream out ) throws IOException - { - super( img, out ); - } - - /// Constructor from Image with interlace setting. - // @param img The image to encode. - // @param out The stream to write the GIF to. - // @param interlace Whether to interlace. - public GifEncoder( Image img, OutputStream out, boolean interlace ) throws IOException - { - super( img, out ); - this.interlace = interlace; - } - - /// Constructor from ImageProducer. - // @param prod The ImageProducer to encode. - // @param out The stream to write the GIF to. - public GifEncoder( ImageProducer prod, OutputStream out ) throws IOException - { - super( prod, out ); - } - - /// Constructor from ImageProducer with interlace setting. - // @param prod The ImageProducer to encode. - // @param out The stream to write the GIF to. - public GifEncoder( ImageProducer prod, OutputStream out, boolean interlace ) throws IOException - { - super( prod, out ); - this.interlace = interlace; - } - - - int width, height; - int[][] rgbPixels; - - void encodeStart( int width, int height ) throws IOException - { - this.width = width; - this.height = height; - rgbPixels = new int[height][width]; - } - - void encodePixels( - int x, int y, int w, int h, int[] rgbPixels, int off, int scansize ) - throws IOException - { - // Save the pixels. - for ( int row = 0; row < h; ++row ) - System.arraycopy( - rgbPixels, row * scansize + off, - this.rgbPixels[y + row], x, w ); - - } - - IntHashtable colorHash; - - void encodeDone() throws IOException - { - int transparentIndex = -1; - int transparentRgb = -1; - // Put all the pixels into a hash table. - colorHash = new IntHashtable(); - int index = 0; - for ( int row = 0; row < height; ++row ) - { - int rowOffset = row * width; - for ( int col = 0; col < width; ++col ) - { - int rgb = rgbPixels[row][col]; - boolean isTransparent = ( ( rgb >>> 24 ) < 0x80 ); - if ( isTransparent ) - { - if ( transparentIndex < 0 ) - { - // First transparent color; remember it. - transparentIndex = index; - transparentRgb = rgb; - } - else if ( rgb != transparentRgb ) - { - // A second transparent color; replace it with - // the first one. - rgbPixels[row][col] = rgb = transparentRgb; - } - } - GifEncoderHashitem item = - (GifEncoderHashitem) colorHash.get( rgb ); - if ( item == null ) - { - if ( index >= 256 ) - throw new IOException( "too many colors for a GIF" ); - item = new GifEncoderHashitem( - rgb, 1, index, isTransparent ); - ++index; - colorHash.put( rgb, item ); - } - else - ++item.count; - } - } - - // Figure out how many bits to use. - int logColors; - if ( index <= 2 ) - logColors = 1; - else if ( index <= 4 ) - logColors = 2; - else if ( index <= 16 ) - logColors = 4; - else - logColors = 8; - - // Turn colors into colormap entries. - int mapSize = 1 << logColors; - byte[] reds = new byte[mapSize]; - byte[] grns = new byte[mapSize]; - byte[] blus = new byte[mapSize]; - for ( Enumeration e = colorHash.elements(); e.hasMoreElements(); ) - { - GifEncoderHashitem item = (GifEncoderHashitem) e.nextElement(); - reds[item.index] = (byte) ( ( item.rgb >> 16 ) & 0xff ); - grns[item.index] = (byte) ( ( item.rgb >> 8 ) & 0xff ); - blus[item.index] = (byte) ( item.rgb & 0xff ); - } - - GIFEncode( - out, width, height, interlace, (byte) 0, transparentIndex, - logColors, reds, grns, blus ); - } - - byte GetPixel( int x, int y ) throws IOException - { - GifEncoderHashitem item = - (GifEncoderHashitem) colorHash.get( rgbPixels[y][x] ); - if ( item == null ) - throw new IOException( "color not found" ); - return (byte) item.index; - } - - static void writeString( OutputStream out, String str ) throws IOException - { - int len = str.length(); - byte[] buf = new byte[len]; - str.getBytes( 0, len, buf, 0 ); - out.write( buf ); - } - - // Adapted from ppmtogif, which is based on GIFENCOD by David - // Rowley <mgardi@watdscu.waterloo.edu>. Lempel-Zim compression - // based on "compress". - - int Width, Height; - boolean Interlace; - int curx, cury; - int CountDown; - int Pass = 0; - - void GIFEncode( - OutputStream outs, int Width, int Height, boolean Interlace, byte Background, int Transparent, int BitsPerPixel, byte[] Red, byte[] Green, byte[] Blue ) - throws IOException - { - byte B; - int LeftOfs, TopOfs; - int ColorMapSize; - int InitCodeSize; - int i; - - this.Width = Width; - this.Height = Height; - this.Interlace = Interlace; - ColorMapSize = 1 << BitsPerPixel; - LeftOfs = TopOfs = 0; - - // Calculate number of bits we are expecting - CountDown = Width * Height; - - // Indicate which pass we are on (if interlace) - Pass = 0; - - // The initial code size - if ( BitsPerPixel <= 1 ) - InitCodeSize = 2; - else - InitCodeSize = BitsPerPixel; - - // Set up the current x and y position - curx = 0; - cury = 0; - - // Write the Magic header - writeString( outs, "GIF89a" ); - - // Write out the screen width and height - Putword( Width, outs ); - Putword( Height, outs ); - - // Indicate that there is a global colour map - B = (byte) 0x80; // Yes, there is a color map - // OR in the resolution - B |= (byte) ( ( 8 - 1 ) << 4 ); - // Not sorted - // OR in the Bits per Pixel - B |= (byte) ( ( BitsPerPixel - 1 ) ); - - // Write it out - Putbyte( B, outs ); - - // Write out the Background colour - Putbyte( Background, outs ); - - // Pixel aspect ratio - 1:1. - //Putbyte( (byte) 49, outs ); - // Java's GIF reader currently has a bug, if the aspect ratio byte is - // not zero it throws an ImageFormatException. It doesn't know that - // 49 means a 1:1 aspect ratio. Well, whatever, zero works with all - // the other decoders I've tried so it probably doesn't hurt. - Putbyte( (byte) 0, outs ); - - // Write out the Global Colour Map - for ( i = 0; i < ColorMapSize; ++i ) - { - Putbyte( Red[i], outs ); - Putbyte( Green[i], outs ); - Putbyte( Blue[i], outs ); - } - - // Write out extension for transparent colour index, if necessary. - if ( Transparent != -1 ) - { - Putbyte( (byte) '!', outs ); - Putbyte( (byte) 0xf9, outs ); - Putbyte( (byte) 4, outs ); - Putbyte( (byte) 1, outs ); - Putbyte( (byte) 0, outs ); - Putbyte( (byte) 0, outs ); - Putbyte( (byte) Transparent, outs ); - Putbyte( (byte) 0, outs ); - } - - // Write an Image separator - Putbyte( (byte) ',', outs ); - - // Write the Image header - Putword( LeftOfs, outs ); - Putword( TopOfs, outs ); - Putword( Width, outs ); - Putword( Height, outs ); - - // Write out whether or not the image is interlaced - if ( Interlace ) - Putbyte( (byte) 0x40, outs ); - else - Putbyte( (byte) 0x00, outs ); - - // Write out the initial code size - Putbyte( (byte) InitCodeSize, outs ); - - // Go and actually compress the data - compress( InitCodeSize+1, outs ); - - // Write out a Zero-length packet (to end the series) - Putbyte( (byte) 0, outs ); - - // Write the GIF file terminator - Putbyte( (byte) ';', outs ); - } - - // Bump the 'curx' and 'cury' to point to the next pixel - void BumpPixel() - { - // Bump the current X position - ++curx; - - // If we are at the end of a scan line, set curx back to the beginning - // If we are interlaced, bump the cury to the appropriate spot, - // otherwise, just increment it. - if ( curx == Width ) - { - curx = 0; - - if ( ! Interlace ) - ++cury; - else - { - switch( Pass ) - { - case 0: - cury += 8; - if ( cury >= Height ) - { - ++Pass; - cury = 4; - } - break; - - case 1: - cury += 8; - if ( cury >= Height ) - { - ++Pass; - cury = 2; - } - break; - - case 2: - cury += 4; - if ( cury >= Height ) - { - ++Pass; - cury = 1; - } - break; - - case 3: - cury += 2; - break; - } - } - } - } - - static final int EOF = -1; - - // Return the next pixel from the image - int GIFNextPixel() throws IOException - { - byte r; - - if ( CountDown == 0 ) - return EOF; - - --CountDown; - - r = GetPixel( curx, cury ); - - BumpPixel(); - - return r & 0xff; - } - - // Write out a word to the GIF file - void Putword( int w, OutputStream outs ) throws IOException - { - Putbyte( (byte) ( w & 0xff ), outs ); - Putbyte( (byte) ( ( w >> 8 ) & 0xff ), outs ); - } - - // Write out a byte to the GIF file - void Putbyte( byte b, OutputStream outs ) throws IOException - { - outs.write( b ); - } - - - // GIFCOMPR.C - GIF Image compression routines - // - // Lempel-Ziv compression based on 'compress'. GIF modifications by - // David Rowley (mgardi@watdcsu.waterloo.edu) - - // General DEFINEs - - static final int BITS = 12; - - static final int HSIZE = 5003; // 80% occupancy - - // GIF Image compression - modified 'compress' - // - // Based on: compress.c - File compression ala IEEE Computer, June 1984. - // - // By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas) - // Jim McKie (decvax!mcvax!jim) - // Steve Davies (decvax!vax135!petsd!peora!srd) - // Ken Turkowski (decvax!decwrl!turtlevax!ken) - // James A. Woods (decvax!ihnp4!ames!jaw) - // Joe Orost (decvax!vax135!petsd!joe) - - int n_bits; // number of bits/code - int maxbits = BITS; // user settable max # bits/code - int maxcode; // maximum code, given n_bits - int maxmaxcode = 1 << BITS; // should NEVER generate this code - - final int MAXCODE( int n_bits ) - { - return ( 1 << n_bits ) - 1; - } - - int[] htab = new int[HSIZE]; - int[] codetab = new int[HSIZE]; - - int hsize = HSIZE; // for dynamic table sizing - - int free_ent = 0; // first unused entry - - // block compression parameters -- after all codes are used up, - // and compression rate changes, start over. - boolean clear_flg = false; - - // Algorithm: use open addressing double hashing (no chaining) on the - // prefix code / next character combination. We do a variant of Knuth's - // algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime - // secondary probe. Here, the modular division first probe is gives way - // to a faster exclusive-or manipulation. Also do block compression with - // an adaptive reset, whereby the code table is cleared when the compression - // ratio decreases, but after the table fills. The variable-length output - // codes are re-sized at this point, and a special CLEAR code is generated - // for the decompressor. Late addition: construct the table according to - // file size for noticeable speed improvement on small files. Please direct - // questions about this implementation to ames!jaw. - - int g_init_bits; - - int ClearCode; - int EOFCode; - - void compress( int init_bits, OutputStream outs ) throws IOException - { - int fcode; - int i /* = 0 */; - int c; - int ent; - int disp; - int hsize_reg; - int hshift; - - // Set up the globals: g_init_bits - initial number of bits - g_init_bits = init_bits; - - // Set up the necessary values - clear_flg = false; - n_bits = g_init_bits; - maxcode = MAXCODE( n_bits ); - - ClearCode = 1 << ( init_bits - 1 ); - EOFCode = ClearCode + 1; - free_ent = ClearCode + 2; - - char_init(); - - ent = GIFNextPixel(); - - hshift = 0; - for ( fcode = hsize; fcode < 65536; fcode *= 2 ) - ++hshift; - hshift = 8 - hshift; // set hash code range bound - - hsize_reg = hsize; - cl_hash( hsize_reg ); // clear hash table - - output( ClearCode, outs ); - - outer_loop: - while ( (c = GIFNextPixel()) != EOF ) - { - fcode = ( c << maxbits ) + ent; - i = ( c << hshift ) ^ ent; // xor hashing - - if ( htab[i] == fcode ) - { - ent = codetab[i]; - continue; - } - else if ( htab[i] >= 0 ) // non-empty slot - { - disp = hsize_reg - i; // secondary hash (after G. Knott) - if ( i == 0 ) - disp = 1; - do - { - if ( (i -= disp) < 0 ) - i += hsize_reg; - - if ( htab[i] == fcode ) - { - ent = codetab[i]; - continue outer_loop; - } - } - while ( htab[i] >= 0 ); - } - output( ent, outs ); - ent = c; - if ( free_ent < maxmaxcode ) - { - codetab[i] = free_ent++; // code -> hashtable - htab[i] = fcode; - } - else - cl_block( outs ); - } - // Put out the final code. - output( ent, outs ); - output( EOFCode, outs ); - } - - // output - // - // Output the given code. - // Inputs: - // code: A n_bits-bit integer. If == -1, then EOF. This assumes - // that n_bits =< wordsize - 1. - // Outputs: - // Outputs code to the file. - // Assumptions: - // Chars are 8 bits long. - // Algorithm: - // Maintain a BITS character long buffer (so that 8 codes will - // fit in it exactly). Use the VAX insv instruction to insert each - // code in turn. When the buffer fills up empty it and start over. - - int cur_accum = 0; - int cur_bits = 0; - - int masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, - 0x001F, 0x003F, 0x007F, 0x00FF, - 0x01FF, 0x03FF, 0x07FF, 0x0FFF, - 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; - - void output( int code, OutputStream outs ) throws IOException - { - cur_accum &= masks[cur_bits]; - - if ( cur_bits > 0 ) - cur_accum |= ( code << cur_bits ); - else - cur_accum = code; - - cur_bits += n_bits; - - while ( cur_bits >= 8 ) - { - char_out( (byte) ( cur_accum & 0xff ), outs ); - cur_accum >>= 8; - cur_bits -= 8; - } - - // If the next entry is going to be too big for the code size, - // then increase it, if possible. - if ( free_ent > maxcode || clear_flg ) - { - if ( clear_flg ) - { - maxcode = MAXCODE(n_bits = g_init_bits); - clear_flg = false; - } - else - { - ++n_bits; - if ( n_bits == maxbits ) - maxcode = maxmaxcode; - else - maxcode = MAXCODE(n_bits); - } - } - - if ( code == EOFCode ) - { - // At EOF, write the rest of the buffer. - while ( cur_bits > 0 ) - { - char_out( (byte) ( cur_accum & 0xff ), outs ); - cur_accum >>= 8; - cur_bits -= 8; - } - - flush_char( outs ); - } - } - - // Clear out the hash table - - // table clear for block compress - void cl_block( OutputStream outs ) throws IOException - { - cl_hash( hsize ); - free_ent = ClearCode + 2; - clear_flg = true; - - output( ClearCode, outs ); - } - - // reset code table - void cl_hash( int hsize ) - { - for ( int i = 0; i < hsize; ++i ) - htab[i] = -1; - } - - // GIF Specific routines - - // Number of characters so far in this 'packet' - int a_count; - - // Set up the 'byte output' routine - void char_init() - { - a_count = 0; - } - - // Define the storage for the packet accumulator - byte[] accum = new byte[256]; - - // Add a character to the end of the current packet, and if it is 254 - // characters, flush the packet to disk. - void char_out( byte c, OutputStream outs ) throws IOException - { - accum[a_count++] = c; - if ( a_count >= 254 ) - flush_char( outs ); - } - - // Flush the packet to disk, and reset the accumulator - void flush_char( OutputStream outs ) throws IOException - { - if ( a_count > 0 ) - { - outs.write( a_count ); - outs.write( accum, 0, a_count ); - a_count = 0; - } - } - - } - -class GifEncoderHashitem - { - - public int rgb; - public int count; - public int index; - public boolean isTransparent; - - public GifEncoderHashitem( int rgb, int count, int index, boolean isTransparent ) - { - this.rgb = rgb; - this.count = count; - this.index = index; - this.isTransparent = isTransparent; - } - - } diff --git a/java/ImageProcessing/framework/Hierarchy.java b/java/ImageProcessing/framework/Hierarchy.java deleted file mode 100644 index 41b1825ef4d..00000000000 --- a/java/ImageProcessing/framework/Hierarchy.java +++ /dev/null @@ -1,347 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import java.util.Vector; - -public class Hierarchy extends Canvas -{ - // Attributes - private String name_; - private Hierarchy root_; - private Hierarchy parent_; - private Icon icon_ = null; - - // State - private boolean collapsed_ = true; - private boolean deadend_ = true; - private Vector contained_ = new Vector(); - private Rectangle self_; - private Rectangle scope_; - - // Constants - private Color COLOR = Color.black; - private Font FONT = new Font("Dialog", Font.BOLD, 12); - private static int TRI_HEIGHT = 8; - private int SPACE = 15; - - static Hierarchy last_lit_ = null; - - public Hierarchy(String name, boolean root) - { - name_ = name; - - if (root) - { - deadend_ = false; - root_ = this; - parent_ = null; - } - } - - public Hierarchy(String name, Icon icon, boolean root) - { - this(name, root); - icon_ = icon; - } - - public Hierarchy(String name) - { - this(name, false); - } - - public Hierarchy(String name, Icon icon) - { - this(name, icon, false); - } - - public void setExpandable(boolean expandable) - { - deadend_ = ! expandable; - - /* - if (root_ != null) - root_.repaint(); - */ - } - - public void setCollapsed(boolean collapsed) - { - collapsed_ = collapsed; - - if (root_ != null) - root_.repaint(); - } - - public void addEntry(Hierarchy entry) - { - deadend_ = false; - entry.parent_ = this; - entry.root_ = root_; - entry.FONT = FONT; - entry.COLOR = COLOR; - entry.SPACE = SPACE; - - contained_.addElement(entry); - } - - public boolean removeEntry(String name) - { - if (contained_.size() == 1) - deadend_ = true; - - return contained_.removeElement(name); - } - - public String getName() - { - return name_; - } - - public void setName(String name) - { - name_ = name; - } - - public Hierarchy getHierarchyParent() - { - return parent_; - } - - public void setFont(Font font) - { - FONT = font; - } - - public void setColor(Color color) - { - COLOR = color; - } - - public void setSpace(int space) - { - SPACE = space; - } - - public void handleEvent() {} - - public boolean mouseDown(Event evt, int x, int y) - { - Hierarchy value = mouseInside(x, y); - - if (value != null) - { - if (! value.deadend_) - { - if (x < value.self_.x + TRI_HEIGHT + SPACE) - { - value.collapsed_ = ! value.collapsed_; - if (value.contained_.isEmpty()) - value.handleEvent(); - repaint(); - } - } - else - { - if (value.contained_.isEmpty()) - value.handleEvent(); - } - } - - return false; - } - - public boolean mouseMove(Event evt, int x, int y) - { - Hierarchy value = mouseInside(x, y); - - if ((value != last_lit_) && (last_lit_ != null)) - last_lit_.highlight(getGraphics(), false); - - if (value != null && value.deadend_) - value.highlight(getGraphics(), true); - - last_lit_ = value; - - return false; - } - - public void paint(Graphics g) - { - Dimension d = size(); - - drawLevel(g, SPACE, SPACE); - - if (d.width < scope_.width || d.height < scope_.height || - d.width > scope_.width || d.height > scope_.height) - resize(scope_.width, scope_.height); - } - - - private Point drawLevel(Graphics g, int x, int y) - { - g.setFont(FONT); - FontMetrics font_metrics = g.getFontMetrics(); - int string_height = font_metrics.getHeight(); - int string_width = font_metrics.stringWidth(name_); - int entry_height = string_height; - int entry_width = string_width + 2*SPACE + TRI_HEIGHT; - int total_height, total_width, initial_x = x, initial_y = y; - int indent = SPACE + TRI_HEIGHT/2; - int temp_x = x; - Point place_marker; - Hierarchy entry; - - if (icon_ != null) - { - entry_height = Math.max(string_height, icon_.iconSize().height); - entry_width += icon_.iconSize().width + SPACE; - indent += icon_.iconSize().width/2; - if (! deadend_) - drawShape(g, x, y + (entry_height - TRI_HEIGHT)/2, deadend_, collapsed_); - } - else - drawShape(g, x, y + (entry_height - TRI_HEIGHT)/2, deadend_, collapsed_); - - self_ = new Rectangle(initial_x, initial_y, entry_width, entry_height); - - temp_x += TRI_HEIGHT + SPACE; - - if (icon_ != null) - { - icon_.drawIcon(g, temp_x, y, root_); - temp_x += SPACE + icon_.iconSize().width; - } - - g.setColor(COLOR); - - g.drawString(name_, temp_x, y + (entry_height + string_height)/2); - - total_width = entry_width; - y += entry_height + SPACE; - - if (! (deadend_ || collapsed_)) - { - x += indent; - for (int i = 0; i < contained_.size(); i++) - { - entry = (Hierarchy)contained_.elementAt(i); - place_marker = entry.drawLevel(g, x, y); - total_width = Math.max(total_width, entry.scope_.width + indent + SPACE); - x = place_marker.x; - y = place_marker.y; - } - x -= indent; - } - - total_height = y - initial_y; - scope_ = new Rectangle(initial_x, initial_y, total_width, total_height); - - return new Point(x, y); - } - - private Hierarchy mouseInside(int x, int y) - { - Hierarchy entry; - Hierarchy return_value = null; - - if (self_.inside(x, y)) - { - return_value = this; - } - else - { - if (scope_.inside(x, y) && (! collapsed_)) - { - for (int i = 0; i < contained_.size(); i++) - { - entry = (Hierarchy)contained_.elementAt(i); - if ((return_value = entry.mouseInside(x, y)) != null) - break; - } - } - else - return_value = null; - } - - return return_value; - } - - private void highlight(Graphics g, boolean lit) - { - g.setFont(FONT); - FontMetrics fm = g.getFontMetrics(); - int string_height = fm.getHeight(); - int x = self_.x + SPACE + TRI_HEIGHT; - int y = self_.y; - - if (icon_ != null) - x += icon_.iconSize().width + SPACE; - - if (lit) - g.setColor(Color.magenta); - else - g.setColor(COLOR); - - g.drawString(name_, x, y + (self_.height + string_height)/2); - } - - - private static void drawShape(Graphics g, int x, int y, boolean dead_end, boolean collapsed) - { - int xpoints[] = new int[3]; - int ypoints[] = new int[3]; - - xpoints[0] = x; - ypoints[0] = y; - - if (dead_end) - { - g.fillOval(x, y, TRI_HEIGHT, TRI_HEIGHT); - } - else - { - // Draw a small collapsed triangle: |> - if (collapsed) - { - xpoints[1] = x; - xpoints[2] = x + TRI_HEIGHT; - ypoints[1] = y + TRI_HEIGHT; - ypoints[2] = y + TRI_HEIGHT/2; - g.fillPolygon(xpoints, ypoints, 3); - } - //Draw a small uncollapsed triangle - else - { - xpoints[1] = x + TRI_HEIGHT; - xpoints[2] = x + TRI_HEIGHT/2; - ypoints[1] = y; - ypoints[2] = y + TRI_HEIGHT; - g.fillPolygon(xpoints, ypoints, 3); - } - } - } - - private static void drawVertHashedLine(Graphics g, int x, int y1, int y2, int hashsize) - { - for (int ytemp = y1; ytemp < y2; ytemp += hashsize*3) - { - if (y2 - hashsize < ytemp) - g.drawLine(x, ytemp, x, y2); - else - g.drawLine(x, ytemp, x, ytemp + hashsize); - } - } - - private static void drawHoroHashedLine(Graphics g, int y, int x1, int x2, Color color, int hashsize) - { - for (int xtemp = x1; xtemp < x2; xtemp += hashsize*3) - { - if (x2 - hashsize < xtemp) - g.drawLine(xtemp, y, x1, y); - else - g.drawLine(xtemp, y, xtemp + hashsize, y); - } - } -} - - diff --git a/java/ImageProcessing/framework/HierarchyAdapter.java b/java/ImageProcessing/framework/HierarchyAdapter.java deleted file mode 100644 index a265be656ea..00000000000 --- a/java/ImageProcessing/framework/HierarchyAdapter.java +++ /dev/null @@ -1,34 +0,0 @@ -package imaging.framework; - -import java.awt.*; - -class HierarchyAdapter extends Hierarchy -{ - public HierarchyAdapter(String name, boolean root) - { - super(name, root); - } - - public HierarchyAdapter(String name, Icon icon, boolean root) - { - super(name, icon, root); - } - - public HierarchyAdapter(String name) - { - super(name); - } - - public HierarchyAdapter(String name, Icon icon) - { - super(name, icon); - } - - public void paint(Graphics g) - { - super.paint(g); - - Container p = getParent().getParent(); - p.getLayout ().layoutContainer (p); - } -} diff --git a/java/ImageProcessing/framework/Icon.java b/java/ImageProcessing/framework/Icon.java deleted file mode 100644 index eed91ed55c7..00000000000 --- a/java/ImageProcessing/framework/Icon.java +++ /dev/null @@ -1,70 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import java.applet.*; -import java.net.*; - -public class Icon -{ - protected Image icon_; - protected Dimension iconSize_; - - Icon() - { - super(); - } - - Icon(String file_name, Component comp) - { - this.icon_ = Toolkit.getDefaultToolkit().getImage(file_name); - this.loadImage(comp); - } - - Icon(Image icon_image, Component comp) - { - this.icon_ = icon_image; - this.loadImage(comp); - } - - Icon(String url, Applet applet) throws MalformedURLException - { - this.icon_ = applet.getImage(new URL(url)); - loadImage(applet); - } - - public void drawIcon(Graphics g, int x, int y, Component comp) - { - g.drawImage(this.icon_, x, y, comp); - } - - private void loadImage(Component comp) - { - try - { - MediaTracker tracker = new MediaTracker(comp); - tracker.addImage(this.icon_, 0); - tracker.waitForID(0); - - this.iconSize_ = new Dimension(this.icon_.getWidth(comp), this.icon_.getHeight(comp)); - } - catch (InterruptedException excp) - { - System.err.println("Icon::getIcon image failed to load"); - } - } - - public Dimension iconSize() - { - return this.iconSize_; - } - - public Image getIconImage() - { - return this.icon_; - } - -} - - - - diff --git a/java/ImageProcessing/framework/ImageApp.java b/java/ImageProcessing/framework/ImageApp.java deleted file mode 100644 index 486f45b9afb..00000000000 --- a/java/ImageProcessing/framework/ImageApp.java +++ /dev/null @@ -1,303 +0,0 @@ -package imaging.framework; - -import java.util.*; -import java.awt.*; -import java.net.*; -import java.io.*; -import java.awt.image.*; -import java.applet.*; -import gjt.Separator; -import gjt.Util; - -public class ImageApp extends Applet -{ - public void init () - { - // Use BorderLayout for our applet frame - this.setLayout (new BorderLayout ()); - - // Now load all the filters specified in the config file - // this.loadFilters (); - this.setupButtonPanel (); - this.add ("Center", this.imageCanvas_); - // Check if we are running in test mode - String testFile = getParameter ("testFile"); - if (testFile != null) - { - this.tester_ = new Tester (testFile, this); - this.tester_.initialize (); - } - // Initialize the DialogManager - DialogManager.initialize (this); - } - - private void setupButtonPanel () - { - Panel southPanel = new Panel (); - southPanel.setLayout (new BorderLayout ()); - - Panel buttonPanel = new Panel (); - buttonPanel.setLayout (new GridLayout (1, 5)); - - this.statusDisplay_ = new StatusDisplay (); - // Create a panel for all the buttons - this.filePanel_ = new FilePanel (this); - this.resetPanel_ = new ResetPanel (this); - this.zoomPanel_ = new ZoomPanel (this); - this.filterPanel_ = new FilterPanel (this); - this.helpPanel_ = new HelpPanel (this); - - buttonPanel.add (this.filePanel_); - buttonPanel.add (this.resetPanel_); - buttonPanel.add (this.zoomPanel_); - buttonPanel.add (this.filterPanel_); - buttonPanel.add (this.helpPanel_); - - southPanel.add ("North", new Separator ()); - southPanel.add ("Center", buttonPanel); - southPanel.add ("South", this.statusDisplay_); - - southPanel.resize (400, 400); - - // Now add all these components to the main frame - this.add ("South", southPanel); - this.add ("North", new Panel ()); // Empty panel (for aesthetics) - // this.add ("East", new Panel ()); // Empty panel (for aesthetics) - // this.add ("West", new Panel ()); // Empty panel (for aesthetics) - } - - public void displayStatus (String s) - { - this.statusDisplay_.setText (s); - } - - // Handle all action events - public void zoomFactor (double zoomFactor) - { - this.imageCanvas_.zoomFactor (zoomFactor); - } - - public void reloadFilters () - { - this.filterPanel_.loadFilters (); - repaint (); - } - - public Hashtable filterTable () - { - return this.filterTable_; - } - - public ImageFilter getFilter (String s) - { - return (ImageFilter) this.filterTable_.get (s); - } - - public void apply () - { - ImageFilter filter = this.getFilter (this.filterPanel_.choice ().getSelectedItem ()); - this.apply (filter); - } - - public void apply (ImageFilter filter) - { - if (filter != null) - { - Util.getFrame (this).setCursor (Frame.WAIT_CURSOR); - this.imageCanvas_.applyFilter (filter); - Util.getFrame (this).setCursor (Frame.DEFAULT_CURSOR); - } - } - - public void resetImage () - { - this.imageCanvas_.applyFilter (null); - } - - public int openURL (String url) - { - if (url == null) - return -1; - - Image image = null; - try - { - System.out.println("Getting image"); - image = getImage (new URL (url)); - System.out.println("Done"); - } - catch (MalformedURLException e) - { - return -1; - } - - if (image != null) - { - // Check if the image was actually loaded. Note that we have - // to wait for the potential image to finish loading before we - // know if it is a valid image. - if (this.imageCanvas_.setImage (image) == -1) - return -1; - else - this.filePanel_.enableSaveButton (); - } - else - return -1; - return 0; - } - - // maintain compatibility - public void saveFile (String url) - { - this.saveFile (url, null); - } - - public void saveFile (String url, String authentication) - { - ImageSender imageSender = new ImageSender (this); - imageSender.open (this.imageCanvas_.getImage (), url); - int bytesSent = imageSender.send (authentication); - if (bytesSent == -1) - DialogManager.popDialog (DialogType.NOT_SUPPORTED, - "Server does not support uploading or URL not found"); - } - - public Choice getFilters () - { - Choice choice = new Choice (); - - // Add the default choice first - choice.addItem ("Filters:"); - - // Now do the file processing -- to determine which filters need - // to be loaded. - - // Check if the filename has been previously specified and - // if not then check if the user has specified the name of the - // config file - if (this.configFile_ == null) - this.configFile_ = getParameter ("configFile"); - - /* - if (this.configFile_ == null) - this.configFile_ = "http://www.cs.wustl.edu/~pjain/java/ACE_wrappers/java/ImageProcessing/framework/filter.conf"; - */ - - if (this.configFile_ == null) - this.configFile_ = this.getCodeBase().toString() + "../ImageProcessing/framework/filter.conf"; - - String configInfo = null; - - // Only get the file as a URL if it was specified as an http style parameter! - if ((this.configFile_ != null) && ((this.configFile_.startsWith("http://")) || - (this.configFile_.startsWith("file://")) || - (this.configFile_.startsWith("ftp://")))) { - - URL url; - - try - { - System.out.println ("Configuration File: " + this.configFile_); - // Create a new URL - url = new URL (this.configFile_); - - // Get the input stream and pipe it to a DataInputStream - DataInputStream iStream = new DataInputStream (url.openStream ()); - - // Create a buffer to hold all the data we get - StringBuffer tempBuf = new StringBuffer (); - // Keep reading the data until we are done - String tempString = iStream.readLine (); - while (tempString != null) - { - tempBuf.append (tempString); - tempBuf.append (" "); - tempString = iStream.readLine (); - } - configInfo = tempBuf.toString (); - } - catch (MalformedURLException e) - { - System.err.println (e); - } - catch (IOException e) - { - System.err.println (e); - } - } - - if (configInfo != null) - { - try - { - StringTokenizer tokens = new StringTokenizer (configInfo); - String fullFilterName = null; - String filterName = null; - // Now parse the string, picking up filter names. Use these - // names to load the actual filters as well add new choices to - // the filter choices. - while (tokens.hasMoreTokens ()) - { - // Get the next token - fullFilterName = tokens.nextToken (); - filterName = this.extractFilterName (fullFilterName); - - System.out.println ("Loading: " + fullFilterName); - // Load the filter class - Class c = Class.forName (fullFilterName); - // Class c = this.filterRepository_.load (filter); - - // Add the filter to the Filter Repository - this.filterTable_.put (filterName, - (ImageFilter) c.newInstance ()); - - // Add filter name to the list of filter choices - choice.addItem (filterName); - } - } - catch (ClassNotFoundException e) - { - System.err.println ("Filter not found: " + e); - return null; - } - catch (IllegalAccessException e) - { - System.err.println ("Filter not found: " + e); - return null; - } - catch (InstantiationException e) - { - System.err.println ("Filter not found: " + e); - return null; - } - } - return choice; - } - - // Extract the short filter name from the full filter name. For - // example, this method returns "EmbossFilter" if it is given the - // string "imaging/filters/EmbossFilter" - private String extractFilterName (String s) - { - String filterName = null; - StringTokenizer tokens = new StringTokenizer (s, "."); - while (tokens.hasMoreTokens ()) - filterName = tokens.nextToken (); - return filterName; - } - - private Panel centerPanel_ = new Panel (); - private String configFile_ = null; - private Choice choice_ = null; - private ImageCanvas imageCanvas_ = new ImageCanvas (); - private FilePanel filePanel_; - private ResetPanel resetPanel_; - private ZoomPanel zoomPanel_; - private FilterPanel filterPanel_; - private HelpPanel helpPanel_; - - private StatusDisplay statusDisplay_; - private Hashtable filterTable_ = new Hashtable (); - private Tester tester_; - -} diff --git a/java/ImageProcessing/framework/ImageByteCounter.java b/java/ImageProcessing/framework/ImageByteCounter.java deleted file mode 100644 index c907c9f1c92..00000000000 --- a/java/ImageProcessing/framework/ImageByteCounter.java +++ /dev/null @@ -1,94 +0,0 @@ -package imaging.framework; - -import java.io.*; -import java.awt.*; -import java.applet.*; -import java.net.*; -import JACE.OS.*; - -public class ImageByteCounter -{ - public ImageByteCounter (String title, Image image, Applet parent) - { - this.image_ = image; - this.parent_ = parent; - - Image im = null; - try - { - im = this.parent_.getImage (new URL (this.parent_.getCodeBase () + - "../ImageProcessing/framework/" + - "10.gif")); - } - catch (MalformedURLException e) - { - ACE.ERROR (e); - } - - indicator_ = new StatusIndicator ("", im); - } - - public int count () - { - int length = 0; - try - { - GIFOutputStream ostream = new GIFOutputStream (indicator_); - // GIFOutputStream ostream = new GIFOutputStream (null); - GifEncoder encoder = new GifEncoder (this.image_, ostream); - encoder.encode (); - - length = ostream.count (); - System.out.println ("send: " + length); - } - catch (IOException e) - { - ACE.ERROR ("Exception generating gif"); - } - indicator_.dispose (); - return length; - } - - Image image_ = null; - StatusIndicator indicator_ = null; - boolean done_ = false; - Applet parent_; -} - -class GIFOutputStream extends OutputStream -{ - public GIFOutputStream (StatusIndicator indicator) - { - super (); - this.indicator_ = indicator; - } - - public synchronized void write (int b) throws IOException - { - bytesWritten_++; - if (this.indicator_ != null) - this.indicator_.update (bytesWritten_); - } - - public synchronized void write (byte buf[]) throws IOException - { - bytesWritten_ += buf.length; - if (this.indicator_ != null) - this.indicator_.update (bytesWritten_); - } - - public synchronized void write (byte buf[], int offset, int length) throws IOException - { - bytesWritten_ += length; - if (this.indicator_ != null) - this.indicator_.update (bytesWritten_); - } - - public int count () - { - return this.bytesWritten_; - } - - private int bytesWritten_ = 0; - private StatusIndicator indicator_ = null; -} diff --git a/java/ImageProcessing/framework/ImageCanvas.java b/java/ImageProcessing/framework/ImageCanvas.java deleted file mode 100644 index 182bd54bf9b..00000000000 --- a/java/ImageProcessing/framework/ImageCanvas.java +++ /dev/null @@ -1,166 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import java.awt.image.*; -import gjt.Util; -import JACE.OS.*; - -class ImageCanvas extends Canvas -{ - public static final double MAX_ZOOM = 4.0; - public static final double MIN_ZOOM = 0.5; - - public int setImage (Image image) - { - int flags = 0; - if (image != null) - { - // Load the image - this.tracker_.addImage(image, 0); - try { this.tracker_.waitForID(0); } catch(InterruptedException excp) {} - - // Check if the image was actually loaded. Note that we have - // to wait for the potential image to finish loading before we - // know if it is a valid image. - flags = this.checkImage (image, this); - if (ACE.BIT_ENABLED (flags, ImageObserver.ERROR)) - return -1; - - // If we reached here, it means image was loaded successfully so cache it - this.image_ = image; - this.originalImage_ = this.image_; - - this.x_ = (this.size ().width - this.image_.getWidth (this))/2; - this.y_ = (this.size ().height - this.image_.getHeight (this))/2; - this.original_x_ = this.x_; - this.original_y_ = this.y_; - repaint (); - } - return 0; - } - - public Image getImage () - { - return this.image_; - } - - public void paint (Graphics g) - { - this.setBackground (Color.white); - if (this.image_ != null) - g.drawImage(this.image_, - this.x_, this.y_, - (int) (this.image_.getWidth (this) * this.zoom_), - (int) (this.image_.getHeight (this) * this.zoom_), - this); - } - - public void applyFilter (ImageFilter filter) - { - if (this.image_ != null) - { - Image temp; - if (filter == null) - { - temp = this.originalImage_; - this.x_ = this.original_x_; - this.y_ = this.original_y_; - this.zoom_ = 1.0; - } - else - temp = this.ip_.processImage(this.image_, filter, this); - - this.tracker_.addImage(temp, 0); - try { this.tracker_.waitForID(0); } catch(InterruptedException excp) {} - - this.image_ = temp; - - // Originally I needed to flush the pixel data for the image to be - // drawn properly. When running the applet in appletviewer, the - // image used to jump around, but running in a browser seems to be - // ok. - //this.image_.flush(); - repaint (); - } - } - - public void zoomFactor (double zoom) - { - this.zoom_ *= zoom; - if (this.zoom_ > ImageCanvas.MAX_ZOOM) - this.zoom_ = ImageCanvas.MAX_ZOOM; - else if (this.zoom_ < ImageCanvas.MIN_ZOOM) - this.zoom_ = ImageCanvas.MIN_ZOOM; - - repaint (); - } - - public boolean mouseDown (Event evt, int x, int y) - { - if (inBounds (x, y)) - { - this.selected_ = true; - this.last_x_ = x; - this.last_y_ = y; - } - return true; - } - - public boolean mouseUp (Event evt, int x, int y) - { - this.selected_ = false; - return true; - } - - public boolean mouseDrag (Event evt, int x, int y) - { - if (this.selected_) - { - this.x_ = x - (this.last_x_ - this.x_); - this.y_ = y - (this.last_y_ - this.y_); - this.last_x_ = x; - this.last_y_ = y; - repaint (); - } - return true; - } - - public boolean mouseMove (Event evt, int x, int y) - { - if (this.image_ != null && inBounds (x, y)) - Util.getFrame (this).setCursor (Frame.HAND_CURSOR); - else - Util.getFrame (this).setCursor (Frame.DEFAULT_CURSOR); - return true; - } - - public boolean mouseExit (Event evt, int x, int y) - { - Util.getFrame (this).setCursor (Frame.DEFAULT_CURSOR); - return true; - } - - // Check if mouse is within the bounds of the image - private boolean inBounds (int x, int y) - { - if (this.image_ == null) - return false; - else - return (x >= this.x_) && - (y >= this.y_) && - (x <= (this.x_ + this.zoom_ * this.image_.getWidth (this))) && - (y <= (this.y_ + this.zoom_ * this.image_.getHeight (this))); - } - - private MediaTracker tracker_ = new MediaTracker(this); - private Image image_, originalImage_; - private int x_ = 0, y_ = 0; - private int original_x_ = 0, original_y_ = 0; - private int width_ = 0, height_ = 0; - private ImageProcessor ip_ = new ImageProcessor (); - private boolean selected_ = false; - private int last_x_ = 0, last_y_ = 0; - private double zoom_ = 1.0; - -} - diff --git a/java/ImageProcessing/framework/ImageEncoder.java b/java/ImageProcessing/framework/ImageEncoder.java deleted file mode 100644 index a0aac0d559f..00000000000 --- a/java/ImageProcessing/framework/ImageEncoder.java +++ /dev/null @@ -1,271 +0,0 @@ -// ImageEncoder - abstract class for writing out an image -// -// Copyright (C) 1996 by Jef Poskanzer <jef@acme.com>. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -// SUCH DAMAGE. -// -// Visit the ACME Labs Java page for up-to-date versions of this and other -// fine Java utilities: http://www.acme.com/java/ - -package imaging.framework; - -import java.util.*; -import java.io.*; -import java.awt.Image; -import java.awt.image.*; - -/// Abstract class for writing out an image. -// <P> -// A framework for classes that encode and write out an image in -// a particular file format. -// <P> -// This provides a simplified rendition of the ImageConsumer interface. -// It always delivers the pixels as ints in the RGBdefault color model. -// It always provides them in top-down left-right order. -// If you want more flexibility you can always implement ImageConsumer -// directly. -// <P> -// <A HREF="/resources/classes/Acme/JPM/Encoders/ImageEncoder.java">Fetch the software.</A><BR> -// <A HREF="/resources/classes/Acme.tar.Z">Fetch the entire Acme package.</A> -// <P> -// @see GifEncoder -// @see PpmEncoder -// @see Acme.JPM.Decoders.ImageDecoder - -public abstract class ImageEncoder implements ImageConsumer - { - - protected OutputStream out; - - private ImageProducer producer; - private int width = -1; - private int height = -1; - private int hintflags = 0; - private boolean started = false; - private boolean encoding; - private IOException iox; - private static final ColorModel rgbModel = ColorModel.getRGBdefault(); - private Hashtable props = null; - - /// Constructor. - // @param img The image to encode. - // @param out The stream to write the bytes to. - public ImageEncoder( Image img, OutputStream out ) throws IOException - { - this( img.getSource(), out ); - } - - /// Constructor. - // @param producer The ImageProducer to encode. - // @param out The stream to write the bytes to. - public ImageEncoder( ImageProducer producer, OutputStream out ) throws IOException - { - this.producer = producer; - this.out = out; - } - - - // Methods that subclasses implement. - - /// Subclasses implement this to initialize an encoding. - abstract void encodeStart( int w, int h ) throws IOException; - - /// Subclasses implement this to actually write out some bits. They - // are guaranteed to be delivered in top-down-left-right order. - // One int per pixel, index is row * scansize + off + col, - // RGBdefault (AARRGGBB) color model. - abstract void encodePixels( - int x, int y, int w, int h, int[] rgbPixels, int off, int scansize ) - throws IOException; - - /// Subclasses implement this to finish an encoding. - abstract void encodeDone() throws IOException; - - - // Our own methods. - - /// Call this after initialization to get things going. - public synchronized void encode() throws IOException - { - encoding = true; - iox = null; - producer.startProduction( this ); - while ( encoding ) - try - { - wait(); - } - catch ( InterruptedException e ) {} - if ( iox != null ) - throw iox; - } - - private boolean accumulate = false; - private int[] accumulator; - - private void encodePixelsWrapper( - int x, int y, int w, int h, int[] rgbPixels, int off, int scansize ) - throws IOException - { - if ( ! started ) - { - started = true; - encodeStart( width, height ); - if ( ( hintflags & TOPDOWNLEFTRIGHT ) == 0 ) - { - accumulate = true; - accumulator = new int[width * height]; - } - } - if ( accumulate ) - for ( int row = 0; row < h; ++row ) - System.arraycopy( - rgbPixels, row * scansize + off, - accumulator, ( y + row ) * width + x, - w ); - else - encodePixels( x, y, w, h, rgbPixels, off, scansize ); - } - - private void encodeFinish() throws IOException - { - if ( accumulate ) - { - encodePixels( 0, 0, width, height, accumulator, 0, width ); - accumulator = null; - accumulate = false; - } - } - - private synchronized void stop() - { - encoding = false; - notifyAll(); - } - - - // Methods from ImageConsumer. - - public void setDimensions( int width, int height ) - { - this.width = width; - this.height = height; - } - - public void setProperties( Hashtable props ) - { - this.props = props; - } - - public void setColorModel( ColorModel model ) - { - // Ignore. - } - - public void setHints( int hintflags ) - { - this.hintflags = hintflags; - } - - public void setPixels( - int x, int y, int w, int h, ColorModel model, byte[] pixels, - int off, int scansize ) - { - int[] rgbPixels = new int[w]; - for ( int row = 0; row < h; ++row ) - { - int rowOff = off + row * scansize; - for ( int col = 0; col < w; ++col ) - rgbPixels[col] = model.getRGB( pixels[rowOff + col] & 0xff ); - try - { - encodePixelsWrapper( x, y + row, w, 1, rgbPixels, 0, w ); - } - catch ( IOException e ) - { - iox = e; - stop(); - return; - } - } - } - - public void setPixels( - int x, int y, int w, int h, ColorModel model, int[] pixels, - int off, int scansize ) - { - if ( model == rgbModel ) - { - try - { - encodePixelsWrapper( x, y, w, h, pixels, off, scansize ); - } - catch ( IOException e ) - { - iox = e; - stop(); - return; - } - } - else - { - int[] rgbPixels = new int[w]; - for ( int row = 0; row < h; ++row ) - { - int rowOff = off + row * scansize; - for ( int col = 0; col < w; ++col ) - rgbPixels[col] = model.getRGB( pixels[rowOff + col] ); - try - { - encodePixelsWrapper( x, y + row, w, 1, rgbPixels, 0, w ); - } - catch ( IOException e ) - { - iox = e; - stop(); - return; - } - } - } - } - - public void imageComplete( int status ) - { - producer.removeConsumer( this ); - if ( status == ImageConsumer.IMAGEABORTED ) - iox = new IOException( "image aborted" ); - else - { - try - { - encodeFinish(); - encodeDone(); - } - catch ( IOException e ) - { - iox = e; - } - } - stop(); - } - - } diff --git a/java/ImageProcessing/framework/ImageProcessor.java b/java/ImageProcessing/framework/ImageProcessor.java deleted file mode 100644 index 422298d508f..00000000000 --- a/java/ImageProcessing/framework/ImageProcessor.java +++ /dev/null @@ -1,111 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import java.awt.image.*; -import java.util.Vector; - -public class ImageProcessor -{ - private Vector pipeline_ = new Vector(); - - - public ImageProcessor() - { - } - - public void addFilter(String filter_name, ImageFilter filter) - { - pipeline_.addElement(new FilterNode(filter_name, filter)); - } - - public boolean removeFilter(String name) - { - FilterNode filter_node; - - for (int i = 0; i < pipeline_.size(); i++) - { - filter_node = (FilterNode)pipeline_.elementAt(i); - if (name.equals(filter_node.getName())) - { - pipeline_.removeElementAt(i); - pipeline_.trimToSize(); - return true; - } - } - - return false; - } - - public Image processImage(Image image, ImageFilter filter, Component component) - { - Image old_image = image, new_image = old_image; - MediaTracker tracker = new MediaTracker(component); - - try - { - new_image = component.createImage(new FilteredImageSource(old_image.getSource(), filter)); - tracker.addImage(new_image, 0); - tracker.waitForID(0); - } - catch(InterruptedException excp) - { - System.out.println("ImageProcessor::processImage Image failed to load."); - System.out.println(excp); - return null; - } - - return new_image; - } - - public Image processImage(Image image, Component component) - { - Image old_image = image, new_image = null; - ImageFilter image_filter; - FilterNode filter_node; - MediaTracker tracker = new MediaTracker(component); - - try - { - for (int i = 0; i < pipeline_.size(); i++) - { - filter_node = (FilterNode) pipeline_.elementAt(i); - image_filter = filter_node.getFilter(); - new_image = component.createImage(new FilteredImageSource(old_image.getSource(), image_filter)); - old_image = new_image; - tracker.addImage(new_image, 0); - tracker.waitForID(0); - } - } - catch(InterruptedException excp) - { - System.out.println("ImageProcessor::processImage Image failed to load."); - System.out.println(excp); - return null; - } - - return new_image; - } -} - - -class FilterNode -{ - private String name_; - private ImageFilter filter_; - - FilterNode(String name, ImageFilter filter) - { - name_ = name; - filter_ = filter; - } - - String getName() - { - return name_; - } - - ImageFilter getFilter() - { - return filter_; - } -} diff --git a/java/ImageProcessing/framework/ImageSender.java b/java/ImageProcessing/framework/ImageSender.java deleted file mode 100644 index c1659267537..00000000000 --- a/java/ImageProcessing/framework/ImageSender.java +++ /dev/null @@ -1,128 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import java.net.*; -import java.io.*; -import java.applet.*; -import JACE.OS.*; -import JACE.Connection.*; - -public class ImageSender -{ - public ImageSender (Applet parent) - { - this.parent_ = parent; - } - - // ****************** - // Currently bombs if it's not in an http or / format - // - public void open (Image image, String url) - { - this.image_ = image; - - this.hostname_ = url; - if (this.hostname_.startsWith ("http://")) - this.hostname_ = this.hostname_.substring (7); - - int index = -1; - if ((index = this.hostname_.indexOf (":")) != -1) - { - String temp = this.hostname_.substring (index + 1); - int i = -1; - if ((i = temp.indexOf ("/")) != -1) - { - this.port_ = (new Integer (temp.substring (0, i))).intValue (); - this.filename_ = temp.substring (i); - } - this.hostname_ = this.hostname_.substring (0, index); - } - else - { - int i = -1; - if ((i = this.hostname_.indexOf ("/")) != -1) - { - this.filename_ = hostname_.substring (i); - } - this.hostname_ = this.hostname_.substring (0, i); - this.port_ = 80; - } - } - - // Maintain compatibility - public int send () - { - return send(null); - } - - /******************************************* - * The authenication string allows the PUT command to work if the server - * accepts the basic HTTP 1.1 encryption scheme - *******************************************/ - public int send (String authentication) - { - ImageByteCounter byteCounter = new ImageByteCounter ("", this.image_, this.parent_); - // StatusIndicator indicator = new StatusIndicator (""); - // ImageByteCounter byteCounter = new ImageByteCounter ("", this.image_, indicator); - int length = byteCounter.count (); - // indicator.dispose (); - // First determine how many bytes we will be sending - /* - try - { - GIFOutputStream ostream = new GIFOutputStream (); - GifEncoder encoder = new GifEncoder (this.image_, ostream); - encoder.encode (); - - length = ostream.count (); - System.out.println ("send: " + length); - } - catch (IOException e) - { - ACE.ERROR ("Exception generating gif"); - } - */ - - GIFHandler gifHandler; - if (authentication == null) - gifHandler = new GIFHandler (this.filename_, this.image_, length); - else - gifHandler = new GIFHandler (this.filename_, this.image_, length, authentication); - - try - { - // Connect to the server and send the image - this.connector_.open (this.hostname_, this.port_); - this.connector_.connect (gifHandler); - } - catch (UnknownHostException e) - { - ACE.ERROR (e); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - - if (gifHandler.returnCode () != -1) - return gifHandler.bytesWritten (); - else - return -1; - } - - private Image image_ = null; - String filename_; - String hostname_; - int port_; - Connector connector_ = new Connector (); - Applet parent_; -} - diff --git a/java/ImageProcessing/framework/IntHashtable.java b/java/ImageProcessing/framework/IntHashtable.java deleted file mode 100644 index 95e6cbc25e0..00000000000 --- a/java/ImageProcessing/framework/IntHashtable.java +++ /dev/null @@ -1,396 +0,0 @@ -// IntHashtable - a Hashtable that uses ints as the keys -// -// This is 90% based on JavaSoft's java.util.Hashtable. -// -// Visit the ACME Labs Java page for up-to-date versions of this and other -// fine Java utilities: http://www.acme.com/java/ - -package imaging.framework; - -import java.util.*; - -/// A Hashtable that uses ints as the keys. -// <P> -// Use just like java.util.Hashtable, except that the keys must be ints. -// This is much faster than creating a new Integer for each access. -// <P> -// <A HREF="/resources/classes/Acme/IntHashtable.java">Fetch the software.</A><BR> -// <A HREF="/resources/classes/Acme.tar.Z">Fetch the entire Acme package.</A> -// <P> -// @see java.util.Hashtable - -public class IntHashtable extends Dictionary implements Cloneable - { - /// The hash table data. - private IntHashtableEntry table[]; - - /// The total number of entries in the hash table. - private int count; - - /// Rehashes the table when count exceeds this threshold. - private int threshold; - - /// The load factor for the hashtable. - private float loadFactor; - - /// Constructs a new, empty hashtable with the specified initial - // capacity and the specified load factor. - // @param initialCapacity the initial number of buckets - // @param loadFactor a number between 0.0 and 1.0, it defines - // the threshold for rehashing the hashtable into - // a bigger one. - // @exception IllegalArgumentException If the initial capacity - // is less than or equal to zero. - // @exception IllegalArgumentException If the load factor is - // less than or equal to zero. - public IntHashtable( int initialCapacity, float loadFactor ) - { - if ( initialCapacity <= 0 || loadFactor <= 0.0 ) - throw new IllegalArgumentException(); - this.loadFactor = loadFactor; - table = new IntHashtableEntry[initialCapacity]; - threshold = (int) ( initialCapacity * loadFactor ); - } - - /// Constructs a new, empty hashtable with the specified initial - // capacity. - // @param initialCapacity the initial number of buckets - public IntHashtable( int initialCapacity ) - { - this( initialCapacity, 0.75f ); - } - - /// Constructs a new, empty hashtable. A default capacity and load factor - // is used. Note that the hashtable will automatically grow when it gets - // full. - public IntHashtable() - { - this( 101, 0.75f ); - } - - /// Returns the number of elements contained in the hashtable. - public int size() - { - return count; - } - - /// Returns true if the hashtable contains no elements. - public boolean isEmpty() - { - return count == 0; - } - - /// Returns an enumeration of the hashtable's keys. - // @see IntHashtable#elements - public synchronized Enumeration keys() - { - return new IntHashtableEnumerator( table, true ); - } - - /// Returns an enumeration of the elements. Use the Enumeration methods - // on the returned object to fetch the elements sequentially. - // @see IntHashtable#keys - public synchronized Enumeration elements() - { - return new IntHashtableEnumerator( table, false ); - } - - /// Returns true if the specified object is an element of the hashtable. - // This operation is more expensive than the containsKey() method. - // @param value the value that we are looking for - // @exception NullPointerException If the value being searched - // for is equal to null. - // @see IntHashtable#containsKey - public synchronized boolean contains( Object value ) - { - if ( value == null ) - throw new NullPointerException(); - IntHashtableEntry tab[] = table; - for ( int i = tab.length ; i-- > 0 ; ) - { - for ( IntHashtableEntry e = tab[i] ; e != null ; e = e.next ) - { - if ( e.value.equals( value ) ) - return true; - } - } - return false; - } - - /// Returns true if the collection contains an element for the key. - // @param key the key that we are looking for - // @see IntHashtable#contains - public synchronized boolean containsKey( int key ) - { - IntHashtableEntry tab[] = table; - int hash = key; - int index = ( hash & 0x7FFFFFFF ) % tab.length; - for ( IntHashtableEntry e = tab[index] ; e != null ; e = e.next ) - { - if ( e.hash == hash && e.key == key ) - return true; - } - return false; - } - - /// Gets the object associated with the specified key in the - // hashtable. - // @param key the specified key - // @returns the element for the key or null if the key - // is not defined in the hash table. - // @see IntHashtable#put - public synchronized Object get( int key ) - { - IntHashtableEntry tab[] = table; - int hash = key; - int index = ( hash & 0x7FFFFFFF ) % tab.length; - for ( IntHashtableEntry e = tab[index] ; e != null ; e = e.next ) - { - if ( e.hash == hash && e.key == key ) - return e.value; - } - return null; - } - - /// A get method that takes an Object, for compatibility with - // java.util.Dictionary. The Object must be an Integer. - public Object get( Object okey ) - { - if ( ! ( okey instanceof Integer ) ) - throw new InternalError( "key is not an Integer" ); - Integer ikey = (Integer) okey; - int key = ikey.intValue(); - return get( key ); - } - - /// Rehashes the content of the table into a bigger table. - // This method is called automatically when the hashtable's - // size exceeds the threshold. - protected void rehash() - { - int oldCapacity = table.length; - IntHashtableEntry oldTable[] = table; - - int newCapacity = oldCapacity * 2 + 1; - IntHashtableEntry newTable[] = new IntHashtableEntry[newCapacity]; - - threshold = (int) ( newCapacity * loadFactor ); - table = newTable; - - for ( int i = oldCapacity ; i-- > 0 ; ) - { - for ( IntHashtableEntry old = oldTable[i] ; old != null ; ) - { - IntHashtableEntry e = old; - old = old.next; - - int index = ( e.hash & 0x7FFFFFFF ) % newCapacity; - e.next = newTable[index]; - newTable[index] = e; - } - } - } - - /// Puts the specified element into the hashtable, using the specified - // key. The element may be retrieved by doing a get() with the same key. - // The key and the element cannot be null. - // @param key the specified key in the hashtable - // @param value the specified element - // @exception NullPointerException If the value of the element - // is equal to null. - // @see IntHashtable#get - // @return the old value of the key, or null if it did not have one. - public synchronized Object put( int key, Object value ) - { - // Make sure the value is not null. - if ( value == null ) - throw new NullPointerException(); - - // Makes sure the key is not already in the hashtable. - IntHashtableEntry tab[] = table; - int hash = key; - int index = ( hash & 0x7FFFFFFF ) % tab.length; - for ( IntHashtableEntry e = tab[index] ; e != null ; e = e.next ) - { - if ( e.hash == hash && e.key == key ) - { - Object old = e.value; - e.value = value; - return old; - } - } - - if ( count >= threshold ) - { - // Rehash the table if the threshold is exceeded. - rehash(); - return put( key, value ); - } - - // Creates the new entry. - IntHashtableEntry e = new IntHashtableEntry(); - e.hash = hash; - e.key = key; - e.value = value; - e.next = tab[index]; - tab[index] = e; - ++count; - return null; - } - - /// A put method that takes an Object, for compatibility with - // java.util.Dictionary. The Object must be an Integer. - public Object put( Object okey, Object value ) - { - if ( ! ( okey instanceof Integer ) ) - throw new InternalError( "key is not an Integer" ); - Integer ikey = (Integer) okey; - int key = ikey.intValue(); - return put( key, value ); - } - - /// Removes the element corresponding to the key. Does nothing if the - // key is not present. - // @param key the key that needs to be removed - // @return the value of key, or null if the key was not found. - public synchronized Object remove( int key ) - { - IntHashtableEntry tab[] = table; - int hash = key; - int index = ( hash & 0x7FFFFFFF ) % tab.length; - for ( IntHashtableEntry e = tab[index], prev = null ; e != null ; prev = e, e = e.next ) - { - if ( e.hash == hash && e.key == key ) - { - if ( prev != null ) - prev.next = e.next; - else - tab[index] = e.next; - --count; - return e.value; - } - } - return null; - } - - /// A remove method that takes an Object, for compatibility with - // java.util.Dictionary. The Object must be an Integer. - public Object remove( Object okey ) - { - if ( ! ( okey instanceof Integer ) ) - throw new InternalError( "key is not an Integer" ); - Integer ikey = (Integer) okey; - int key = ikey.intValue(); - return remove( key ); - } - - /// Clears the hash table so that it has no more elements in it. - public synchronized void clear() - { - IntHashtableEntry tab[] = table; - for ( int index = tab.length; --index >= 0; ) - tab[index] = null; - count = 0; - } - - /// Creates a clone of the hashtable. A shallow copy is made, - // the keys and elements themselves are NOT cloned. This is a - // relatively expensive operation. - public synchronized Object clone() - { - try - { - IntHashtable t = (IntHashtable) super.clone(); - t.table = new IntHashtableEntry[table.length]; - for ( int i = table.length ; i-- > 0 ; ) - t.table[i] = ( table[i] != null ) ? - (IntHashtableEntry) table[i].clone() : null; - return t; - } - catch ( CloneNotSupportedException e) - { - // This shouldn't happen, since we are Cloneable. - throw new InternalError(); - } - } - - /// Converts to a rather lengthy String. - public synchronized String toString() - { - int max = size() - 1; - StringBuffer buf = new StringBuffer(); - Enumeration k = keys(); - Enumeration e = elements(); - buf.append( "{" ); - - for ( int i = 0; i <= max; ++i ) - { - String s1 = k.nextElement().toString(); - String s2 = e.nextElement().toString(); - buf.append( s1 + "=" + s2 ); - if ( i < max ) - buf.append( ", " ); - } - buf.append( "}" ); - return buf.toString(); - } - } - - -class IntHashtableEntry - { - int hash; - int key; - Object value; - IntHashtableEntry next; - - protected Object clone() - { - IntHashtableEntry entry = new IntHashtableEntry(); - entry.hash = hash; - entry.key = key; - entry.value = value; - entry.next = ( next != null ) ? (IntHashtableEntry) next.clone() : null; - return entry; - } - } - - -class IntHashtableEnumerator implements Enumeration - { - boolean keys; - int index; - IntHashtableEntry table[]; - IntHashtableEntry entry; - - IntHashtableEnumerator( IntHashtableEntry table[], boolean keys ) - { - this.table = table; - this.keys = keys; - this.index = table.length; - } - - public boolean hasMoreElements() - { - if ( entry != null ) - return true; - while ( index-- > 0 ) - if ( ( entry = table[index] ) != null ) - return true; - return false; - } - - public Object nextElement() - { - if ( entry == null ) - while ( ( index-- > 0 ) && ( ( entry = table[index] ) == null ) ) - ; - if ( entry != null ) - { - IntHashtableEntry e = entry; - entry = e.next; - return keys ? new Integer( e.key ) : e.value; - } - throw new NoSuchElementException( "IntHashtableEnumerator" ); - } - } diff --git a/java/ImageProcessing/framework/ListFiles.java b/java/ImageProcessing/framework/ListFiles.java deleted file mode 100644 index 7abe067341c..00000000000 --- a/java/ImageProcessing/framework/ListFiles.java +++ /dev/null @@ -1,167 +0,0 @@ -package imaging.framework; - -import java.net.*; -import java.io.*; -import java.applet.*; - -public class ListFiles -{ - public ListFiles () - { - } - - public ListFiles (FileBrowser browser, Applet parent) - { - this.browser_ = browser; - try - { - this.fileIcon_ = new Icon (parent.getCodeBase () + - "../ImageProcessing/framework/" + - "doc01.gif", - parent); - this.dirIcon_ = new Icon (parent.getCodeBase () + - "../ImageProcessing/framework/" + - "file03.gif", - parent); - } - catch (MalformedURLException e) - { - } - } - - public String stripProtocolHeader (String url) - { - if (url.startsWith ("http://")) - { - return url.substring (7); - } - else - return url; - } - - public int listFiles (String url, FileNode fileNode) - { - String s = this.stripProtocolHeader (url); - String hostname = s; - String directory = null; - int index = -1; - - if ((index = s.indexOf ("/")) != -1) - { - hostname = s.substring (0, index); - directory = s.substring (index); - } - return this.listFiles (hostname, directory, fileNode); - } - - public int listFiles (String url, String directory, FileNode fileNode) - { - boolean validDirectory = false; - int count = 0; - String hostname = this.stripProtocolHeader (url); - this.url_ = url; - this.directory_ = directory; - try - { - Socket sock = new Socket (hostname, 80); - PrintStream out = new PrintStream (sock.getOutputStream ()); - DataInputStream in = new DataInputStream (sock.getInputStream ()); - System.out.println ("Connected to: " + hostname); - - String request = null; - if (directory.endsWith ("/")) - request = "GET " + directory + "\n\n"; - else - request = "GET " + directory + "/\n\n"; - - System.out.println ("Sending request: " + request); - - // Send the request - out.println (request); - - String reply = null; - // Receive the reply - - // Read all the data in a loop. Search for "Parent Directory" - // to verify that this indeed is a directory. If we encounter - // the string "<HTML>" then assume that this is an HTML page - // and therefore the directory contained "index.html" - while ((reply = in.readLine ()) != null) - { - if (validDirectory) - this.parse (reply, fileNode); - else - { - // Take a guess at the type of data we get back - if (reply.indexOf ("Parent Directory") != -1) - validDirectory = true; - else if ((reply.toUpperCase ().indexOf ("<HTML>") != -1) || - (reply.toUpperCase ().indexOf ("<P>") != -1) || - (reply.toUpperCase ().indexOf ("<TABLE") != -1)) - return 0; - } - } - } - catch (MalformedURLException e) - { - System.err.println (e); - } - catch (IOException e) - { - System.err.println (e); - } - if (validDirectory == false) - return -1; - return 1; - } - - private int parse (String s, FileNode fileNode) - { - int i= -1; - int j = -1; - int startIndex = -1; - int endIndex = -1; - boolean isFile = true; - String name = null; - - if ((i = s.indexOf ("HREF=")) != -1) - startIndex = i + 6; - else - return -1; - - if ((j = s.indexOf (">", i)) != -1) - endIndex = j - 1; - else - return -1; - - // Check if this is a directory - if (s.charAt (endIndex - 1) == '/') - isFile = false; - - if (endIndex >= startIndex) - { - name = s.substring (startIndex, endIndex); - if (browser_ != null) - { - // System.out.println (name); - if (isFile) - fileNode.addEntry (new FileNode (name, this.fileIcon_, null, - fileNode.app ())); - else - { - FileNode f = new FileNode (name, this.dirIcon_, this, - fileNode.app ()); - fileNode.addEntry (f); - f.setExpandable (true); - } - } - } - return 0; - } - - private FileBrowser browser_ = null; - private String url_ = null; - private String directory_ = null; - private Icon fileIcon_; - private Icon dirIcon_; -} diff --git a/java/ImageProcessing/framework/LoadURLFrame.java b/java/ImageProcessing/framework/LoadURLFrame.java deleted file mode 100755 index 610d9eaafa8..00000000000 --- a/java/ImageProcessing/framework/LoadURLFrame.java +++ /dev/null @@ -1,142 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import java.awt.image.*; -import java.net.*; -import java.io.*; - -/****************************************************** - * Future idea: - * - * Create a smart button class with an invoke method that's - * to be called when the button is pressed. - * - * Subclasses override the invoke method to define - * specific behavior. - * - * That would allow things like load and save frames - * to be almost exactly the same -- one could inherit - * from the other and override addButtons, etc - *****************************************************/ - -class LoadURLFrame extends Frame -{ - public LoadURLFrame (String title, ImageApp parent) - { - super (title); - - this.parent_ = parent; - this.resize (500,130); - - this.addButtons(); - } - - private void addButtons() - { - this.setLayout (new BorderLayout ()); - - Panel textPanel = new Panel (); - textPanel.setLayout (new BorderLayout ()); - textPanel.add ("North", new Label ("Image Location:")); - textPanel.add ("Center", this.openURLText_); - - Panel buttonPanel = new Panel (); - buttonPanel.setLayout (new FlowLayout (FlowLayout.CENTER)); - - buttonPanel.add (this.openButton_); - - buttonPanel.add (this.clearButton_); - buttonPanel.add (this.cancelButton_); - - this.add ("North", textPanel); - this.add ("South", buttonPanel); - } - - private int browseFiles (String url) - { - fileBrowser_ = new FileBrowser ("Browse", this.parent_); - ListFiles list = new ListFiles (this.fileBrowser_, this.parent_); - return this.fileBrowser_.initialize (url, list); - } - - // Handle all action events - public boolean action (Event e, Object arg) - { - if (e.target instanceof Button) - { - if (e.target == this.openButton_) - { - this.getURL (); - } - else if (e.target == this.clearButton_) - { - this.openURLText_.setText (new String ()); - this.openURLText_.requestFocus (); - } - else if (e.target == this.cancelButton_) - this.dispose (); - validate (); - return true; - } - else - return false; - } - - public boolean keyDown (Event e, int key) - { - if (key == 10) - { - this.getURL (); - return true; - } - else - return false; - } - - private void getURL () - { - this.hide (); - String url = this.openURLText_.getText (); - this.dispose (); - - // The following is only for debugging - if (url.compareTo ("ru") == 0) - url = "http://www.cs/~pjain/gifs/"; - else if (url.compareTo ("pj") == 0) - url = "http://www.cs/~pjain/myphoto.gif"; - - if (!url.endsWith ("/") && - (this.parent_.openURL (url) != -1)) // Try to open it as an image - return; - else - { - ListFiles list = new ListFiles (); - switch (this.browseFiles (url)) - { - case 1: - this.fileBrowser_.show (); - break; - case 0: - DialogManager.popDialog (DialogType.MALFORMED_URL, - "Error: Directory contains index.html"); - break; - default: - DialogManager.popDialog (DialogType.MALFORMED_URL, - "Error: Not a valid image or URL not found"); - break; - } - } - } - - // Create the Open URL Frame and also the buttons which appear in - // it - private Button openButton_ = new Button ("Open"); - private Button clearButton_ = new Button ("Clear"); - private Button cancelButton_ = new Button ("Cancel"); - - private TextField openURLText_ = new TextField (40); - - private FileBrowser fileBrowser_ = null; - private ImageApp parent_; - -} diff --git a/java/ImageProcessing/framework/Makefile b/java/ImageProcessing/framework/Makefile deleted file mode 100644 index 1187b8a88d7..00000000000 --- a/java/ImageProcessing/framework/Makefile +++ /dev/null @@ -1,45 +0,0 @@ -# Makefile - -.SUFFIXES: .java .class - -JACE_WRAPPER = ../.. -CLASSDIR = $(JACE_WRAPPER)/classes -DOCDIR = $(JACE_WRAPPER)/doc - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: - javac -d ${JACE_WRAPPER}/classes $(files) - -clean: - rm -rf *~ - -realclean: clean - rm -rf $(JACE_WRAPPER)/classes/imaging/framework - -files = ImageProcessor.java \ - DialogType.java \ - LoadURLFrame.java \ - SaveURLFrame.java \ - DialogManager.java \ - ImageCanvas.java \ - ImageApp.java \ - BaseButton.java \ - FilePanel.java \ - StatusDisplay.java \ - Icon.java \ - Hierarchy.java \ - HierarchyAdapter.java \ - FileBrowser.java \ - ListFiles.java \ - IntHashtable.java \ - ImageEncoder.java \ - GifEncoder.java \ - ImageByteCounter.java \ - StatusIndicator.java \ - GIFHandler.java \ - ImageSender.java \ - ServerTest.java \ - ServerHandler.java \ - Tester.java \ - TestHandler.java diff --git a/java/ImageProcessing/framework/MedJava.html b/java/ImageProcessing/framework/MedJava.html deleted file mode 100644 index a073413bfbb..00000000000 --- a/java/ImageProcessing/framework/MedJava.html +++ /dev/null @@ -1,15 +0,0 @@ -<HTML> - -<BODY text = "#000000" -link="#000fff" -vlink="#ff0f0f" -bgcolor="#888888"> - -<HR> -<APPLET CODEBASE="/classes/" CODE="imaging.framework.ImageApp.class" width=700 height=700> -<param name=filename value="myphoto.gif"> - -</APPLET> -<HR> - -</HTML> diff --git a/java/ImageProcessing/framework/Options.java b/java/ImageProcessing/framework/Options.java deleted file mode 100644 index edbe90ba904..00000000000 --- a/java/ImageProcessing/framework/Options.java +++ /dev/null @@ -1,25 +0,0 @@ -package imaging.framework; - -import java.awt.*; - -class Options -{ - // Set GridBagConstraints - public static void constrain (Container container, Component component, - int gridx, int gridy, - int gridwidth, int gridheight, - int fill, int anchor) - { - GridBagConstraints c = new GridBagConstraints (); - GridBagLayout gbl = (GridBagLayout) container.getLayout (); - - c.gridx = gridx; - c.gridy = gridy; - c.gridwidth = gridwidth; - c.gridheight = gridheight; - c.fill = fill; - c.anchor = anchor; - gbl.setConstraints (component, c); - container.add (component); - } -} diff --git a/java/ImageProcessing/framework/SaveURLFrame.java b/java/ImageProcessing/framework/SaveURLFrame.java deleted file mode 100755 index c3b6adf3490..00000000000 --- a/java/ImageProcessing/framework/SaveURLFrame.java +++ /dev/null @@ -1,133 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import java.awt.image.*; -import java.net.*; -import java.io.*; - -/****************************************************** - * Future idea: - * - * Create a smart button class with an invoke method that's - * to be called when the button is pressed. - * - * Subclasses override the invoke method to define - * specific behavior. - * - * That would allow things like load and save frames - * to be almost exactly the same -- one could inherit - * from the other and override addButtons, etc - *****************************************************/ - - -class SaveURLFrame extends Frame -{ - public SaveURLFrame (String title, ImageApp parent) - { - super (title); - - this.parent_ = parent; - this.resize (500,200); - - this.addButtons(); - } - - private void addButtons() - { - this.setLayout (new BorderLayout ()); - - Panel textPanels = new Panel(); - textPanels.setLayout(new BorderLayout()); - - Panel URLPanel = new Panel (); - URLPanel.setLayout (new BorderLayout ()); - URLPanel.add ("North", new Label ("Image Location:")); - URLPanel.add ("Center", this.openURLText_); - - // Password panel - Panel pwPanel = new Panel(); - pwPanel.setLayout (new BorderLayout ()); - pwPanel.add ("North", new Label ("Authentication:")); - pwPanel.add ("Center", this.passwordText_); - - textPanels.add("North", URLPanel); - textPanels.add("South", pwPanel); - - Panel buttonPanel = new Panel (); - buttonPanel.setLayout (new FlowLayout (FlowLayout.CENTER)); - - buttonPanel.add (this.saveButton_); - buttonPanel.add (this.clearButton_); - buttonPanel.add (this.cancelButton_); - - this.add ("North", textPanels); - this.add ("South", buttonPanel); - } - - // Handle all action events - public boolean action (Event e, Object arg) - { - if (e.target instanceof Button) - { - if (e.target == this.saveButton_) - { - this.saveFile (); - } - else if (e.target == this.clearButton_) - { - this.openURLText_.setText (new String ()); - this.openURLText_.requestFocus (); - } - else if (e.target == this.cancelButton_) - this.dispose (); - validate (); - return true; - } - else - return false; - } - - public boolean keyDown (Event e, int key) - { - if (key == 10) - { - this.saveFile (); - return true; - } - else - return false; - } - - private void saveFile () - { - String url = this.openURLText_.getText (); - String password = this.passwordText_.getText(); - this.hide (); - this.dispose (); - - // The following is only for debugging - if (url.startsWith ("#")) - url = "http://merengue.cs:5432/" + url.substring (1); - - if ((password != null) && (password.length() > 0)) - this.parent_.saveFile (url, password); - else - this.parent_.saveFile (url); - } - - - // Create the Open URL Frame and also the buttons which appear in - // it - private Button saveButton_ = new Button ("Save"); - private Button clearButton_ = new Button ("Clear"); - private Button cancelButton_ = new Button ("Cancel"); - - private TextField openURLText_ = new TextField (40); - private TextField passwordText_ = new TextField (40); - - private ImageApp parent_; - - // Flag indicating if this is a load window or a save window - private boolean open_ = true; - -} diff --git a/java/ImageProcessing/framework/Separator.java b/java/ImageProcessing/framework/Separator.java deleted file mode 100644 index 6bd610e1ad9..00000000000 --- a/java/ImageProcessing/framework/Separator.java +++ /dev/null @@ -1,90 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A separator that is drawn either vertically or horizontally - * depending upon how it is laid out. Can be drawn either - * etched-in or etched-out, with varying thicknesses. Both - * thickness and etching are settable at construction time - * only.<p> - * - * Default thickness is 2 pixels and default etching is - * Etching.IN. Note that thicknesses greater than 4 loose the - * etching effect.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see Etching - * @see gjt.test.SeparatorTest - */ -public class Separator extends Canvas { - static private Etching _defaultEtching = Etching.IN; - static private int _defaultThickness = 2; - - private Etching etching; - private int thickness; - - public Separator() { - this(_defaultThickness, _defaultEtching); - } - public Separator(int thickness) { - this(thickness, _defaultEtching); - } - public Separator(Etching etching) { - this(_defaultThickness, etching); - } - public Separator(int thickness, Etching etching) { - this.etching = etching; - this.thickness = thickness; - resize(thickness, thickness); - } - public Dimension minimumSize() { - return preferredSize(); - } - public Dimension preferredSize() { - return new Dimension(thickness, thickness); - } - public void paint(Graphics g) { - Dimension size = size(); - Color brighter = getBackground().brighter().brighter(); - Color darker = getBackground().darker().darker(); - - if(etching == Etching.IN) { - if(size.width > size.height) - paintHorizontal(g, size, darker, brighter); - else - paintVertical(g, size, darker, brighter); - } - else { - if(size.width > size.height) - paintHorizontal(g, size, brighter, darker); - else - paintVertical(g, size, brighter, darker); - } - } - public String paramString() { - Dimension size = size(); - Orientation orient = size.width > size.height ? - Orientation.HORIZONTAL : - Orientation.VERTICAL; - return super.paramString() + "thickness=" + - thickness + "," + etching + "," + orient; - } - private void paintHorizontal(Graphics g, Dimension size, - Color top, Color bottom) { - g.setColor(top); - g.fillRect(0, (size.height/2) - (thickness/2), - size.width, thickness/2); - g.setColor(bottom); - g.fillRect(0, size.height/2, size.width, thickness/2); - } - private void paintVertical(Graphics g, Dimension size, - Color left, Color right) { - g.setColor(left); - g.fillRect((size.width/2) - (thickness/2), - 0, thickness/2, size.height); - g.setColor(right); - g.fillRect(size.width/2, 0, thickness/2, size.height); - } -} diff --git a/java/ImageProcessing/framework/ServerHandler.java b/java/ImageProcessing/framework/ServerHandler.java deleted file mode 100644 index 88da64d6328..00000000000 --- a/java/ImageProcessing/framework/ServerHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -package imaging.framework; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.Connection.*; - -public class ServerHandler extends SvcHandler -{ - public int open (Object obj) - { - new Thread (this).start (); - return 0; - } - - public void run () - { - int msg_len; - try - { - while (true) - { - StringBuffer msg = new StringBuffer (); - msg_len = this.peer ().recv (msg); - if (msg_len == 0) - break; - System.out.println (msg); - } - } - catch (NullPointerException e) - { - ACE.ERROR ("connection reset by peer"); - } - catch (IOException e) - { - ACE.ERROR (e); - } - finally - { - try - { - this.peer ().close (); - } - catch (IOException e) - { - } - } - - } -} diff --git a/java/ImageProcessing/framework/ServerTest.java b/java/ImageProcessing/framework/ServerTest.java deleted file mode 100644 index b5ab00596ea..00000000000 --- a/java/ImageProcessing/framework/ServerTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package imaging.framework; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.Connection.*; - -public class ServerTest -{ - void print_usage_and_die () - { - System.out.println ("Usage: ServerTest [<port>]"); - System.exit (0); - } - - public void init (int port) - { - try - { - Acceptor acceptor = new Acceptor (Class.forName ("imaging.framework.ServerHandler")); - acceptor.open (port); - while (true) - { - acceptor.accept (); - } - } - catch (ClassNotFoundException e) - { - ACE.ERROR (e); - } - catch (SocketException e) - { - ACE.ERROR ("Socket Exception: " + e); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR ("Dang!" + e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - } - - public static void main (String [] args) - { - int port = ACE.DEFAULT_SERVER_PORT; - ServerTest server = new ServerTest (); - - if (args.length == 1) - { - try - { - port = Integer.parseInt (args[0]); - } - catch (NumberFormatException e) - { - server.print_usage_and_die (); - } - } - server.init (port); - } -} diff --git a/java/ImageProcessing/framework/StatusDisplay.java b/java/ImageProcessing/framework/StatusDisplay.java deleted file mode 100644 index e20e9b8384d..00000000000 --- a/java/ImageProcessing/framework/StatusDisplay.java +++ /dev/null @@ -1,23 +0,0 @@ -package imaging.framework; - -import java.awt.*; -import gjt.Separator; - -class StatusDisplay extends Panel -{ - public StatusDisplay () - { - this.setLayout (new BorderLayout ()); - this.textField_.setEditable (false); - this.add ("North", new Separator ()); - this.add ("Center", this.textField_); - this.add ("South", new Separator ()); - } - - public void setText (String s) - { - this.textField_.setText (s); - } - - private TextField textField_ = new TextField (); -} diff --git a/java/ImageProcessing/framework/StatusIndicator.java b/java/ImageProcessing/framework/StatusIndicator.java deleted file mode 100644 index 0f13a71c016..00000000000 --- a/java/ImageProcessing/framework/StatusIndicator.java +++ /dev/null @@ -1,70 +0,0 @@ -package imaging.framework; - -import java.io.*; -import java.awt.*; - -public class StatusIndicator extends Frame -{ - public StatusIndicator (String title, Image image) - { - super (title); - this.image_ = image; - // statusCanvas_ = new CounterCanvas (image); - this.setLayout (new BorderLayout ()); - this.text_ = new TextField (); - this.label_ = new TextField ("Generating"); - - this.add ("North", this.label_); - this.add ("Center", text_); - // this.add ("Center", statusCanvas_); - // this.add ("Center", new Button ("Hello")); - // this.add ("South", new Button ("Hello")); - this.resize (300,200); - this.show (); - } - - public void update (int count) - { - // this.label_.setText ("Generating..."); - this.text_.setText ((new Integer (count++)).toString ()); - // statusCanvas_.update (); - // textCanvas_.setCount (count); - } - - TextField text_; - TextField label_; - Image image_; - // CounterCanvas statusCanvas_ = null; -} - -class CounterCanvas extends Canvas -{ - public CounterCanvas (Image image) - { - this.image_ = image; - } - - public void paint (Graphics g) - { - g.clearRect (0, 0, this.size ().width, this.size ().height); - this.setBackground (Color.white); - - if (this.image_ != null) - g.drawImage(this.image_, - 40, 40, - this.image_.getWidth (this), - this.image_.getHeight (this), - this); - - g.setFont (new Font ("TimesRoman", Font.PLAIN, 18)); - g.drawString ("Generating GIF format: ", 120, 120); - } - - public void update () - { - repaint (); - } - - Image image_ = null; -} - diff --git a/java/ImageProcessing/framework/TestHandler.java b/java/ImageProcessing/framework/TestHandler.java deleted file mode 100644 index 5a97ae6f8b2..00000000000 --- a/java/ImageProcessing/framework/TestHandler.java +++ /dev/null @@ -1,149 +0,0 @@ -package imaging.framework; - -import java.io.*; -import java.net.*; -import java.awt.*; -import java.awt.image.*; -import java.util.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.Timers.*; - -public class TestHandler extends SvcHandler -{ - public TestHandler (String imageList, - String JAWSServer, int JAWSPort, - ImageApp parent) - { - this.imageList_ = imageList; - this.JAWSServer_ = JAWSServer; - this.JAWSPort_ = JAWSPort; - this.parent_ = parent; - this.filterTable_ = this.parent_.filterTable(); - } - - public int open (Object obj) - { - // We got called by the Connector so assume connection was set up - // fine and therfore do not use standard output - stdOut = false; - - doTesting (); - return 0; - } - - public void doTesting () - { - if (imageList_ != null) - { - StringTokenizer tokens = new StringTokenizer (imageList_); - String image = null; - - // Now parse the string, picking up image names. - while (tokens.hasMoreTokens ()) - { - // Get the next token - image = tokens.nextToken (); - this.process (image); - } - } - } - - private void write (String data) - { - try - { - // If we are connected to the server then send the data to the - // server, otherwise write it to standard out. - if (stdOut) - System.out.print (data); - else - this.peer ().send (data); - } - catch (IOException e) - { - ACE.ERROR (e); - } - } - - private void process (String image) - { - this.write ("Image: " + image + "\n"); - - this.loadImage (image); - this.processImage (image); - this.uploadImage (image); - } - - private void loadImage (String image) - { - this.write ("\tLoading..."); - - // Start the timer - timer_.start (); - - // Load the image - parent_.openURL (image); - - // Stop the timer - timer_.stop (); - long time = timer_.elapsedTime (); - - this.write ("done (" + ((double) time)/1000 + " seconds).\n"); - } - - private void processImage (String image) - { - this.write ("\tProcessing...\n"); - - for (Enumeration e = filterTable_.keys (); e.hasMoreElements (); ) - { - String filterName = (String) e.nextElement (); - - this.write ("\t\t" + filterName + "..."); - - ImageFilter filter = (ImageFilter) filterTable_.get (filterName); - - // Reset the image -- in case it was modified earlier - this.parent_.resetImage (); - - // Start the timer - timer_.start (); - - this.parent_.apply (filter); - - // Stop the timer - timer_.stop (); - long time = timer_.elapsedTime (); - - this.write ("done (" + ((double) time)/1000 + " seconds).\n"); - } - } - - private void uploadImage (String image) - { - int index = image.lastIndexOf ("/"); - String imageName = image.substring (index+1); - String url = "http://" + this.JAWSServer_ + ":" + this.JAWSPort_ + "/" + imageName; - this.write ("\tUploading " + url + "..."); - - // Start the timer - timer_.start (); - - this.parent_.saveFile (url); - - // Stop the timer - timer_.stop (); - long time = timer_.elapsedTime (); - - this.write ("done (" + ((double) time)/1000 + " seconds).\n"); - } - - private ImageApp parent_ = null; - private ProfileTimer timer_ = new ProfileTimer (); - private String imageList_ = null; - private boolean stdOut = true; - private Hashtable filterTable_ = null; - private String JAWSServer_ = null; - private int JAWSPort_ = 5432; -} diff --git a/java/ImageProcessing/framework/Tester.java b/java/ImageProcessing/framework/Tester.java deleted file mode 100644 index 79204bb4c5a..00000000000 --- a/java/ImageProcessing/framework/Tester.java +++ /dev/null @@ -1,148 +0,0 @@ -package imaging.framework; - -import java.io.*; -import java.net.*; -import java.awt.*; -import java.awt.image.*; -import java.util.*; -import JACE.Connection.*; -import JACE.OS.*; - -public class Tester implements Runnable -{ - public static final String DEFAULT_TEST_SERVER = "siesta.cs.wustl.edu"; - public static final int DEFAULT_TEST_SERVER_PORT = 7787; - public static final String DEFAULT_JAWS_SERVER = "siesta.cs.wustl.edu"; - public static final int DEFAULT_JAWS_SERVER_PORT = 5432; - - public Tester (String testInFile, - ImageApp parent) - { - this.testInFile_ = testInFile; - this.parent_ = parent; - } - - public void initialize () - { - System.out.println ("Initializing tester..."); - - // Get the hostname of the test server - this.server_ = this.parent_.getParameter ("testServer"); - if (this.server_ == null) - this.server_ = DEFAULT_TEST_SERVER; - - // Get the port number of the test server - String testPortString = this.parent_.getParameter ("testPort"); - if (testPortString == null) - this.port_ = DEFAULT_TEST_SERVER_PORT; - else - this.port_ = (new Integer (testPortString)).intValue (); - - // Get the hostname of the JAWS server - this.JAWSServer_ = this.parent_.getParameter ("JAWSServer"); - if (this.JAWSServer_ == null) - this.JAWSServer_ = DEFAULT_JAWS_SERVER; - - // Get the port number of the JAWS server - String JAWSPortString = this.parent_.getParameter ("JAWSPort"); - if (JAWSPortString == null) - this.JAWSServerPort_ = DEFAULT_JAWS_SERVER_PORT; - else - this.JAWSServerPort_ = (new Integer (JAWSPortString)).intValue (); - - System.out.println ("Test Input File: " + this.testInFile_); - System.out.println ("Test Server: " + this.server_ + "\tPort: " + this.port_); - System.out.println ("JAWS Server: " + this.JAWSServer_ + "\tPort: " + this.JAWSServerPort_); - - // Run in your own thread of control - (new Thread (this)).start (); - } - - public void run () - { - this.setupConnection (this.getImages ()); - } - - private String getImages () - { - URL inputURL; - String imageList = null; - try - { - // Create input URL - inputURL = new URL (this.testInFile_); - - // Get the input stream and pipe it to a DataInputStream - DataInputStream iStream = new DataInputStream (inputURL.openStream ()); - - // Create a buffer to hold all the data we get - StringBuffer tempBuf = new StringBuffer (); - // Keep reading the data until we are done - String tempString = iStream.readLine (); - while (tempString != null) - { - tempBuf.append (tempString); - tempBuf.append (" "); - tempString = iStream.readLine (); - } - imageList = tempBuf.toString (); - } - catch (MalformedURLException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - return imageList; - } - - private void setupConnection (String imageList) - { - // First try to connect to the server. If the server is not - // running then we will write to standard output. - - // Create a handler which will handle our connection. - TestHandler handler = new TestHandler (imageList, - this.JAWSServer_, this.JAWSServerPort_, - this.parent_); - try - { - Connector connector = new Connector (); - connector.open (server_, port_); - connector.connect (handler); - } - catch (UnknownHostException e) - { - ACE.ERROR (e); - } - catch (SocketException e) - { - System.out.println ("Test Server not running! Writing to standard out..."); - // The server is not running so write all the output to screen - handler.doTesting (); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - } - - private String testInFile_ = null; - private ImageApp parent_ = null; - private String server_ = "siesta.cs.wustl.edu"; - private int port_ = 7787; - - private String JAWSServer_ = "siesta.cs.wustl.edu"; - private int JAWSServerPort_ = 5432; -} - diff --git a/java/ImageProcessing/framework/doc01.gif b/java/ImageProcessing/framework/doc01.gif Binary files differdeleted file mode 100644 index 51262529f6d..00000000000 --- a/java/ImageProcessing/framework/doc01.gif +++ /dev/null diff --git a/java/ImageProcessing/framework/file03.gif b/java/ImageProcessing/framework/file03.gif Binary files differdeleted file mode 100644 index c98654c604b..00000000000 --- a/java/ImageProcessing/framework/file03.gif +++ /dev/null diff --git a/java/ImageProcessing/framework/filter.conf b/java/ImageProcessing/framework/filter.conf deleted file mode 100644 index 2e90ea136ce..00000000000 --- a/java/ImageProcessing/framework/filter.conf +++ /dev/null @@ -1,15 +0,0 @@ -imaging.filters.EmbossFilter -imaging.filters.BleachFilter -imaging.filters.BlurFilter -imaging.filters.DarkenFilter -imaging.filters.DeSpeckleFilter -imaging.filters.EdgeDetectFilter -imaging.filters.OilPaintFilter -imaging.filters.PixelizeFilter -imaging.filters.RotateFilter -imaging.filters.SharpenFilter -imaging.filters.SpreadFilter - - - - diff --git a/java/ImageProcessing/framework/help.conf b/java/ImageProcessing/framework/help.conf deleted file mode 100644 index 8a07e2867d9..00000000000 --- a/java/ImageProcessing/framework/help.conf +++ /dev/null @@ -1,216 +0,0 @@ - MedJava - ~~~~~~~ - -Overview --------- - -MedJava is a prototype of a large scale distributed medical imaging -system. It has been developed using Java, in particular, several -components of Java ACE. - -Here are the key features of the MedJava toolkit: - -* Images can be both downloaded and uploaded across the network. -* Images can be uploaded to Web servers that support HTTP PUT - functionality (for example, JAWS). -* The tool contains more than a dozen image filters to do image - processing. -* The image filters can be configured into the system dynamically - using the Service Configurator pattern. - -Please send comments/suggestions to Prashant Jain (pjain@cs.wustl.edu). - -====================================================================== -Getting Started ---------------- - -MedJava applet can be configured with several (optional) parameters -via the HTML file from which the applet is invoked. Here is a list of -the parameters: - -Note: - 1) * indicates test-mode parameters - 2) All Default URLs begin with - http://www.cs.wustl.edu/~pjain/java/ACE_wrappers/java/ImageProcessing/framework/ - -<START> -Name -<TAB> -<TAB> -Description -<TAB> -<TAB> -<TAB> -<TAB> -Default -<P> --------------------------------------------------------------- -<P> -configFile -<TAB> -<TAB> -Specifies a URL that points to the filter -<P> -<TAB> -<TAB> -configuration file. -<TAB> -<TAB> -<TAB> -<TAB> -<TAB> -filter.conf -<P> -<P> -*testFile -<TAB> -<TAB> -Specifies a URL that points to the file that contains -<P> -<TAB> -<TAB> -a list of images that need to be tested. -<TAB> -<TAB> -<TAB> -testImages.conf -<P> -<P> -*testServer -<TAB> -Specifies the name of the test server. -<TAB> -<TAB> -<TAB> -siesta.cs.wustl.edu -<P> -<P> -*testPort -<TAB> -<TAB> -Specifies the port number of the test server. -<TAB> -<TAB> -<TAB> -7789 -<P> -<P> -*JAWSServer -<TAB> -Specifies the name of the server to use in -<P> -<TAB> -<TAB> -doing image uploading during testing. -<TAB> -<TAB> -<TAB> -siesta.cs.wustl.edu -<P> -<P> -*JAWSPort -<TAB> -Specifies the port number of the server to use -<P> -<TAB> -<TAB> -in doing image uploading during testing. -<TAB> -<TAB> -<TAB> -5432 -<P> -====================================================================== -<END> - -Menu ----- - -o Open URL - - Allows user to specify a URL. If the URL points to an image that is - readable, then the image is downloaded and displayed in the view - panel. - - If the URL points to a directory that is readable then a window - appears displaying a list of files in that directory. The user can - then click on an image file in this window to fetch an image. - - IMPORTANT NOTE: If the URL points to a directory, the directory must - not contain an "index.html" file! If it does, the - query will fail and no list of files will appear. - -o Save - - Allows user to specify a URL to save the currently loaded image to. - All images are saved in GIF format. Note that saving/uploading a - file can take a while depending upon the size of the image. This is - because, the tool first generates the GIF format and then sends the - bytes across the network. - - IMPORTANT NOTE: The Web server must support image uploading, that is - HTTP PUT functionality. Also, due to applet - restrictions, the server MUST be running on the same - host from which the applet was downloaded from. - -o Reset - - Resets the image to the original. Note that the effects of any - filters that were applied to the image will be lost. - -o Reload Filters - - Reads the filter configuration file again and reloads all the image - filters. Note that this serves as the trigger of the Service - Configurator pattern allowing the tool to reconfigure based on new - configuration information. - - The filters are specified in filter.conf. To add/remove filters, - change this file and then select "Reload Filters". - - To specify a different configuration file, please see "Getting Started". - -o Zoom In - - Zooms in to the currently displayed image. Note that the applet only - allows to zoom in 4 x times. - -o Zoom Out - - Zooms out of the currently displayed image. Note that the applet - only allows to zoom out 1/4 x times. - -o Apply - - Apply the currently selected filter. By default no filter is - selected. Note that applying a filter to an image can taken - anywhere between a few seconds to a few minutes depending upon the - image size, the filter type, and the speed of the machine on which - the applet is running. - -o Filters: - - Allows the user to select a filter from the ones that have been - configured into the applet. Note that this is a choice menu and its - entries depend upon the filters that were specified in the filter - configuration file. - - For more information, on how to specify the filters, please see - "Getting Started". - -o About - - Displays the "About" dialog containing the version of the MedJava - applet. - -o Help - - Displays this window - -====================================================================== - -Limitations ------------ - -In several browsers, for images larger than 100 KB, the Java virtual -machine may run out of memory while doing image processing. diff --git a/java/ImageProcessing/framework/test.html b/java/ImageProcessing/framework/test.html deleted file mode 100644 index 7a9acf34e38..00000000000 --- a/java/ImageProcessing/framework/test.html +++ /dev/null @@ -1,19 +0,0 @@ -<HTML> - -<BODY text = "#000000" -link="#000fff" -vlink="#ff0f0f" -bgcolor="#888888"> - -<HR> -<APPLET CODEBASE="../../classes" CODE="imaging.framework.ImageApp.class" width=700 height=700> -<param name=configFile value="http://www.cs.wustl.edu/~pjain/java/ACE_wrappers/java/ImageProcessing/framework/testFilter.conf"> -<param name=testFile value="http://www.cs.wustl.edu/~pjain/java/ACE_wrappers/java/ImageProcessing/framework/testImages.conf"> -<param name=testServer value="siesta.cs.wustl.edu"> -<param name=testPort value="7789"> -<param name=JAWSServer value="siesta.cs.wustl.edu"> -<param name=JAWSPort value="5432"> -</APPLET> -<HR> - -</HTML>
\ No newline at end of file diff --git a/java/ImageProcessing/framework/testFilter.conf b/java/ImageProcessing/framework/testFilter.conf deleted file mode 100644 index 2e90ea136ce..00000000000 --- a/java/ImageProcessing/framework/testFilter.conf +++ /dev/null @@ -1,15 +0,0 @@ -imaging.filters.EmbossFilter -imaging.filters.BleachFilter -imaging.filters.BlurFilter -imaging.filters.DarkenFilter -imaging.filters.DeSpeckleFilter -imaging.filters.EdgeDetectFilter -imaging.filters.OilPaintFilter -imaging.filters.PixelizeFilter -imaging.filters.RotateFilter -imaging.filters.SharpenFilter -imaging.filters.SpreadFilter - - - - diff --git a/java/JACE/ASX/IOCntlCmds.java b/java/JACE/ASX/IOCntlCmds.java deleted file mode 100644 index 3cc7c76256d..00000000000 --- a/java/JACE/ASX/IOCntlCmds.java +++ /dev/null @@ -1,38 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * TaskFlags.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -/** - * Constants used for IOCTL messages. - * - *@see JACE.ASX.IOCntlMsg - */ -public abstract class IOCntlCmds -{ - /** Set the low water mark. */ - public static final int SET_LWM = 1; - - /** Get the low water mark. */ - public static final int GET_LWM = 2; - - /** Set the high water mark. */ - public static final int SET_HWM = 3; - - /** Get the high water mark. */ - public static final int GET_HWM = 4; - - /** Link modules */ - public static final int MOD_LINK = 5; - - /** Unlink modules */ - public static final int MOD_UNLINK = 6; -} diff --git a/java/JACE/ASX/IOCntlMsg.java b/java/JACE/ASX/IOCntlMsg.java deleted file mode 100644 index 4eea18b36f6..00000000000 --- a/java/JACE/ASX/IOCntlMsg.java +++ /dev/null @@ -1,124 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * IOCntlMsg.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; - -/** - * Data format for IOCTL messages. - */ -public class IOCntlMsg -{ - - // = Initialization method. - - /* - * Initialize the control message. - *@param c IOCntlCmd for the control message. Note that this should - * be of type IOCntlCmds - */ - public IOCntlMsg (int c) - { - this.cmd_ = c; - } - - // = Get/set methods - - /* - * Get the command. - *@return the command. - */ - public int cmd () - { - return this.cmd_; - } - - /* - * Set the command. - *@param c the command. - */ - public void cmd (int c) - { - this.cmd_ = c; - } - - /* - * Get the count. - *@return the count. - */ - public int count () - { - return this.count_; - } - - /* - * Set the count. - *@param c the count. - */ - public void count (int c) - { - this.count_ = c; - } - - /* - * Get the error. - *@return the error. - */ - public int error () - { - return this.error_; - } - - /* - * Set the error. - *@param e the error. - */ - public void error (int e) - { - this.error_ = e; - } - - /* - * Get the return value. - *@return the return value. - */ - public int rval () - { - return this.rval_; - } - - /* - * Set the return value. - *@param r the return value. - */ - public void rval (int r) - { - this.rval_ = r; - } - - public String toString () - { - return (new Integer (this.cmd_)).toString (); - } - - private int cmd_; - // Command. - - private int count_; - // Count. - - private int error_; - // Error. - - private int rval_; - // Return value -} diff --git a/java/JACE/ASX/MessageBlock.java b/java/JACE/ASX/MessageBlock.java deleted file mode 100644 index 4035e34a7bd..00000000000 --- a/java/JACE/ASX/MessageBlock.java +++ /dev/null @@ -1,447 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * MessageBlock.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; - -/** - * Object used to store messages in the ASX framework.<P> - * - * <tt>MessageBlock</tt> is modeled after the message data structures - * used in System V STREAMS. A <tt>MessageBlock</tt> is composed of - * one or more <tt>MessageBlock</tt>s that are linked together by - * <em>PREV</em> and <em>NEXT</em> pointers. In addition, a - * <tt>MessageBlock</tt> may also be linked to a chain of other - * <tt>MessageBlock</tt>s. This structure enables efficient manipulation - * of arbitrarily-large messages <em>without</em> incurring memory - * copying overhead. - * - *@see MessageQueue - */ -public class MessageBlock -{ - /** - * Create an empty Message Block - */ - public MessageBlock () - { - this (0); - } - - /** - * Create an empty Message Block. - * Note that this assumes that type of MessageBlock is MB_DATA. - *@param size size of the Message Block to create. - */ - public MessageBlock (int size) - { - // Note the explicit cast toString() is needed. For some strange - // reason, it fails otherwise if size == 0. - this ((new StringBuffer (size)).toString ()); - } - - /** - * Create a Message Block. Note that this assumes that type of - * MessageBlock is MB_DATA. - *@param data initial data to create a Message Block with. - */ - public MessageBlock (String data) - { - this (MessageType.MB_DATA, - null, - data); - } - - /** - * Create a Message Block. - *@param type type of the Message Block (must be one of those - * specified in class Message Type) - *@param cont next block of data - *@param data initial data to create Message Block with - */ - public MessageBlock (int type, - MessageBlock cont, - String data) - { - this.flags_ = 0; - this.priority_ = 0; - this.next_ = null; - this.prev_ = null; - - this.init (type, cont, data); - } - - /** - * Create a Message Block. Note that this assumes that type of - * MessageBlock is MB_OBJECT. - *@param obj initial object to create a Message Block with. - */ - public MessageBlock (Object obj) - { - this (MessageType.MB_OBJECT, - null, - obj); - } - - /** - * Create a Message Block. - *@param type type of the Message Block (must be one of those - * specified in class Message Type) - *@param cont next block of data - *@param obj initial object to create Message Block with - */ - public MessageBlock (int type, - MessageBlock cont, - Object obj) - { - this.init (type, cont, obj); - } - - /* Initialize the Message Block - *@param data data to initialize Message Block with - */ - public void init (String data) - { - this.base_ = new StringBuffer (data); - } - - /** - * Initialize a Message Block. - *@param type type of the Message Block (must be one of those - * specified in class Message Type) - *@param cont next block of data - *@param data data to initialize Message Block with - */ - public void init (int msgType, - MessageBlock msgCont, - String data) - { - if (data.length () == 0) - this.base_ = new StringBuffer (0); - else - this.base_ = new StringBuffer (data); - this.type_ = msgType; - this.cont_ = msgCont; - } - - /** - * Initialize a Message Block. Note that this assumes that type of - * MessageBlock is MB_OBJECT. - *@param obj initial object to initialize a Message Block with. - */ - public void init (Object obj) - { - this.init (MessageType.MB_OBJECT, null, obj); - } - - /** - * Initialize a Message Block. - *@param type type of the Message Block (must be one of those - * specified in class Message Type) - *@param cont next block of data - *@param obj object to initialize Message Block with - */ - public void init (int msgType, - MessageBlock msgCont, - Object obj) - { - this.obj_ = obj; - this.type_ = msgType; - this.cont_ = msgCont; - this.flags_ = 0; - this.priority_ = 0; - this.next_ = null; - this.prev_ = null; - } - - /** - * Set message flags. Note that the flags will be set on top of - * already set flags. - *@param moreFlags flags to set for the Message Block. - */ - public long setFlags (long moreFlags) - { - // Later we might mask more_flags so that user can't change - // internal ones: more_flags &= ~(USER_FLAGS -1). - this.flags_ = ACE.SET_BITS (this.flags_, moreFlags); - return this.flags_; - } - - /** - * Unset message flags. - *@param lessFlags flags to unset for the Message Block. - */ - public long clrFlags (long lessFlags) - { - // Later we might mask more_flags so that user can't change - // internal ones: less_flags &= ~(USER_FLAGS -1). - this.flags_ = ACE.CLR_BITS (this.flags_, lessFlags); - return this.flags_; - } - - /** - * Get the message flags. - *@return Message flags - */ - public long flags () - { - return this.flags_; - } - - /** - * Get the type of the message. - *@return message type - */ - public int msgType () - { - return this.type_; - } - - /** - * Set the type of the message. - *@param t type of the message - */ - public void msgType (int t) - { - this.type_ = t; - } - - /** - * Get the class of the message. Note there are two classes, - * <normal> messages and <high-priority> messages. - *@return message class - */ - public int msgClass () - { - return this.msgType () >= MessageType.MB_PRIORITY - ? MessageType.MB_PRIORITY : MessageType.MB_NORMAL; - } - - /** - * Find out if the message is a data message. - *@return true if message is a data message, false otherwise - */ - public boolean isDataMsg () - { - int mt = this.msgType (); - return mt == MessageType.MB_DATA - || mt == MessageType.MB_PROTO - || mt == MessageType.MB_PCPROTO; - } - - /** - * Find out if the message is an object message. - *@return true if message is an object message, false otherwise - */ - public boolean isObjMsg () - { - int mt = this.msgType (); - return mt == MessageType.MB_OBJECT - || mt == MessageType.MB_PROTO - || mt == MessageType.MB_PCPROTO; - } - - /** - * Get the priority of the message. - *@return message priority - */ - public long msgPriority () - { - return this.priority_; - } - - /** - * Set the priority of the message. - *@param pri priority of the message - */ - public void msgPriority (long pri) - { - this.priority_ = pri; - } - - /** - * Get message data. This assumes that msgType is MB_DATA. - *@return message data - */ - public String base () - { - // Create a String object to return - char temp[] = new char [this.base_.length ()]; - this.base_.getChars (0, this.base_.length (), temp, 0); - return new String (temp); - } - - /** - * Set the message data. This assumes that msgType is MB_DATA. - *@param data message data - *@param msgFlags message flags - */ - public void base (String data, - long msgFlags) - { - this.base_ = new StringBuffer (data); - this.flags_ = msgFlags; - } - - /** - * Get message object. This assumes that msgType is MB_OBJECT. - *@return message object - */ - public Object obj () - { - return this.obj_; - } - - /** - * Set the message object. This assumes that msgType is MB_OBJECT. - *@param object message object - *@param msgFlags message flags - */ - public void obj (Object obj, - long msgFlags) - { - this.obj_ = obj; - this.flags_ = msgFlags; - } - - // = The following four methods only make sense if the Message_Block - // is of type MB_DATA and not MB_OBJECT. - - /** - * Get length of the message. This method only makes sense if the - * MessageBlock is of type MB_DATA and not MB_OBJECT. - *@return length of the message. - */ - public int length () - { - return this.base_.length (); - } - - /** - * Set the length of the message. This method only makes sense if the - * MessageBlock is of type MB_DATA and not MB_OBJECT. - *@param n message length - */ - public void length (int n) - { - this.base_.setLength (n); - } - - /** - * Get size of the allocated buffer for the message. This method - * only makes sense if the MessageBlock is of type MB_DATA and not - * MB_OBJECT. - *@return size of the message buffer - */ - public int size () - { - return this.base_.capacity (); - } - - /** - * Set the total size of the buffer. This method will grow the - * buffer if need be. Also, this method only makes sense if the - * MessageBlock is of type MB_DATA and not MB_OBJECT. - *@param n size of message buffer - */ - public void size (int n) - { - this.base_.ensureCapacity (n); - } - - - /** - * Get the continuation field. The coninuation field is used to - * chain together composite messages. - *@return the continuation field - */ - public MessageBlock cont () - { - return this.cont_; - } - - /** - * Set the continuation field. The coninuation field is used to - * chain together composite messages. - *@param msgCont continuation field - */ - void cont (MessageBlock msgCont) - { - this.cont_ = msgCont; - } - - /** - * Get link to next message. The next message points to the - * <MessageBlock> directly ahead in the MessageQueue. - *@return next message block - */ - MessageBlock next () - { - return this.next_; - } - - /** - * Set link to next message. The next message points to the - * <MessageBlock> directly ahead in the MessageQueue. - *@param msgBlock next message block - */ - void next (MessageBlock msgBlock) - { - this.next_ = msgBlock; - } - - /** - * Get link to previous message. The previous message points to the - * <MessageBlock> directly before in the MessageQueue. - *@return previous message block - */ - MessageBlock prev () - { - return this.prev_; - } - - /** - * Set link to previous message. The previous message points to the - * <MessageBlock> directly before in the MessageQueue. - *@param msgBlock previous message block - */ - void prev (MessageBlock msgBlock) - { - this.prev_ = msgBlock; - } - - private int type_; - // Type of message. - - private long flags_; - // Misc flags. - - private long priority_; - // Priority of message. - - private StringBuffer base_; - // String data of message block (initialized to null). - - private Object obj_; - // Object data of message block (initialized to null). - - private MessageBlock cont_; - // Next message block in the chain. - - private MessageBlock next_; - // Next message in the list. - - private MessageBlock prev_; - // Previous message in the list. - -} - diff --git a/java/JACE/ASX/MessageQueue.java b/java/JACE/ASX/MessageQueue.java deleted file mode 100644 index df25870dd52..00000000000 --- a/java/JACE/ASX/MessageQueue.java +++ /dev/null @@ -1,633 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * MessageQueue.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import java.util.Date; -import JACE.OS.*; -import JACE.Reactor.*; - -class NotFullCondition extends TimedWait -{ - public NotFullCondition (MessageQueue mq) - { - super (mq); - this.mq_ = mq; - } - - public boolean condition () { - // Delegate to the appropriate conditional - // check on the MessageQueue. - return !this.mq_.isFull (); - } - private MessageQueue mq_; -} - -class NotEmptyCondition extends TimedWait -{ - public NotEmptyCondition (MessageQueue mq) - { - super (mq); - this.mq_ = mq; - } - - public boolean condition () { - // Delegate to the appropriate conditional - // check on the MessageQueue. - return !this.mq_.isEmpty (); - } - private MessageQueue mq_; -} - - -/** - * A thread-safe message queueing facility, modeled after the - * queueing facilities in System V StreamS. <P> - * - * <tt>MessageQueue</tt> is the central queueing facility for messages - * in the ASX framework. All operations are thread-safe, as it is intended - * to be used for inter-thread communication (<em>e.g.</em>, a producer and - * consumer thread joined by a <tt>MessageQueue</tt>). The queue - * consists of <tt>MessageBlock</tt>s. - *</blockquote> - * - *@see MessageBlock - *@see TimeValue - */ -public class MessageQueue -{ - /** - * Default constructor - */ - public MessageQueue () - { - this (DEFAULT_HWM, DEFAULT_LWM); - } - - /** - * Create a Message Queue with high and low water marks. - *@param hwm High water mark (max number of bytes allowed in the - * queue) - *@param lwm Low water mark (min number of bytes in the queue) - */ - public MessageQueue (int hwm, int lwm) - { - if (this.open (hwm, lwm) == -1) - ACE.ERROR ("open"); - } - - /** - * Initialize a Message Queue with high and low water marks. - *@param hwm High water mark (max number of bytes allowed in the - * queue) - *@param lwm Low water mark (min number of bytes in the queue) - */ - public synchronized int open (int hwm, int lwm) - { - this.highWaterMark_ = hwm; - this.lowWaterMark_ = lwm; - this.deactivated_ = false; - this.currentBytes_ = 0; - this.currentCount_ = 0; - this.tail_ = null; - this.head_ = null; - return 0; - } - - // ************ Note! *********** - // = For enqueue, enqueueHead, enqueueTail, and dequeueHead if - // timeout is specified, the caller will wait until the *absolute time* - // tv. Calls will return, however, when queue is closed, - // deactivated, or if it is past the time tv - - /** - * Enqueue a <MessageBlock> into the <MessageQueue> in accordance - * with its <msgPriority> (0 is lowest priority). Note that the - * call will block (unless the queue has been deactivated). - * - *@exception java.lang.InterruptedException Interrupted while accessing queue - *@param newItem item to enqueue onto the Message Queue - *@return -1 on failure, else the number of items still on the queue. - */ - public synchronized int enqueue (MessageBlock newItem) throws InterruptedException - { - return this.enqueue (newItem, null); - } - - /** - * Enqueue a <MessageBlock> into the <MessageQueue> in accordance - * with its <msgPriority> (0 is lowest priority). Note that the - * call will return if the queue has been deactivated or it is - * later than the specified absolute time value. - *@param newItem item to enqueue onto the Message Queue - *@param tv absolute TimeValue to timeout after - *@return -1 on failure, else the number of items still on the - * queue. - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - public synchronized int enqueue (MessageBlock newItem, - TimeValue tv) throws InterruptedException - { - int result = -1; - if (this.deactivated_) - return -1; - try - { - if (tv == null) // Need to do a blocking wait - notFullCondition_.timedWait (); - else // Need to do a timed wait - notFullCondition_.timedWait (tv); - } - catch (TimeoutException e) - { - return -1; - } - - // Check again if queue is still active - if (this.deactivated_) - return -1; - else - result = this.enqueueInternal (newItem); - - // Tell any blocked threads that the queue has a new item! - this.notEmptyCondition_.broadcast (); - return result; - } - - /** - * Enqueue a <MessageBlock> at the end of the <MessageQueue>. Note - * that the call will block (unless the queue has been deactivated). - *@param newItem item to enqueue onto the Message Queue - *@return -1 on failure, else the number of items still on the queue. - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - public synchronized int enqueueTail (MessageBlock newItem) throws InterruptedException - { - return this.enqueueTail (newItem, null); - } - - /** - * Enqueue a <MessageBlock> at the end of the <MessageQueue>. Note - * that the call will return when it's later than the given TimeValue or - * if the queue has been deactivated. - *@param newItem item to enqueue onto the Message Queue - *@param tv absolute TimeValue to wait until before returning (unless - * the operation compeltes before this time) - *@return -1 on failure, else the number of items still on the queue. - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - public synchronized int enqueueTail (MessageBlock newItem, - TimeValue tv) throws InterruptedException - { - int result = -1; - if (this.deactivated_) - return -1; - try - { - if (tv == null) // Need to do a blocking wait - notFullCondition_.timedWait (); - else // Need to do a timed wait - notFullCondition_.timedWait (tv); - } - catch (TimeoutException e) - { - return -1; - } - - // Check again if queue is still active - if (this.deactivated_) - return -1; - else - result = this.enqueueTailInternal (newItem); - - // Tell any blocked threads that the queue has a new item! - this.notEmptyCondition_.broadcast (); - return result; - } - - /** - * Enqueue a <MessageBlock> at the head of the <MessageQueue>. Note - * that the call will block (unless the queue has been deactivated). - *@param newItem item to enqueue onto the Message Queue - *@return -1 on failure, else the number of items still on the queue. - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - public synchronized int enqueueHead (MessageBlock newItem) throws InterruptedException - { - return this.enqueueHead (newItem, null); - } - - /** - * Enqueue a <MessageBlock> at the head of the <MessageQueue>. Note - * that the call will return when it's later than the given TimeValue or - * if the queue has been deactivated. - *@param newItem item to enqueue onto the Message Queue - *@param tv absolute TimeValue to wait until before returning (unless - * the operation completes before that time) - *@return -1 on failure, else the number of items still on the queue. - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - public synchronized int enqueueHead (MessageBlock newItem, - TimeValue tv) throws InterruptedException - { - int result = -1; - if (this.deactivated_) - return -1; - try - { - if (tv == null) // Need to do a blocking wait - notFullCondition_.timedWait (); - else // Need to do a timed wait - notFullCondition_.timedWait (tv); - } - catch (TimeoutException e) - { - return -1; - } - - // Check again if queue is still active - if (this.deactivated_) - return -1; - else - result = this.enqueueHeadInternal (newItem); - - // Tell any blocked threads that the queue has a new item! - this.notEmptyCondition_.broadcast (); - return result; - } - - /** - * Dequeue and return the <MessageBlock> at the head of the - * <MessageQueue>. Note that the call will block (unless the queue - * has been deactivated). - *@return null on failure, else the <MessageBlock> at the head of queue. - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - public synchronized MessageBlock dequeueHead () throws InterruptedException - { - return this.dequeueHead (null); - } - - /** - * Dequeue and return the <MessageBlock> at the head of the - * <MessageQueue>. Note that the call when return if the queue has - * been deactivated or when the current time is later than the given - * time value. - *@param tv absolute time timeout (blocks indefinitely if null) - *@return null on failure, else the <MessageBlock> at the head of queue. - *@exception InterruptedException Interrupted while accessing queue - */ - public synchronized MessageBlock dequeueHead (TimeValue tv) - throws InterruptedException - { - MessageBlock result = null; - if (this.deactivated_) - return null; - try - { - if (tv == null) // Need to do a blocking wait - notEmptyCondition_.timedWait (); - else // Need to do a timed wait - notEmptyCondition_.timedWait (tv); - } - catch (TimeoutException e) - { - return null; - } - - // Check again if queue is still active - if (this.deactivated_) - return null; - else - result = this.dequeueHeadInternal (); - - // Tell any blocked threads that the queue has room for an item! - this.notFullCondition_.broadcast (); - return result; - } - - /** - * Check if queue is full. - *@return true if queue is full, else false. - */ - public synchronized boolean isFull () - { - return this.isFullInternal (); - } - - /** - * Check if queue is empty. - *@return true if queue is empty, else false. - */ - public synchronized boolean isEmpty () - { - return this.isEmptyInternal (); - } - - /** - * Get total number of bytes on the queue. - *@return total number number of bytes on the queue - */ - public int messageBytes () - { - return this.currentBytes_; - } - - /** - * Get total number of messages on the queue. - *@return total number number of messages on the queue - */ - public int messageCount () - { - return this.currentCount_; - } - - // = Flow control routines - - /** - * Get high watermark. - *@return high watermark - */ - public int highWaterMark () - { - return this.highWaterMark_; - } - - /** - * Set high watermark. - *@param hwm high watermark - */ - public void highWaterMark (int hwm) - { - this.highWaterMark_ = hwm; - } - - /** - * Get low watermark. - *@return low watermark - */ - public int lowWaterMark () - { - return this.lowWaterMark_; - } - - /** - * Set low watermark. - *@param lwm low watermark - */ - public void lowWaterMark (int lwm) - { - this.lowWaterMark_ = lwm; - } - - // = Activation control methods. - - /** - * Deactivate the queue and wakeup all threads waiting on the queue - * so they can continue. No messages are removed from the queue, - * however. Any other operations called until the queue is - * activated again will immediately return -1. - *@return WAS_INACTIVE if queue was inactive before the call and - * WAS_ACTIVE if queue was active before the call. - */ - public synchronized int deactivate () - { - return this.deactivateInternal (); - } - - - /** - * Reactivate the queue so that threads can enqueue and dequeue - * messages again. - *@return WAS_INACTIVE if queue was inactive before the call and - * WAS_ACTIVE if queue was active before the call. - */ - public synchronized int activate () - { - return this.activateInternal (); - } - - protected boolean isEmptyInternal () - { - // Not sure about this one!!!! - return this.currentBytes_ <= this.lowWaterMark_ && this.currentCount_ <= 0; - } - - protected boolean isFullInternal () - { - return this.currentBytes_ > this.highWaterMark_; - } - - protected int deactivateInternal () - { - int currentStatus = - this.deactivated_ ? WAS_INACTIVE : WAS_ACTIVE; - - this.notFullCondition_.broadcast (); - this.notEmptyCondition_.broadcast (); - - this.deactivated_ = true; - return currentStatus; - } - - protected int activateInternal () - { - int currentStatus = - this.deactivated_ ? WAS_INACTIVE : WAS_ACTIVE; - this.deactivated_ = false; - - return currentStatus; - } - - protected int enqueueTailInternal (MessageBlock newItem) - { - if (newItem == null) - return -1; - - // List was empty, so build a new one. - if (this.tail_ == null) - { - this.head_ = newItem; - this.tail_ = newItem; - newItem.next (null); - newItem.prev (null); - } - // Link at the end. - else - { - newItem.next (null); - this.tail_.next (newItem); - newItem.prev (this.tail_); - this.tail_ = newItem; - } - - if (newItem.msgType() != MessageType.MB_OBJECT) - { - // Make sure to count *all* the bytes in a composite message!!! - for (MessageBlock temp = newItem; - temp != null; - temp = temp.cont ()) - this.currentBytes_ += temp.size (); - } - - this.currentCount_++; - return this.currentCount_; - } - - protected int enqueueHeadInternal (MessageBlock newItem) - { - if (newItem == null) - return -1; - - newItem.prev (null); - newItem.next (this.head_); - - if (this.head_ != null) - this.head_.prev (newItem); - else - this.tail_ = newItem; - - this.head_ = newItem; - - if (newItem.msgType() != MessageType.MB_OBJECT) - { - // Make sure to count *all* the bytes in a composite message!!! - for (MessageBlock temp = newItem; - temp != null; - temp = temp.cont ()) - this.currentBytes_ += temp.size (); - } - - this.currentCount_++; - - return this.currentCount_; - } - - protected int enqueueInternal (MessageBlock newItem) - { - if (newItem == null) - return -1; - - if (this.head_ == null) - // Check for simple case of an empty queue, where all we need to - // do is insert <newItem> into the head. - return this.enqueueHeadInternal (newItem); - else - { - MessageBlock temp; - - // Figure out where the new item goes relative to its priority. - - for (temp = this.head_; - temp != null; - temp = temp.next ()) - { - if (temp.msgPriority () <= newItem.msgPriority ()) - // Break out when we've located an item that has lower - // priority that <newItem>. - break; - } - - if (temp == null) - // Check for simple case of inserting at the end of the queue, - // where all we need to do is insert <newItem> after the - // current tail. - return this.enqueueTailInternal (newItem); - else if (temp.prev () == null) - // Check for simple case of inserting at the beginning of the - // queue, where all we need to do is insert <newItem> before - // the current head. - return this.enqueueHeadInternal (newItem); - else - { - // Insert the message right before the item of equal or lower - // priority. - newItem.next (temp); - newItem.prev (temp.prev ()); - temp.prev ().next (newItem); - temp.prev (newItem); - } - } - - if (newItem.msgType() != MessageType.MB_OBJECT) - { - // Make sure to count *all* the bytes in a composite message!!! - for (MessageBlock temp = newItem; - temp != null; - temp = temp.cont ()) - this.currentBytes_ += temp.size (); - } - - this.currentCount_++; - return this.currentCount_; - } - - protected MessageBlock dequeueHeadInternal () - { - MessageBlock firstItem = this.head_; - this.head_ = this.head_.next (); - - if (this.head_ == null) - this.tail_ = null; - - if (firstItem.msgType() != MessageType.MB_OBJECT) - { - // Make sure to subtract off all of the bytes associated with this - // message. - for (MessageBlock temp = firstItem; - temp != null; - temp = temp.cont ()) - this.currentBytes_ -= temp.size (); - } - - this.currentCount_--; - return firstItem; - } - - - /** Default high watermark (16 K). */ - public final static int DEFAULT_HWM = 16 * 1024; - - /** Default low watermark. */ - public final static int DEFAULT_LWM = 0; - - /** Message queue was active before activate() or deactivate(). */ - public final static int WAS_ACTIVE = 1; - - /** Message queue was inactive before activate() or deactivate(). */ - public final static int WAS_INACTIVE = 2; - - private int highWaterMark_; - // Greatest number of bytes before blocking. - - private int lowWaterMark_; - // Lowest number of bytes before unblocking occurs. - - private boolean deactivated_; - // Indicates that the queue is inactive. - - private int currentBytes_; - // Current number of bytes in the queue. - - private int currentCount_; - // Current number of messages in the queue. - - private MessageBlock head_; - // Head of Message_Block list. - - private MessageBlock tail_; - // Tail of Message_Block list. - - // The Delegated Notification mechanisms. - private NotFullCondition notFullCondition_ = new NotFullCondition (this); - private NotEmptyCondition notEmptyCondition_ = new NotEmptyCondition (this); - -} diff --git a/java/JACE/ASX/MessageType.java b/java/JACE/ASX/MessageType.java deleted file mode 100644 index 97e33a6c6ba..00000000000 --- a/java/JACE/ASX/MessageType.java +++ /dev/null @@ -1,102 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * MessageType.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -/** - * Message types used by MessageBlock. <P> - * - * Defines bit masks used to identify various types of messages.<P> - * - * This class is not intended to be instantiable. - * - *@see MessageBlock - */ -public class MessageType -{ - // = Data and protocol messages (regular and priority) - /** regular data */ - public static final int MB_DATA = 0x01; - - /** protocol control */ - public static final int MB_PROTO = 0x02; - - /** regular data */ - public static final int MB_OBJECT = 0x09; - - - // = Control messages (regular and priority) - /** line break */ - public static final int MB_BREAK = 0x03; - - /** pass file pointer */ - public static final int MB_PASSFP = 0x04; - - /** post an event to an event queue */ - public static final int MB_EVENT = 0x05; - - /** generate process signal */ - public static final int MB_SIG = 0x06; - - /** ioctl; set/get params */ - public static final int MB_IOCTL = 0x07; - - /** set various stream head options */ - public static final int MB_SETOPTS = 0x08; - - - // = Control messages (high priority; go to head of queue) - /** acknowledge ioctl */ - public static final int MB_IOCACK = 0x81; - - /** negative ioctl acknowledge */ - public static final int MB_IOCNAK = 0x82; - - /** priority proto message */ - public static final int MB_PCPROTO = 0x83; - - /** generate process signal */ - public static final int MB_PCSIG = 0x84; - - /** generate read notification */ - public static final int MB_READ = 0x85; - - /** flush your queues */ - public static final int MB_FLUSH = 0x86; - - /** stop transmission immediately */ - public static final int MB_STOP = 0x87; - - /** restart transmission after stop */ - public static final int MB_START = 0x88; - - /** line disconnect */ - public static final int MB_HANGUP = 0x89; - - /** fatal error used to set u.u_error */ - public static final int MB_ERROR = 0x8a; - - /** post an event to an event queue */ - public static final int MB_PCEVENT = 0x8b; - - - /** Normal priority messages */ - public static final int MB_NORMAL = 0x00; - - /** High priority control messages */ - public static final int MB_PRIORITY = 0x80; - - // Default private constructor to avoid instantiation - private MessageType () - { - } -} - diff --git a/java/JACE/ASX/Module.java b/java/JACE/ASX/Module.java deleted file mode 100644 index 2b80cd690c9..00000000000 --- a/java/JACE/ASX/Module.java +++ /dev/null @@ -1,246 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * Module.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; - -/** - * Provides an abstraction for managing a bi-directional flow of - * messages. <P> - * - * This is based on the Module concept in System V Streams, - * which contains a pair of Tasks, one for handling upstream - * processing, one for handling downstream processing. - */ -public class Module -{ - // = Initialization and termination methods. - - /** - * Create an empty Module. - */ - public Module () - { - // Do nothing... - this.name ("<unknown>"); - } - - /* - * Create an initialized module. - *@param modName identity of the module. - *@param writerQ writer task of the module. - *@param readerQ reader task of the module. - *@param flags Module flags - */ - public Module (String modName, - Task writerQ, - Task readerQ, - Object flags) - { - this.open (modName, writerQ, readerQ, flags); - } - - /* - * Create an initialized module. - *@param modName identity of the module. - *@param writerQ writer task of the module. - *@param readerQ reader task of the module. - *@param flags Module flags - */ - public void open (String modName, - Task writerQ, - Task readerQ, - Object arg) - { - this.name (modName); - this.arg_ = arg; - - if (writerQ == null) - writerQ = new ThruTask (); - if (readerQ == null) - readerQ = new ThruTask (); - - this.reader (readerQ); - this.writer (writerQ); - - // Setup back pointers. - readerQ.module (this); - writerQ.module (this); - } - - - /* - * Set the writer task. - *@param q the writer task - */ - public void writer (Task q) - { - this.qPair_[1] = q; - if (q != null) - q.flags (ACE.CLR_BITS (q.flags (), TaskFlags.ACE_READER)); - } - - /* - * Set the reader task. - *@param q the reader task - */ - public void reader (Task q) - { - this.qPair_[0] = q; - if (q != null) - q.flags (ACE.SET_BITS (q.flags (), TaskFlags.ACE_READER)); - } - - /* - * Link this Module on top of Module. - *@param m the module to link this on top of. - */ - public void link (Module m) - { - this.next (m); - this.writer ().next (m.writer ()); - m.reader ().next (this.reader ()); - } - - /* - * Set and get pointer to sibling Task in Module. - *@param orig the task to get the sibling for - *@return the sibling of the task - */ - public Task sibling (Task orig) - { - if (this.qPair_[0] == orig) - return this.qPair_[1]; - else if (this.qPair_[1] == orig) - return this.qPair_[0]; - else - return null; - } - - /* - * Close down the module and its tasks. - *@param flags Module flags - *@return 0 on success, -1 on failure - */ - public int close (long flags) - { - Task readerQ = this.reader (); - Task writerQ = this.writer (); - int result = 0; - - if (readerQ != null) - { - if (readerQ.close (flags) == -1) - result = -1; - readerQ.flush (flags); - readerQ.next (null); - } - - if (writerQ != null) - { - if (writerQ.close (flags) == -1) - result = -1; - writerQ.flush (flags); - writerQ.next (null); - } - - return result; - } - - /* - * Get the argument passed to tasks. - *@return the argument passed to tasks. - */ - public Object arg () - { - return this.arg_; - } - - /* - * Set the argument to be passed to tasks. - *@param a the argument to be passed to tasks. - */ - public void arg (Object a) - { - this.arg_ = a; - } - - /* - * Get the name of the module. - *@return the name of the module. - */ - public String name () - { - return this.name_; - } - - /* - * Set the name of the module. - *@param n the name of the module. - */ - public void name (String n) - { - this.name_ = n; - } - - /* - * Get the writer task of the module. - *@return the writer task of the module. - */ - public Task writer () - { - return this.qPair_[1]; - } - - /* - * Get the reader task of the module. - *@return the reader task of the module. - */ - public Task reader () - { - return this.qPair_[0]; - } - - /* - * Get the next pointer to the module above in the stream. - *@return the next pointer to the module above in the stream. - */ - public Module next () - { - return this.next_; - } - - /* - * Set the next pointer to the module above in the stream. - *@param m the next pointer to the module above in the stream. - */ - public void next (Module m) - { - this.next_ = m; - } - - private Task qPair_[] = new Task[2]; - // Pair of Tasks that form the "read-side" and "write-side" of the - // ACE_Module partitioning. - - private String name_ = null; - // Name of the ACE_Module. - - private Module next_; - // Next ACE_Module in the stack. - - private Object arg_; - // Argument passed through to the reader and writer task when they - // are opened. - -} - diff --git a/java/JACE/ASX/Stream.java b/java/JACE/ASX/Stream.java deleted file mode 100644 index 6a968714ab7..00000000000 --- a/java/JACE/ASX/Stream.java +++ /dev/null @@ -1,436 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * Stream.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; - -/** - * This class is the primary abstraction for the ASX framework. - * It is moduled after System V Stream. <P> - * - * A Stream consists of a stack of Modules, each of which - * contains two Tasks. - * - *@see Module - *@see Task - */ - -public class Stream -{ - - public Stream () - { - this (null, null, null); - } - - // Create a Stream consisting of <head> and <tail> as the Stream - // head and Stream tail, respectively. If these are 0 then the - // <ACE_Stream_Head> and <ACE_Stream_Tail> are used, respectively. - // <arg> is the value past in to the open() methods of the tasks. - - public Stream (Object a, - Module head, - Module tail) - { - this.linkedUs_ = null; - // this.final_close_ = this.lock_; - - if (this.open (a, head, tail) == -1) - ACE.ERROR ("open" + head.name () + " " + tail.name ()); - } - - public int push (Module newTop) - { - if (this.pushModule (newTop, - this.streamHead_.next (), - this.streamHead_) == -1) - return -1; - else - return 0; - } - - // Note that the timeout tv is absolute time - public int put (MessageBlock mb, TimeValue tv) - { - return this.streamHead_.writer ().put (mb, tv); - } - - // Note that the timeout tv is absolute time - public MessageBlock get (TimeValue tv) throws InterruptedException - { - return this.streamHead_.reader ().getq (tv); - } - -// Return the "top" ACE_Module in a ACE_Stream, skipping over the -// stream_head. - - public Module top () - { - if (this.streamHead_.next () == this.streamTail_) - return null; - else - return this.streamHead_.next (); - } - -// Remove the "top" ACE_Module in a ACE_Stream, skipping over the -// stream_head. - - public int pop (long flags) - { - if (this.streamHead_.next () == this.streamTail_) - return -1; - else - { - // Skip over the ACE_Stream head. - Module top = this.streamHead_.next (); - Module newTop = top.next (); - - this.streamHead_.next (newTop); - - // Close the top ACE_Module. - - top.close (flags); - - this.streamHead_.writer ().next (newTop.writer ()); - newTop.reader ().next (this.streamHead_.reader ()); - - return 0; - } - } - -// Remove a named ACE_Module from an arbitrary place in the -// ACE_Stream. - - public int remove (String name, long flags) - { - Module prev = null; - - for (Module mod = this.streamHead_; - mod != null; mod = mod.next ()) - if (name.compareTo (mod.name ()) == 0) - { - if (prev == null) // Deleting ACE_Stream Head - this.streamHead_.link (mod.next ()); - else - prev.link (mod.next ()); - - mod.close (flags); - return 0; - } - else - prev = mod; - - return -1; - } - - public Module find (String name) - { - for (Module mod = this.streamHead_; - mod != null; - mod = mod.next ()) - if (name.compareTo (mod.name ()) == 0) - return mod; - - return null; - } - -// Actually push a module onto the stack... - - private int pushModule (Module newTop, - Module currentTop, - Module head) - { - Task ntReader = newTop.reader (); - Task ntWriter = newTop.writer (); - Task ctReader = null; - Task ctWriter = null; - - if (currentTop != null) - { - ctReader = currentTop.reader (); - ctWriter = currentTop.writer (); - ctReader.next (ntReader); - } - - ntWriter.next (ctWriter); - - if (head != null) - { - if (head != newTop) - head.link (newTop); - } - else - ntReader.next (null); - - newTop.next (currentTop); - - if (ntReader.open (newTop.arg ()) == -1) - return -1; - - if (ntWriter.open (newTop.arg ()) == -1) - return -1; - return 0; - } - - public synchronized int open (Object a, - Module head, - Module tail) - { - Task h1 = null, h2 = null; - Task t1 = null, t2 = null; - - if (head == null) - { - h1 = new StreamHead (); - h2 = new StreamHead (); - head = new Module ("ACEStreamHead", h1, h2, a); - } - - if (tail == null) - { - t1 = new StreamTail (); - t2 = new StreamTail (); - tail = new Module ("ACEStreamTail", - t1, t2, a); - } - - // Make sure *all* the allocation succeeded! - if (h1 == null || h2 == null || head == null - || t1 == null || t2 == null || tail == null) - { - // Close up! - head.close (0); - tail.close (0); - return -1; - } - - this.streamHead_ = head; - this.streamTail_ = tail; - - if (this.pushModule (this.streamTail_, - null, null) == -1) - return -1; - else if (this.pushModule (this.streamHead_, - this.streamTail_, - this.streamHead_) == -1) - return -1; - else - return 0; - } - - public synchronized int close (long flags) - { - if (this.streamHead_ != null - && this.streamTail_ != null) - { - // Don't bother checking return value here. - this.unlinkInternal (); - - int result = 0; - - // Remove and cleanup all the intermediate modules. - - while (this.streamHead_.next () != this.streamTail_) - { - if (this.pop (flags) == -1) - result = -1; - } - - // Clean up the head and tail of the stream. - if (this.streamHead_.close (flags) == -1) - result = -1; - if (this.streamTail_.close (flags) == -1) - result = -1; - - this.streamHead_ = null; - this.streamTail_ = null; - - // Tell all threads waiting on the close that we are done. - // this.final_close_.broadcast (); - return result; - } - return 0; - } - - public int control (int cmd, Object a) throws InterruptedException - { - IOCntlMsg ioc = new IOCntlMsg (cmd); - - // Create a data block that contains the user-supplied data. - MessageBlock db = - new MessageBlock (MessageType.MB_IOCTL, - null, - a); - - // Create a control block that contains the control field and a - // pointer to the data block. - MessageBlock cb = - new MessageBlock (MessageType.MB_IOCTL, - db, - (Object) ioc); - - int result = 0; - - if (this.streamHead_.writer ().put (cb, null) == -1) - result = -1; - else if ((cb = this.streamHead_.reader ().getq (null)) == null) - result = -1; - else - result = ((IOCntlMsg ) cb.obj ()).rval (); - - return result; - } - -// Link two streams together at their bottom-most Modules (i.e., the -// one just above the Stream tail). Note that all of this is premised -// on the fact that the Stream head and Stream tail are non-NULL... -// This must be called with locks held. - - private int linkInternal (Stream us) - { - this.linkedUs_ = us; - // Make sure the other side is also linked to us! - us.linkedUs_ = this; - - Module myTail = this.streamHead_; - - if (myTail == null) - return -1; - - // Locate the module just above our Stream tail. - while (myTail.next () != this.streamTail_) - myTail = myTail.next (); - - Module otherTail = us.streamHead_; - - if (otherTail == null) - return -1; - - // Locate the module just above the other Stream's tail. - while (otherTail.next () != us.streamTail_) - otherTail = otherTail.next (); - - // Reattach the pointers so that the two streams are linked! - myTail.writer ().next (otherTail.reader ()); - otherTail.writer ().next (myTail.reader ()); - return 0; - } - - public synchronized int link (Stream us) - { - return this.linkInternal (us); - } - -// Must be called with locks held... - - private int unlinkInternal () - { - // Only try to unlink if we are in fact still linked! - - if (this.linkedUs_ != null) - { - Module myTail = this.streamHead_; - - // Only relink if we still exist! - if (myTail != null) - { - // Find the module that's just before our stream tail. - while (myTail.next () != this.streamTail_) - myTail = myTail.next (); - - // Restore the writer's next() link to our tail. - myTail.writer ().next (this.streamTail_.writer ()); - } - - Module otherTail = this.linkedUs_.streamHead_; - - // Only fiddle with the other side if it in fact still remains. - if (otherTail != null) - { - while (otherTail.next () != this.linkedUs_.streamTail_) - otherTail = otherTail.next (); - - otherTail.writer ().next (this.linkedUs_.streamTail_.writer ()); - - } - - // Make sure the other side is also aware that it's been unlinked! - this.linkedUs_.linkedUs_ = null; - - this.linkedUs_ = null; - return 0; - } - else - return -1; - } - - public synchronized int unlink () - { - return this.unlinkInternal (); - } - - public void dump () - { - ACE.DEBUG ("-------- module links --------"); - - for (Module mp = this.streamHead_; ; mp = mp.next ()) - { - ACE.DEBUG ("module name = " + mp.name ()); - if (mp == this.streamTail_) - break; - } - - ACE.DEBUG ("-------- writer links --------"); - - Task tp; - - for (tp = this.streamHead_.writer (); ; tp = tp.next ()) - { - ACE.DEBUG ("writer queue name = " + tp.name ()); - tp.dump (); - ACE.DEBUG ("-------\n"); - if (tp == this.streamTail_.writer () - || (this.linkedUs_ != null && tp == this.linkedUs_.streamHead_.reader ())) - break; - } - - ACE.DEBUG ("-------- reader links --------\n"); - for (tp = this.streamTail_.reader (); ; tp = tp.next ()) - { - ACE.DEBUG ("reader queue name = " + tp.name ()); - tp.dump (); - ACE.DEBUG ("-------\n"); - if (tp == this.streamHead_.reader () - || (this.linkedUs_ != null && tp == this.linkedUs_.streamHead_.writer ())) - break; - } - } - - Module streamHead_ = null; - // Pointer to the head of the stream. - - Module streamTail_ = null; - // Pointer to the tail of the stream. - - Stream linkedUs_ = null; - // Pointer to an adjoining linked stream. - - // = Synchronization objects used for thread-safe streams. - // ACE_SYNCH_MUTEX lock_; - // Protect the stream against race conditions. - - // ACE_SYNCH_CONDITION final_close_; - // Use to tell all threads waiting on the close that we are done. - -} - - diff --git a/java/JACE/ASX/StreamHead.java b/java/JACE/ASX/StreamHead.java deleted file mode 100644 index 1492b43a297..00000000000 --- a/java/JACE/ASX/StreamHead.java +++ /dev/null @@ -1,123 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * StreamHead.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; - -/** - * Standard module that acts as the head of a ustream. - */ - -public class StreamHead extends Task -{ - // Module that acts as the head of a Stream. - - public int open (Object obj) - { - return 0; - } - - public int close (long l) - { - return 0; - } - - public int svc () - { - return -1; - } - - private int control (MessageBlock mb) - { - - IOCntlMsg ioc = (IOCntlMsg) mb.obj (); - int cmd = ioc.cmd (); - - switch (cmd) - { - case IOCntlCmds.SET_LWM: - case IOCntlCmds.SET_HWM: - this.waterMarks (cmd, mb.cont ().length ()); - ioc.rval (0); - break; - default: - return 0; - } - return ioc.rval (); - } - - /* Performs canonical flushing at the ACE_Stream Head */ - - private int canonicalFlush (MessageBlock mb) - { - String s = mb.base (); - long f = (new Long (s)).longValue (); - - if ((f & TaskFlags.ACE_FLUSHR) != 0) - { - this.flush (TaskFlags.ACE_FLUSHALL); - f &= ~TaskFlags.ACE_FLUSHR; - } - if ((f & TaskFlags.ACE_FLUSHW) != 0) - return this.reply (mb, null); - return 0; - } - - // Will block forever to add the given MessageBlock - public int put (MessageBlock mb) - { - return this.put (mb, null); - } - - // tv is absolute time - public int put (MessageBlock mb, TimeValue tv) - { - int res = 0; - if (mb.msgType () == MessageType.MB_IOCTL - && (res = this.control (mb)) == -1) - return res; - - if (this.isWriter ()) - { - return this.putNext (mb, tv); - } - else /* this.isReader () */ - { - switch (mb.msgType ()) - { - case MessageType.MB_FLUSH: - return this.canonicalFlush (mb); - default: - break; - } - - try - { - return this.putq (mb, tv); - } - catch (InterruptedException e) - { - return -1; - } - } - } - - public void dump () - { - } - - public int handleTimeout (TimeValue tv, Object obj) - { - return 0; - } - -} diff --git a/java/JACE/ASX/StreamTail.java b/java/JACE/ASX/StreamTail.java deleted file mode 100644 index c1148a4c0f1..00000000000 --- a/java/JACE/ASX/StreamTail.java +++ /dev/null @@ -1,114 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * StreamTail.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; - -/** - * Standard module that acts as the tail of a ustream. - */ -public class StreamTail extends Task -{ - // Module that acts as the tail of a Stream. - - public int open (Object obj) - { - return 0; - } - - public int close (long l) - { - return 0; - } - - public int svc () - { - return -1; - } - - private int control (MessageBlock mb) - { - IOCntlMsg ioc = (IOCntlMsg) mb.obj (); - int cmd = ioc.cmd (); - - switch (cmd) - { - case IOCntlCmds.SET_LWM: - case IOCntlCmds.SET_HWM: - { - int size = mb.cont ().length (); - - this.waterMarks (cmd, size); - this.sibling ().waterMarks (cmd, size); - ioc.rval (0); - break; - } - default: - mb.msgType (MessageType.MB_IOCNAK); - } - return this.reply (mb, null); - } - - // Perform flush algorithm as though we were the driver - private int canonicalFlush (MessageBlock mb) - { - String s = mb.base (); - long f = (new Long (s)).longValue (); - - if ((f & TaskFlags.ACE_FLUSHW) != 0) - { - this.flush (TaskFlags.ACE_FLUSHALL); - f &= ~TaskFlags.ACE_FLUSHW; - } - if ((f & TaskFlags.ACE_FLUSHR) != 0) - { - this.sibling ().flush (TaskFlags.ACE_FLUSHALL); - return this.reply (mb, null); - } - return 0; - } - - // put the given MessageBlock without a timeout (block forever if - // necessary) - public int put (MessageBlock mb) - { - return this.put (mb, null); - } - - // tv is an absolute time timeout - public int put (MessageBlock mb, TimeValue tv) - { - if (this.isWriter ()) - { - switch (mb.msgType ()) - { - case MessageType.MB_IOCTL: - return this.control (mb); - /* NOTREACHED */ - default: - break; - } - } - - return -1; - } - - public void dump () - { - } - - public int handleTimeout (TimeValue tv, Object obj) - { - return 0; - } - -} diff --git a/java/JACE/ASX/Task.java b/java/JACE/ASX/Task.java deleted file mode 100644 index b13de64f16a..00000000000 --- a/java/JACE/ASX/Task.java +++ /dev/null @@ -1,443 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * Task.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; -import JACE.Reactor.*; -import JACE.Concurrency.*; - -/** - * Primary interface for application message processing, as well - * as input and output message queueing. <P> - * - * This class serves as the basis for passive and active objects - * in ACE. - * - *@see MessageQueue - *@see EventHandler - */ -public abstract class Task implements Runnable, EventHandler -{ - // = Initialization/termination methods. - - /** - * Initialize a Task. Note, we allocate a message queue ourselves. - */ - public Task () - { - this.msgQueue_ = new MessageQueue (); - this.thrMgr_ = null; - } - - /** - * Initialize a Task. Note, we use the message queue and thread - * manager supplied by the user. - *@param mq Message Queue to hold list of messages on the Task - *@param thrMgr Thread Manager that manages all the spawned threads - */ - public Task (MessageQueue mq, - ThreadManager thrMgr) - { - this.msgQueue_ = mq; - this.thrMgr_ = thrMgr; - } - - /** - * Not meant to be invoked by the user directly!. This needs to be - * in the public interface in order to get invoked by Thread - * class. - */ - public void run () - { - this.svc (); - } - - // = Initialization and termination hooks (note that these *must* be - // defined by subclasses). - - /** - * Hook called to open a Task. - *@param obj used to pass arbitrary information - */ - public abstract int open (Object obj); - - /** - * Hook called to close a Task. - */ - public abstract int close (long flags); - - // = Immediate and deferred processing methods, respectively. - - /** - * Transfer a message into the queue to handle immediate - * processing. - *@param mb Message Block to handle immediately - *@param tv Latest time to wait until (absolute time) - */ - public abstract int put (MessageBlock mb, TimeValue tv); - - /** - * Run by a daemon thread to handle deferred processing. Note, that - * to do anything useful, this method should be overriden by the - * subclass. - *@return default implementation always returns 0. - */ - public int svc () - { - return 0; - } - - /** - * Set the underlying Thread Manager. - *@param t Thread Manager to use - */ - public synchronized void thrMgr (ThreadManager t) - { - this.thrMgr_ = t; - } - - /** - * Get the Thread Manager. - *@return Underlying Thread Manager - */ - public synchronized ThreadManager thrMgr () - { - return this.thrMgr_; - } - - // = Active object method. - - /** - * Turn the task into an active object. That is, having <nThreads> - * separate threads of control that all invoke Task::svc. - *@param flags Task Flags - *@param nThreads number of threads to spawn - *@param forceActive whether to force creation of new threads or not - *@return -1 if failure occurs, 1 if Task is already an active - * object and <forceActive> is false (doesn't *not* create a new - * thread in this case), and 0 if Task was not already an active - * object and a thread is created successfully or thread is an active - * object and <forceActive> is true. - */ - public synchronized int activate (long flags, int nThreads, boolean forceActive) - { - // Create a Thread Manager if we do not already have one - if (this.thrMgr_ == null) - this.thrMgr_ = new ThreadManager (); - - if (this.thrCount () > 0 && forceActive == false) - return 1; // Already active. - this.flags_ = flags; - - if (ACE.BIT_ENABLED (flags, TaskFlags.THR_DAEMON)) - this.thrMgr_.spawnN (nThreads, this, true); // Spawn off all threads as daemon threads - else // Spawn off all threads as normal threads - this.thrMgr_.spawnN (nThreads, this, false); - - return 0; - } - - // = Suspend/resume a Task - - /** - * Suspend a task. Default implementation is a no-op. - */ - public synchronized void suspend () - { - } - - /** - * Resume a suspended task. Default implementation is a no-op. - */ - public synchronized void resume () - { - } - - /** - * Get the current group name. - *@return name of the current thread group - */ - public synchronized String grpName () - { - if (this.thrMgr_ != null) - return this.thrMgr_.thrGrp ().getName (); - else - return null; - } - - /** - * Get the message queue associated with this task. - *@return the message queue associated with this task. - */ - public MessageQueue msgQueue () - { - return this.msgQueue_; - } - - /** - * Set the message queue associated with this task. - *@param mq Message Queue to use with this Task. - */ - public void msgQueue (MessageQueue mq) - { - this.msgQueue_ = mq; - } - - /** - * Get the number of threads currently running within the Task. - *@return the number of threads currently running within the Task. - * 0 if we're a passive object, else > 0. - */ - public synchronized int thrCount () - { - if (this.thrMgr_ != null) - return this.thrMgr_.thrGrp ().activeCount (); - else - return 0; - } - - /** - * Set the Task flags - *@param flags Task Flags - */ - public synchronized void flags (long flags) - { - this.flags_ = flags; - } - - /** - * Get the Task flags - *@return Task Flags - */ - public synchronized long flags () - { - return this.flags_; - } - - // = Message queue manipulation methods. - - - /* - * Dump debug information. - */ - public void dump () - { - } - - /** - * Insert a message into the queue, blocking forever if necessary. - *@param mb Message Block to insert - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - protected int putq (MessageBlock mb) throws InterruptedException - { - return this.putq(mb, null); - } - - /** - * Insert message into the message queue. - *@param mb Message Block to insert into the Message Queue - *@param tv time to wait until (absolute time) - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - protected int putq (MessageBlock mb, TimeValue tv) throws InterruptedException - { - return this.msgQueue_.enqueueTail (mb, tv); - } - - /** - * Extract the first message from the queue, blocking forever if - * necessary. - *@return the first Message Block from the Message Queue. - *@exception InterrupteException Interrupted while accessing queue - */ - protected MessageBlock getq() throws InterruptedException - { - return this.getq(null); - } - - /** - * Extract the first message from the queue. Note that the call is blocking. - *@return the first Message Block from the Message Queue. - *@param tv Latest time to wait until (absolute time) - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - protected MessageBlock getq (TimeValue tv) throws InterruptedException - { - return this.msgQueue_.dequeueHead (tv); - } - - /** - * Return a message back to the queue. - *@param mb Message Block to return back to the Message Queue - *@param tv Latest time to wait until (absolute time) - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - protected int ungetq (MessageBlock mb, TimeValue tv) throws InterruptedException - { - return this.msgQueue_.enqueueHead (mb, tv); - } - - /** - * Transfer message to the adjacent ACETask in an ACEStream. - *@param mb Message Block to transfer to the adjacent Task - *@param tv Latest time to wait until (absolute time) - *@return -1 if there is no adjacent Task, else the return value of - * trying to put the Message Block on that Task's Message Queue. - */ - protected int putNext (MessageBlock mb, TimeValue tv) - { - return this.next_ == null ? -1 : this.next_.put (mb, tv); - } - - /** - * Turn the message back around. Puts the message in the sibling's - * Message Queue. - *@param mb Message Block to put into sibling's Message Queue - *@param tv Latest time to wait until (absolute time) - *@return -1 if there is no adjacent Task to the sibling, else the - * return value of trying to put the Message Block on sibling's - * Message Queue. - */ - protected int reply (MessageBlock mb, TimeValue tv) - { - return this.sibling ().putNext (mb, tv); - } - - // = ACE_Task utility routines to identify names et al. - - /** - * Get the name of the enclosing Module. - *@return the name of the enclosing Module if there's one associated - * with the Task, else null. - */ - protected String name () - { - if (this.mod_ == null) - return null; - else - return this.mod_.name (); - } - - /** - * Get the Task's sibling. - *@return the Task's sibling if there's one associated with the - * Task's Module, else null. - */ - protected Task sibling () - { - if (this.mod_ == null) - return null; - else - return this.mod_.sibling (this); - } - - /** - * Set the Task's module. - *@param mod the Task's Module. - */ - protected void module (Module mod) - { - this.mod_ = mod; - } - - /** - * Get the Task's module. - *@return the Task's Module if there is one, else null. - */ - protected Module module () - { - return this.mod_; - } - - /** - * Check if queue is a reader. - *@return true if queue is a reader, else false. - */ - protected boolean isReader () - { - return (ACE.BIT_ENABLED (this.flags_, TaskFlags.ACE_READER)); - } - - /** - * Check if queue is a writer. - *@return true if queue is a writer, else false. - */ - protected boolean isWriter () - { - return (ACE.BIT_DISABLED (this.flags_, TaskFlags.ACE_READER)); - } - - // = Pointers to next ACE_Queue (if ACE is part of an ACE_Stream). - - /** - * Get next Task pointer. - *@return pointer to the next Task - */ - protected Task next () - { - return this.next_; - } - - /** - * Set next Task pointer. - *@param task next task pointer - */ - protected void next (Task task) - { - this.next_ = task; - } - - // Special routines corresponding to certain message types. - - /** - * Flush the Message Queue - *@return 0 if Message Queue is null, 1 if flush succeeds, -1 if - * ACE_FLUSHALL bit is not enabled in flags. - */ - protected int flush (long flag) - { - if (ACE.BIT_ENABLED (flag, TaskFlags.ACE_FLUSHALL)) - return (this.msgQueue_ == null ? 0 : 1); - else - return -1; - } - - - /** - * Manipulate watermarks. - *@param cmd IOCntlCmd - *@param size watermark - */ - protected void waterMarks (int cmd, int size) - { - if (cmd == IOCntlCmds.SET_LWM) - this.msgQueue_.lowWaterMark (size); - else /* cmd == IOCntlMsg.SET_HWM */ - this.msgQueue_.highWaterMark (size); - } - - private ThreadManager thrMgr_ = null; - // Thread_Manager that manages all the spawned threads - - private long flags_; - // Task flags. - - private MessageQueue msgQueue_; - // List of messages on the Task.. - - private Task next_; - // Adjacent ACE_Task. - - private Module mod_; - // Back-pointer to the enclosing module. -} diff --git a/java/JACE/ASX/TaskFlags.java b/java/JACE/ASX/TaskFlags.java deleted file mode 100644 index 13347283adf..00000000000 --- a/java/JACE/ASX/TaskFlags.java +++ /dev/null @@ -1,49 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * TaskFlags.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -/** - * Flags used within Task. - * - *@see Task - */ -public abstract class TaskFlags -{ - /** Identifies a Task as being the "reader" in a Module. */ - public static final int ACE_READER = 01; - - /** Just flush data messages in the queue. */ - public static final int ACE_FLUSHDATA = 02; - - /** Flush all messages in the Queue. */ - public static final int ACE_FLUSHALL = 04; - - /** Flush read queue */ - public static final int ACE_FLUSHR = 010; - - /** Flush write queue */ - public static final int ACE_FLUSHW = 020; - - /** Flush both queues */ - public static final int ACE_FLUSHRW = 030; - - /** Identifies a thread as suspended */ - public static final int THR_SUSPENDED = 0x00000080; - - /** Identifies a thread as a daemon thread */ - public static final int THR_DAEMON = 0x00000100; - - // Default private constructor to avoid instantiation - private TaskFlags () - { - } -} diff --git a/java/JACE/ASX/ThruTask.java b/java/JACE/ASX/ThruTask.java deleted file mode 100644 index 3fd0bbd4476..00000000000 --- a/java/JACE/ASX/ThruTask.java +++ /dev/null @@ -1,44 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * ThruTask.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -/** - * Standard module that acts as a "no op", simply passing on all - * data to its adjacent neighbor. - */ -public class ThruTask extends Task -{ - public int open (Object obj) - { - return 0; - } - - public int close (long flags) - { - return 0; - } - - public int put (MessageBlock msg, TimeValue tv) - { - return this.putNext (msg, tv); - } - - public int svc () - { - return -1; - } - - public int handleTimeout (TimeValue tv, Object obj) - { - return 0; - } -} diff --git a/java/JACE/ASX/TimeValue.java b/java/JACE/ASX/TimeValue.java deleted file mode 100644 index 452f80447c4..00000000000 --- a/java/JACE/ASX/TimeValue.java +++ /dev/null @@ -1,296 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Reactor - * - * = FILENAME - * TimeValue.java - * - *@author Prashant Jain - * - *************************************************/ -//package JACE.Reactor; -package JACE.ASX; - -/** - * Encapsulates a specific time or time interval. <P> - * - * Also provides methods for generating absolute times from - * relative times. This is used throughout JACE for timeouts. - * - *@see TimedWait - */ -public class TimeValue -{ - /** - * TimeValue representing 0 seconds and 0 nanoseconds. - */ - public final static TimeValue zero = new TimeValue (0,0); - - /** - * Default constructor. This creates a TimeValue that is - * equal to TimeValue.zero. - */ - public TimeValue () - { - this (0, 0); - } - - /** - * Constructor - *@param sec seconds - */ - public TimeValue (long sec) - { - this (sec, 0); - } - - /** - * Constructor - *@param sec seconds - *@param nanos nanoseconds - */ - public TimeValue (long sec, int nanos) - { - this.set (sec, nanos); - } - - /** - * Sets the seconds and nanoseconds of Time Value - *@param sec seconds - *@param nanos nanoseconds - */ - public void set (long sec, int nanos) - { - this.millisec_ = sec * 1000; - this.nanos_ = nanos; - this.normalize (); - } - - /** - * Get seconds - *@return Seconds - */ - public long sec () - { - return this.millisec_/1000; - } - - /** - * Get nanoseconds - *@return Nanoseconds - */ - public int nanos () - { - return this.nanos_; - } - - /** - * Get time in milliseconds. - *@return time in milliseconds - */ - public long getMilliTime () - { - return this.millisec_; - } - - /** - * Get a String representation of the Time Value. - *@return String representation of the Time Value - */ - public String toString () - { - return (new Long (this.millisec_/1000)).toString () + ":" + - (new Integer (this.nanos_)).toString (); - } - - /** - * Get current time. - *@return the current system time as a new TimeValue - */ - public static TimeValue getTimeOfDay () - { - return new TimeValue (System.currentTimeMillis ()/1000); - } - - /** - * Return a new TimeValue that represents the current system time - * of day offset by the given number of seconds and nanoseconds. - *@param sec Number of seconds to offset by - *@param nanos Number of nanoseconds to offset by - *@see JACE.ASX.TimeValue - *@return TimeValue for the system time plus the given offset - */ - public static TimeValue relativeTimeOfDay(long sec, int nanos) - { - return new TimeValue ((System.currentTimeMillis() / 1000) + sec, - nanos); - } - - /** - * Return a new TimeValue that represents the current system time - * of day offset by the given TimeValue. - *@param tv TimeValue to offset by - *@see JACE.ASX.TimeValue - *@return TimeValue for the system time plus the given offset - */ - public static TimeValue relativeTimeOfDay(TimeValue offset) - { - return new TimeValue ((System.currentTimeMillis() / 1000) + - offset.sec(), - offset.nanos()); - } - - /** - * Compare two Time Values for equality. - *@param tv Time Value to compare with - *@return true if the two Time Values are equal, false otherwise - */ - public boolean equals (TimeValue tv) - { - return this.millisec_ == (tv.sec () * 1000) && this.nanos_ == tv.nanos (); - } - - /** - * Compare two Time Values for non-equality. - *@param tv Time Value to compare with - *@return true if the two Time Values are not equal, false otherwise - */ - public boolean notEquals (TimeValue tv) - { - return !this.equals (tv); - } - - /** - * Add two Time Values. - *@param tv1 The first Time Value - *@param tv2 The second Time Value - *@return sum of the two Time Values. - */ - public static TimeValue plus (TimeValue tv1, TimeValue tv2) - { - TimeValue tv = new TimeValue (tv1.sec () + tv2.sec (), - tv1.nanos () + tv2.nanos ()); - tv.normalize (); - return tv; - } - - /** - * Subtract two Time Values. - *@param tv1 The first Time Value - *@param tv2 The second Time Value - *@return difference of the two Time Values. - */ - public static TimeValue minus (TimeValue tv1, TimeValue tv2) - { - TimeValue tv = new TimeValue (tv1.sec () - tv2.sec (), - tv1.nanos () - tv2.nanos ()); - tv.normalize (); - return tv; - } - - /** - * Add Time Value to "this". - *@param tv The Time Value to add to this. - */ - public void plusEquals (TimeValue tv) - { - this.set (this.sec () + tv.sec (), - this.nanos () + tv.nanos ()); - this.normalize (); - } - - /** - * Subtract Time Value from "this". - *@param tv The Time Value to subtract from this. - */ - public void minusEquals (TimeValue tv) - { - this.set (this.sec () - tv.sec (), - this.nanos () - tv.nanos ()); - this.normalize (); - } - - /** - * Compare two Time Values for less than. - *@param tv Time Value to compare with - *@return true if "this" is less than tv, false otherwise - */ - public boolean lessThan (TimeValue tv) - { - return tv.greaterThan (this); - } - - /** - * Compare two Time Values for greater than. - *@param tv Time Value to compare with - *@return true if "this" is greater than tv, false otherwise - */ - public boolean greaterThan (TimeValue tv) - { - if (this.sec () > tv.sec ()) - return true; - else if (this.sec () == tv.sec () - && this.nanos () > tv.nanos ()) - return true; - else - return false; - } - - /** - * Compare two Time Values for <=. - *@param tv Time Value to compare with - *@return true if "this" <= tv, false otherwise - */ - public boolean lessThanEqual (TimeValue tv) - { - return tv.greaterThanEqual (this); - } - - /** - * Compare two Time Values for >=. - *@param tv Time Value to compare with - *@return true if "this" >= tv, false otherwise - */ - public boolean greaterThanEqual (TimeValue tv) - { - return this.sec () >= tv.sec () && this.nanos () >= tv.nanos (); - } - - private void normalize () - { - if (this.nanos_ >= ONE_MILLISECOND) - { - do - { - this.millisec_++; - this.nanos_ -= ONE_MILLISECOND; - } - while (this.nanos_ >= ONE_MILLISECOND); - } - else if (this.nanos_ <= -ONE_MILLISECOND) - { - do - { - this.millisec_--; - this.nanos_ += ONE_MILLISECOND; - } - while (this.nanos_ <= -ONE_MILLISECOND); - } - - if (this.millisec_ >= 1 && this.nanos_ < 0) - { - this.millisec_--; - this.nanos_ += ONE_MILLISECOND; - } - else if (this.millisec_ < 0 && this.nanos_ > 0) - { - this.millisec_++; - this.nanos_ -= ONE_MILLISECOND; - } - } - - private long millisec_; - private int nanos_; - private final static int ONE_MILLISECOND = 1000000; -} diff --git a/java/JACE/ASX/TimedWait.java b/java/JACE/ASX/TimedWait.java deleted file mode 100644 index dc1d0bab673..00000000000 --- a/java/JACE/ASX/TimedWait.java +++ /dev/null @@ -1,157 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * TimedWait.java - * - *@author Prashant Jain and Doug Schmidt - * - *************************************************/ -package JACE.ASX; - -/** - * A wait/notify system with absolute time timeouts and built-in - * check of a condition. <P> - * - * Subclasses define the condition to check, and the object to - * wait on can be specified. - */ -public abstract class TimedWait -{ - /** - * Default Constructor. Sets "this" to be used for the delegation of - * the wait() call to. - */ - public TimedWait () - { - object_ = this; - } - - /** - * Constructor. Allows subclasses to supply us with an Object that - * is delegated the wait() call. - *@param obj The Object that is delegated the wait() call. - */ - public TimedWait (Object obj) - { - object_ = obj; - } - - /** - * Hook method that needs to be implemented by subclasses. - */ - public abstract boolean condition (); - - /** - * Wait until condition becomes true. Note that the method - * blocks. Also note that this method is final to ensure that no one - * overrides it. - * IMPORTANT: This method assumes it is called with the object_'s - * monitor lock already held. - *@exception InterruptedException Interrupted during wait - */ - public final void timedWait () throws InterruptedException - { - // Acquire the monitor lock. - if (!condition ()) - { - // Only attempt to perform the wait if the condition isn't - // true initially. - for (;;) - { - // Wait until we are notified. - object_.wait (); - - // Recheck the condition. - if (condition ()) - break; // Condition became true. - - // else we were falsely notified so go back into wait - } - } - } - - /** - * Template Method that implements the actual timed wait. Note that - * this method is final to ensure that no one overrides it. - * IMPORTANT: This method assumes it is called with the object_'s - * monitor lock already held. - * If the specified wait time is zero, this checks the condition, - * then returns on success or throws a TimeoutException on failure. - *@param tv Absolute time to wait until before throwing an exception - * if the condition isn't satisfied - *@exception java.lang.InterruptedException Interrupted during wait - *@exception JACE.ASX.TimeoutException Reached timeout specified - */ - public final void timedWait (TimeValue tv) - throws InterruptedException, - TimeoutException - { - if (tv == null) { - this.timedWait(); - return; - } - - // Acquire the monitor lock. - if (!condition ()) - { - long start = System.currentTimeMillis(); - long waitTime = tv.getMilliTime() - start; - - for (;;) { - - // Prevent a conversion from absolute to relative time from - // generating a zero or negative waitTime. - if (waitTime < 1) - throw new TimeoutException (); - - // Wait until we are notified. - object_.wait (waitTime); - - // Recheck the condition. - if (!condition ()) { - - long now = System.currentTimeMillis(); - - // Timed out! - if (now >= tv.getMilliTime ()) - throw new TimeoutException (); - else - // We still have some time left to wait, so adjust the - // wait_time. - waitTime = tv.getMilliTime() - now; - } - else - break; // Condition became true. - } - } - } - - /** - * Notify any one thread waiting on the object_. - * IMPORTANT: This method assumes it is called with the object_'s - * monitor lock already held. - */ - public final void signal () { - object_.notify (); - } - - /** - * Notify all threads waiting on the object_. - * IMPORTANT: This method assumes it is called with the object_'s - * monitor lock already held. - */ - public final void broadcast () { - object_.notifyAll (); - } - - /** - * The object we delegate to. If a subclass gives us a particular - * object, we use that to delegate to, otherwise, we ``delegate'' - * to ourself (i.e., this). - */ - protected Object object_; - -} diff --git a/java/JACE/ASX/TimeoutException.java b/java/JACE/ASX/TimeoutException.java deleted file mode 100644 index d55cc4fe999..00000000000 --- a/java/JACE/ASX/TimeoutException.java +++ /dev/null @@ -1,37 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * TimeoutException.java - * - *@author Prashant Jain and Doug Schmidt - * - *************************************************/ -package JACE.ASX; - -/** - * Thrown when a timer has expired. - */ -public class TimeoutException extends Exception -{ - /** - * Default Constructor. - */ - public TimeoutException () - { - super ("Timed Out"); - } - - /** - * Constructor. - *@param timeout The timeout value which expired. - *@param desc Textual description of the exception - */ - public TimeoutException (TimeValue timeout, String desc) - { - super ("Timed Out in " + timeout + ": " + desc); - } - -} diff --git a/java/JACE/ASX/package.html b/java/JACE/ASX/package.html deleted file mode 100644 index 346782ed083..00000000000 --- a/java/JACE/ASX/package.html +++ /dev/null @@ -1,11 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Message queueing facilities. -<P> -@see <a href="http://www.cs.wustl.edu/~schmidt/ACE-papers.html#ipc"> -Documents on ACE interprocess communication components</a> -@see <a href="http://www.cs.wustl.edu/~schmidt/ACE-papers.html#streams"> -Documents on the ACE streams framework</a> -</BODY> -</HTML> diff --git a/java/JACE/Concurrency/AbstractLock.java b/java/JACE/Concurrency/AbstractLock.java deleted file mode 100644 index c8afaf789ae..00000000000 --- a/java/JACE/Concurrency/AbstractLock.java +++ /dev/null @@ -1,269 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * Lock.java - * - *@author Everett Anderson - * - *************************************************/ -package JACE.Concurrency; - -import JACE.ASX.*; - -/** - * Interface for any Java ACE synchronization mechanism. - * <P> - * Defines the interface for Token, Mutex, RWMutex, Semaphore, - * and the RemoteLock proxies in the Token service, as well as - * the possible constant return values. - * <P> - * Methods which take TimeValue timeouts can throw - * JACE.ASX.TimeoutExceptions. The locks should continue to - * function properly after a thread times out or is interrupted. - * <em>Also note that the timeouts are absolute time-of-day - * values, not relative times.</em> - * <P> - * An AbstractLock.FAILURE can be returned for an undefined type of - * failure. - * <P> - * You can assume that - * AbstractLock.FAILURE < AbstractLock.SUCCESS < AbstractLock.SLEEPHOOK - * <P> - * Any method can throw a LockException, providing a way to return - * unusual error cases in future types of locks (such as the Token - * service). - * <P> - * It is safe to call release () in a finally block, since it will - * return FAILURE if the accessing thread is not the owner. - * - */ -public interface AbstractLock -{ - /** - * Generic failure indication, used as a return value. - */ - public static final int FAILURE = -1; - - /** - * Success indication, used as a return value. - */ - int SUCCESS = 0; - - /** - * Success indication, but notes that the thread had to sleep - * to complete it (and it called the sleep hook). Used as a - * return value. - */ - int SLEEPHOOK = 1; - - - /** - * Acquire ownership of the lock, blocking indefinitely if necessary. - * <P> - *@return AbstractLock.FAILURE or AbstractLock.SUCCESS - *@exception LockException special exception defined by a later - * implementation - *@exception InterruptedException indicates another thread has - * interrupted this one during wait - */ - public int acquire () throws LockException, InterruptedException; - - /** - * Acquire ownership of the lock by the given absolute time time-out. - * A value of null for the timeout parameter results in a blocking - * acquire. - * A value of TimeValue.zero throws a TimeoutException if the - * acquire would block. - * <P> - *@param timeout absolute time by which the lock must be acquired - *@return appropriate Lock return value (AbstractLock.FAILURE, - * AbstractLock.SUCCESS or AbstractLock.SLEEPHOOK) - *@exception LockException special exception defined by a later - * implementation - *@exception JACE.ASX.TimeoutException thrown when the lock is not - * obtained by the desired time - *@exception InterruptedException indicates another thread has - * interrupted this one during wait - *@see AbstractLock#tryAcquire - */ - public int acquire (TimeValue timeout) - throws LockException, TimeoutException, InterruptedException; - - /** - * Acquire a read lock, blocking indefinitely if necessary. This can - * be used to implement Reader-Writer locks in which multiple readers - * may have simultaneous access. - * <P> - *@return AbstractLock.FAILURE or AbstractLock.SUCCESS - *@exception LockException special exception defined by a later - * implementation - *@exception InterruptedException indicates another thread has - * interrupted this one during wait - */ - public int acquireRead () throws LockException, InterruptedException; - - /** - * Acquire a read lock by the given absolute time time-out. This can - * be used to implement Reader-Writer locks in which multiple readers - * may have simultaneous access. - * <P> - *@param timeout absolute time by which the lock must be acquired - *@return appropriate lock return value (AbstractLock.FAILURE, - * AbstractLock.SUCCESS or AbstractLock.SLEEPHOOK) - *@exception LockException special exception defined by a later - * implementation - *@exception JACE.ASX.TimeoutException thrown when the lock is not - * obtained by the desired time - *@exception InterruptedException indicates another thread has - * interrupted this one during wait - *@see AbstractLock#tryAcquireRead - */ - public int acquireRead (TimeValue timeout) - throws LockException, TimeoutException, InterruptedException; - - /** - * Acquire a write lock, blocking indefinitely if necessary. This can - * be used to implement Reader-Writer locks in which a writer has - * exclusive access. - * <P> - *@return AbstractLock.FAILURE or AbstractLock.SUCCESS - *@exception LockException special exception defined by a later - * implementation - *@exception InterruptedException indicates another thread has - * interrupted this one during wait - */ - public int acquireWrite () throws LockException, InterruptedException; - - /** - * Acquire a write lock by the given absolute time time-out. This can - * be used to implement Reader-Writer locks in which a writer has - * exclusive access. - * <P> - *@param timeout absolute time by which the lock must be acquired - *@return appropriate AbstractLock return value (AbstractLock.FAILURE, - * AbstractLock.SUCCESS or AbstractLock.SLEEPHOOK) - *@exception LockException special exception defined by a later - * implementation - *@exception JACE.ASX.TimeoutException thrown when the lock is not - * obtained by the desired time - *@exception InterruptedException indicates another thread has - * interrupted this one during wait - *@see AbstractLock#tryAcquireWrite - */ - public int acquireWrite (TimeValue timeout) - throws LockException, TimeoutException, InterruptedException; - - /** - * Give up the lock to some number of waiting threads (if any), then - * reacquire, blocking indefinitely if necessary. - * <P> - * An optimized method that efficiently reacquires the token if no - * other threads are waiting. This is useful for situations where - * you don't want to degrade the quality of service if there are - * other threads waiting to get the token. - * <P> - *@param requeuePosition position in the waiters queue to insert - * this thread. If this value is -1 and there are other - * threads waiting to obtain the token, this thread is queued - * at the end. If this value is greater than -1, then it - * indicates how many entries to skip over before inserting - * our thread into the queue. (For example, if it is 0, - * this thread is put at the front of the queue.) If this - * value is greater than the number of waiters, this thread is - * simply put at the end of the current waiters queue. - *@return AbstractLock.FAILURE or AbstractLock.SUCCESS - *@exception LockException special exception defined by a later - * implementation - *@exception InterruptedException indicates another thread has - * interrupted this one during wait - */ - public int renew (int requeuePosition) throws LockException, - InterruptedException; - - /** - * Give up the lock to some waiting threads (if any), then reacquire - * by the given absolute time time-out. - * <P> - * An optimized method that efficiently reacquires the token if no - * other threads are waiting. This is useful for situations where - * you don't want to degrade the quality of service if there are - * other threads waiting to get the token. - * <P> - * A value of null for the timeout should indicate a blocking renew. - * <P> - *@param requeuePosition position in the waiters queue to insert - * this thread. If this value is -1 and there are other - * threads waiting to obtain the token, this thread is queued - * at the end. If this value is greater than -1, then it - * indicates how many entries to skip over before inserting - * our thread into the queue. (For example, if it is 0, - * this thread is put at the front of the queue.) If this - * value is greater than the number of waiters, this thread is - * simply put at the end of the current waiters queue. - * - *@param timeout absolute time by which the lock must be reacquired - * - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - *@exception LockException special exception defined by a later - * implementation - *@exception JACE.ASX.TimeoutException thrown when the lock is not - * obtained by the desired time - *@exception InterruptedException indicates another thread has - * interrupted this one during wait - */ - public int renew (int requeuePosition, TimeValue timeout) - throws LockException, TimeoutException, InterruptedException; - - /** - * Try to acquire the lock without blocking. - * <P> - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - *@exception LockException special exception defined by a later - * implementation - */ - public int tryAcquire () throws LockException; - - /** - * Try to acquire a read lock without blocking. - * <P> - *@see #acquireRead - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - *@exception LockException special exception defined by a later - * implementation - */ - public int tryAcquireRead () throws LockException; - - /** - * Try to acquire a write lock without blocking. - *<P> - *@see #acquireWrite - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - *@exception LockException special exception defined by a later - * implementation - */ - public int tryAcquireWrite () throws LockException; - - /** - * Method that is called before a thread goes to sleep in an - * acquire. This should be overridden by a subclass to define - * the appropriate behavior. - */ - public void sleepHook (); - - /** - * Release ownership of this lock. - * <P> - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - *@exception LockException special exception defined by a later - * implementation - */ - public int release () throws LockException; -} diff --git a/java/JACE/Concurrency/Condition.java b/java/JACE/Concurrency/Condition.java deleted file mode 100644 index 1889f6e1edf..00000000000 --- a/java/JACE/Concurrency/Condition.java +++ /dev/null @@ -1,124 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * Condition.java - * - *@author Irfan Pyarali - * - *************************************************/ -package JACE.Concurrency; - -import JACE.ASX.TimeoutException; -import JACE.ASX.TimeValue; - -/** - * Abstraction for <em>traditional</em> - * condition variable - * <P> - * This condition variable allows the use of one - * mutex between multiple conditions. - * This implementation is based on the C++ version of ACE. - */ -public class Condition -{ - /** - * Default constructor - *@param Mutex for synchronization - */ - public Condition (Mutex mutex) - { - mutex_ = mutex; - } - - /** - * Wait for condition to become signaled. - *@exception InterruptedException exception during wait - */ - public void Wait () - throws InterruptedException - { - waiters_++; - - try - { - mutex_.release(); - synchronized (waitObject_) { - waitObject_.wait (); - } - mutex_.acquire (); - } - finally - { - waiters_--; - } - } - - /** - * TimedWait for condition to become signaled. Note that the - * given TimeValue is an absolute time, not a relative time. - * - *@param tv Absolute time to wait until before timing out - *@exception TimeoutException wait timed out exception - *@exception InterruptedException exception during wait - */ - public void Wait (TimeValue tv) - throws TimeoutException, InterruptedException - { - waiters_++; - - try - { - mutex_.release(); - - synchronized (waitObject_) { - long start = System.currentTimeMillis(); - long waitTime = tv.getMilliTime() - start; - if (waitTime < 1) - throw new TimeoutException (); - waitObject_.wait (waitTime); - } - - mutex_.acquire (tv); - } - finally - { - waiters_--; - } - } - - /** - * Signal condition. Wake one waiter (if any). - */ - public void signal () - { - synchronized (waitObject_) { - waitObject_.notify (); - } - } - - /** - * Signal condition. Wake up all waiters (if any). - */ - public void broadcast () - { - synchronized (waitObject_) { - waitObject_.notifyAll (); - } - } - - /** - * Accessor to lock - *@return Mutex - */ - public Mutex mutex () - { - return mutex_; - } - - private int waiters_; - private Object waitObject_ = new Object (); - private Mutex mutex_; -} diff --git a/java/JACE/Concurrency/LockAdapter.java b/java/JACE/Concurrency/LockAdapter.java deleted file mode 100644 index db2e9de05c7..00000000000 --- a/java/JACE/Concurrency/LockAdapter.java +++ /dev/null @@ -1,262 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * Lock.java - * - *@author Everett Anderson - * - *************************************************/ -package JACE.Concurrency; - -import JACE.ASX.*; - -/** - * Abstract adapter class which provides useful default implementations - * for several methods in the AbstractLock interface, as well as - * protected helper functions for making sure only the owner - * can perform certain operations. - * - *@see JACE.Concurrency.AbstractLock - */ -public abstract class LockAdapter implements AbstractLock -{ - /** - * Default implementation that calls acquire (TimeValue) with a null - * timeout. - * - *@see AbstractLock#acquire - */ - public int acquire () throws InterruptedException - { - try { - return acquire (null); - } catch (TimeoutException e) { - // This should never happen - return AbstractLock.FAILURE; - } - } - - /** - * Acquire ownership of the lock by the given absolute time time-out. - * A value of null for the timeout parameter results in a blocking - * acquire. - * A value of TimeValue.zero throws a TimeoutException if the - * acquire would block. - * <P> - *@param timeout absolute time by which the lock must be acquired - *@return appropriate Lock return value (AbstractLock.FAILURE, - * AbstractLock.SUCCESS or AbstractLock.SLEEPHOOK) - *@exception JACE.ASX.TimeoutException thrown when the lock is not - * obtained by the desired time - *@exception InterruptedException indicates another thread has - * interrupted this one during wait - *@see AbstractLock#tryAcquire - */ - public abstract int acquire (TimeValue timeout) - throws TimeoutException, InterruptedException; - - /** - * Default implementation that calls acquireRead (TimeValue) with a - * null timeout. - * - *@see AbstractLock#acquireRead - */ - public int acquireRead () throws InterruptedException - { - try { - return acquireRead (null); - } catch (TimeoutException e) { - // This should never happen - } - - return AbstractLock.FAILURE; - } - - /** - * Default implementation that calls acquire (TimeValue). - * - *@see AbstractLock#acquireRead(TimeValue) - */ - public int acquireRead (TimeValue timeout) - throws TimeoutException, InterruptedException - { - return acquire (timeout); - } - - /** - * Default implementation that calls acquire with a null - * timeout. - * - *@see AbstractLock#acquireWrite - */ - public int acquireWrite () throws InterruptedException - { - try { - return acquire (null); - } catch (TimeoutException e) { - // This should never happen - } - - return AbstractLock.FAILURE; - } - - /** - * Default implementation that calls acquire (TimeValue). - * - *@see AbstractLock#acquireWrite(TimeValue) - */ - public int acquireWrite (TimeValue timeout) - throws TimeoutException, InterruptedException - { - return acquire (timeout); - } - - /** - * Default implementation that calls renew (int, TimeValue) with - * a null timeout. - * - *@see AbstractLock#renew(int) - */ - public int renew (int requeuePosition) throws InterruptedException - { - try - { - return renew (requeuePosition, null); - } catch (TimeoutException e) { - // Note that this should never happen since we requested a - // blocking acquire. - return AbstractLock.FAILURE; - } - } - - /** - * Give up the lock to some waiting threads (if any), then reacquire - * by the given absolute time time-out. - * <P> - * An optimized method that efficiently reacquires the token if no - * other threads are waiting. This is useful for situations where - * you don't want to degrade the quality of service if there are - * other threads waiting to get the token. - * <P> - * A value of null for the timeout should indicate a blocking renew. - * <P> - *@param requeuePosition position in the waiters queue to insert - * this thread. If this value is -1 and there are other - * threads waiting to obtain the token, this thread is queued - * at the end. If this value is greater than -1, then it - * indicates how many entries to skip over before inserting - * our thread into the queue. (For example, if it is 0, - * this thread is put at the front of the queue.) If this - * value is greater than the number of waiters, this thread is - * simply put at the end of the current waiters queue. - * - *@param timeout absolute time by which the lock must be reacquired - * - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - *@exception JACE.ASX.TimeoutException thrown when the lock is not - * obtained by the desired time - *@exception InterruptedException indicates another thread has - * interrupted this one during wait - */ - public abstract int renew (int requeuePosition, - TimeValue timeout) - throws TimeoutException, - InterruptedException; - - /** - * Default implementation that calls tryAcquire (). - * - *@see AbstractLock#tryAcquireRead - */ - public int tryAcquireRead () - { - return tryAcquire (); - } - - /** - * Default implementation that calls tryAcquire (). - * - *@see AbstractLock#tryAcquireWrite - */ - public int tryAcquireWrite () - { - return tryAcquire (); - } - /** - * Try to acquire the lock without blocking. - * <P> - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - */ - public abstract int tryAcquire (); - - /** - * Default implementation as a no-op. - * - *@see AbstractLock#sleepHook - */ - public void sleepHook () - { - } - - /** - * Release ownership of this lock. - * <P> - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - */ - public abstract int release (); - - /** - * Obtains an Object which uniquely identifies the current accessor - * (usually a thread). This is used to make sure only an owner can - * perform certain operations like release. Subclasses can redefine - * the behavior as necessary, such as in the Token service where it is - * defined to be the client ID sent by the proxy. - * <P> - * When using Java 1.2 or later, it might be more efficient to use - * ThreadLocal and an Integer for the ID. The current default - * implementation returns the Thread.currentThread () reference. - * - *@return Object representing a unique ID for this accessor - */ - protected Object accessorID () - { - return Thread.currentThread(); - } - - /** - * Check to see if the current accessor is the (or a) owner of this - * lock. - */ - protected boolean isOwner() - { - return accessorID().equals(this.owner_); - } - - /** - * Set the current accessor to be the (or a) owner of this lock. - */ - protected void setOwner() - { - this.owner_ = accessorID(); - } - - /** - * Make sure that this accessor is no longer the (or a) owner of this - * lock. - */ - protected void clearOwner() - { - this.owner_ = null; - } - - /** - * Reference to the accessorID of the owner. - */ - private Object owner_; -} diff --git a/java/JACE/Concurrency/LockException.java b/java/JACE/Concurrency/LockException.java deleted file mode 100644 index dff4c09c626..00000000000 --- a/java/JACE/Concurrency/LockException.java +++ /dev/null @@ -1,28 +0,0 @@ -package JACE.Concurrency; - -/** - * Base class for possible exceptions thrown from Lock - * mechanisms. This can be used by later Lock - * implementations to signal special types of exceptions, such - * as a remote failure, etc. - * <P> - */ -public class LockException extends java.lang.Exception -{ - /** - * Default constructor - */ - public LockException () { } - - /** - * Constructor with a string message that will be returned - * via the getMessage() method on Exception. - * <P> - *@see java.lang.Exception#getMessage - */ - public LockException (String message) - { - super(message); - } -} - diff --git a/java/JACE/Concurrency/Mutex.java b/java/JACE/Concurrency/Mutex.java deleted file mode 100644 index 856fdbd79eb..00000000000 --- a/java/JACE/Concurrency/Mutex.java +++ /dev/null @@ -1,239 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * Mutex.java - * - *@author Prashant Jain - *@author Everett Anderson - * - *************************************************/ -package JACE.Concurrency; - -import java.util.*; -import JACE.ASX.*; - -/** - * Value added abstraction for mutex variable creation. - * - * A mutex whose operations do not block forever and can time out. - * <P> - * <EM>This class does not support recursive semantics.</EM> - */ -public class Mutex extends LockAdapter -{ - /** - * Acquire ownership of the lock, blocking indefinitely if necessary. - * <P> - *@return AbstractLock.FAILURE or AbstractLock.SUCCESS - *@exception InterruptedException indicates another thread has - * interrupted this one during wait - */ - public synchronized int acquire () throws InterruptedException - { - if (this.monitor_.condition ()) { - this.monitor_.condition (false); - setOwner (); - return AbstractLock.SUCCESS; - } - - this.numberOfWaiters_++; - try { - sleepHook (); - this.monitor_.timedWait (); - } finally { - this.numberOfWaiters_--; - } - this.monitor_.condition (false); - setOwner(); - - return AbstractLock.SLEEPHOOK; - } - - public int renew (int requeuePosition, - TimeValue timeout) - throws InterruptedException, - TimeoutException - { - RenewObject rwo; - - synchronized (this) { - - if (!this.isOwner ()) - return AbstractLock.FAILURE; - - if (numberOfWaiters_ == 0 || requeuePosition == 0) - return AbstractLock.SUCCESS; - - if (requeuePosition < 0 || requeuePosition > numberOfWaiters_) - requeuePosition = numberOfWaiters_; - - rwo = new RenewObject (requeuePosition); - - this.release (); - this.renewers_.addElement (rwo); - } - - // We can't have the method synchronized, or synchronize on (this) - // in here because then the Thread that was woken up won't be able - // to continue its acquire. - // - // Normally when an exception occurs in timedWait, this thread just - // needs to remove itself from the renewers queue. - // - // However, the following situation exists: - // Thread A is the current owner, and is doing processing in release() - // This thread generates a timeout exception in timedWait - // Thread A signals this thread to wake up and take ownership, and - // removes it from the queue. - // This thread never takes ownership -- the exception keeps going up. - // - // This could lead to other renewers waiting in limbo forever. - // - // Solution: If this thread has an exception and it looks like it - // has been proclaimed the owner, then it calls release and lets - // the exception continue. - - boolean exceptionOccured = true; - try { - synchronized (rwo) { - rwo.timedWait (timeout); - - exceptionOccured = false; - } - } finally { - if (exceptionOccured) { - synchronized (this) { - if (!renewers_.removeElement (rwo)) { - setOwner (); - release (); - } - } - } - } - - synchronized (this) { - setOwner (); - } - - // By this point, we should know that we have the lock. The condition - // flag is never set to true in the release() call from the Thread - // that gave us control. - - return AbstractLock.SUCCESS; - } - - public synchronized int tryAcquire () { - if (this.monitor_.condition ()) { - this.monitor_.condition (false); - setOwner(); - return AbstractLock.SUCCESS; - } else - return AbstractLock.FAILURE; - } - - public synchronized int acquire (TimeValue tv) - throws TimeoutException, InterruptedException - { - if (this.monitor_.condition ()) { - this.monitor_.condition (false); - setOwner (); - return AbstractLock.SUCCESS; - } - - this.numberOfWaiters_++; - try { - sleepHook (); - this.monitor_.timedWait (tv); - } finally { - this.numberOfWaiters_--; - } - this.monitor_.condition (false); - setOwner(); - - return AbstractLock.SLEEPHOOK; - } - - /** - * Checks any objects in the renewers queue, giving one of them - * the lock if it is appropriate. Assumes the synchronization - * lock is already held. - * - *@return true if a renewer was signaled, else false - */ - protected boolean signalNextRenewer () - { - // First find the renewer with the minimum yieldTo count, processing - // all of them along the way. - if (this.renewers_.size() > 0) { - - RenewObject renewer = (RenewObject)renewers_. - elementAt (renewers_.size () - 1); - - renewer.decrementYieldTo (); - - for (int i = this.renewers_.size() - 2; i >=0; i--) { - - RenewObject rwo = (RenewObject)renewers_.elementAt (i); - - rwo.decrementYieldTo (); - - renewer = renewer.min (rwo); - } - - // If the renewer with the minimum yieldTo count has yielded to - // enough threads, or if there are no waiting threads, it should - // be signaled (thus, it wakes up and obtains the lock again). - - if (renewer.condition () || numberOfWaiters_ == 0) { - // Note that we leave monitor_.condition in the false state so - // we are assured that only the renewer (and not another - // Thread that does an acquire) will gain control. This - // is important since the renew method can't be synchronized - // in its current implementation. - renewers_.removeElement(renewer); - - synchronized (renewer) { - renewer.signal (); - } - - return true; - } - } - - return false; - } - - public synchronized int release () - { - if (!isOwner()) - return AbstractLock.FAILURE; - - if (!signalNextRenewer ()) { - // Do a normal release if there are no threads waiting to renew - // or no such threads are ready to renew. - this.monitor_.condition (true); - this.monitor_.signal (); - } - - return AbstractLock.SUCCESS; - } - - /** - * Monitor used to signal whether or not this Mutex is available. - */ - protected WaitObject monitor_ = new WaitObject (true, this); - // The monitor (adapter) to wait on - - /** - * Queue of waiting renewers. - */ - protected Vector renewers_ = new Vector (); - - /** - * Number of waiting threads. - */ - protected int numberOfWaiters_ = 0; -} diff --git a/java/JACE/Concurrency/RWMutex.java b/java/JACE/Concurrency/RWMutex.java deleted file mode 100644 index abb30ce3bc8..00000000000 --- a/java/JACE/Concurrency/RWMutex.java +++ /dev/null @@ -1,268 +0,0 @@ -package JACE.Concurrency; - -import java.util.*; -import JACE.ASX.*; - -/** - * A read/write lock allows multiple - * readers or a single writer to access the guarded element. - * <P> - * <EM>This class does not support recursive semantics.</EM> - */ -public class RWMutex extends LockAdapter -{ - public synchronized int tryAcquire () - { - if (referenceCount_ == 0) { - referenceCount_ = -1; - setOwner (); - return AbstractLock.SUCCESS; - } else - return AbstractLock.FAILURE; - } - - public synchronized int tryAcquireRead () - { - if (referenceCount_ > -1 && waiters_.size () == 0) { - referenceCount_++; - setOwner (); - return AbstractLock.SUCCESS; - } else - return AbstractLock.FAILURE; - } - - public int acquire(TimeValue timeout) - throws TimeoutException, InterruptedException - { - return acquireWrite(timeout); - } - - public void waitUntilIsOwner (RWWaitObject waitObj, TimeValue timeout) - throws TimeoutException, InterruptedException - { - boolean exceptionOccured = true; - try { - sleepHook (); - synchronized (waitObj) { - waitObj.timedWait (timeout); - } - exceptionOccured = false; - } finally { - - synchronized (this) { - - if (exceptionOccured) { - if (!waiters_.removeElement (waitObj)) { - setOwner (); - release (); - } - } else - setOwner(); - } - } - } - - public int acquireRead(TimeValue timeout) - throws TimeoutException, InterruptedException - { - RWWaitObject waitObj = null; - - synchronized (this) { - - if (referenceCount_ > -1 && waiters_.size () == 0) { - referenceCount_++; - setOwner (); - return AbstractLock.SUCCESS; - } - - waitObj = new RWWaitObject (true); - - waiters_.addElement (waitObj); - } - - waitUntilIsOwner (waitObj, timeout); - - return AbstractLock.SLEEPHOOK; - } - - public int acquireWrite(TimeValue timeout) - throws TimeoutException, InterruptedException - { - RWWaitObject waitObj = null; - - synchronized (this) { - - if (referenceCount_ == 0) { - referenceCount_ = -1; - setOwner (); - return AbstractLock.SUCCESS; - } - - waitObj = new RWWaitObject (false); - - waiters_.addElement (waitObj); - } - - waitUntilIsOwner (waitObj, timeout); - - // When the writer gets here, it has been cleared to go by - // whatever thread specifically gave control to this writer in - // release. The referenceCount_ and numberOfWaitingWriters_ - // variables are also adjusted by the releasing thread since - // it already has a synchronization lock. Not doing that, - // and then having another synchronized (this) block in here - // could lead to a situation in which another thread sneaks - // in inbetween when this thread leaves timedWait and goes to - // adjust them. - - return AbstractLock.SLEEPHOOK; - } - - - public synchronized int release () - { - if (!isOwner ()) - return AbstractLock.FAILURE; - - clearOwner (); - - // Releasing a reader. - if (referenceCount_ > 0) { - referenceCount_--; - - if (referenceCount_ != 0) - return AbstractLock.SUCCESS; - - } else { - // releasing a writer - referenceCount_ = 0; - } - - if (waiters_.size () == 0) - return AbstractLock.SUCCESS; - - if (releaseFirstReaders () == 0) { - RWWaitObject waitObj = (RWWaitObject)waiters_.firstElement (); - waiters_.removeElementAt (0); - - referenceCount_ = -1; - - waitObj.condition (true); - synchronized (waitObj) { - waitObj.signal (); - } - } - - return AbstractLock.SUCCESS; - } - - // Releases all waiting readers up to the first waiting writer - // or the end of the queue. Returns the number of readers - // released. - protected int releaseFirstReaders () - { - int releasedReaders = 0; - - do { - - RWWaitObject waitObj = (RWWaitObject)waiters_.firstElement (); - if (!waitObj.isReader ()) - break; - - waiters_.removeElementAt (0); - - referenceCount_++; - releasedReaders++; - - waitObj.condition (true); - synchronized (waitObj) { - waitObj.signal (); - } - - } while (waiters_.size () > 0); - - return releasedReaders; - } - - public int renew (int requeuePosition, - JACE.ASX.TimeValue timeout) - throws InterruptedException, - TimeoutException - { - RWWaitObject waitObj = null; - - synchronized (this) { - - if (!isOwner ()) - return AbstractLock.FAILURE; - - if (requeuePosition == 0 || waiters_.size () == 0) - return AbstractLock.SUCCESS; - - waitObj = new RWWaitObject (referenceCount_ > 0); - - if (requeuePosition < 0 || requeuePosition > waiters_.size ()) { - requeuePosition = waiters_.size (); - } - - waiters_.insertElementAt (waitObj, requeuePosition); - - release (); - } - - waitUntilIsOwner (waitObj, timeout); - - // When the writer gets here, it has been cleared to go by - // whatever thread specifically gave control to this writer in - // release. The referenceCount_ and numberOfWaitingWriters_ - // variables are also adjusted by the releasing thread since - // it already has a synchronization lock. Not doing that, - // and then having another synchronized (this) block in here - // could lead to a situation in which another thread sneaks - // in inbetween when this thread leaves timedWait and goes to - // adjust them. - - return AbstractLock.SUCCESS; - } - - static class RWWaitObject extends WaitObject - { - public RWWaitObject (boolean isReader) - { - isReader_ = isReader; - } - - public boolean isReader () - { - return isReader_; - } - - private boolean isReader_ = false; - } - - protected boolean isOwner () - { - return owners_.containsKey (accessorID()); - } - - protected void setOwner () - { - owners_.put (accessorID(), this); - } - - protected void clearOwner () - { - owners_.remove (accessorID()); - } - - private Vector waiters_ = new Vector (); - - private int referenceCount_ = 0; - // Value is -1 if writer has the lock, else this keeps track of the - // number of readers holding the lock. - - private Hashtable owners_ = new Hashtable (); - - private int nestingLevel_ = 0; -} - diff --git a/java/JACE/Concurrency/RenewObject.java b/java/JACE/Concurrency/RenewObject.java deleted file mode 100644 index b690958968a..00000000000 --- a/java/JACE/Concurrency/RenewObject.java +++ /dev/null @@ -1,36 +0,0 @@ -package JACE.Concurrency; - -import JACE.ASX.TimedWait; - -class RenewObject extends TimedWait -{ - public RenewObject (int maxYieldTo) - { - yieldTo_ = maxYieldTo; - } - - public boolean condition () - { - return yieldTo_ <= 0; - } - - public void decrementYieldTo() - { - this.yieldTo_--; - } - - public int yieldTo () - { - return this.yieldTo_; - } - - public RenewObject min (RenewObject other) - { - if (other.yieldTo_ < this.yieldTo_) - return other; - else - return this; - } - - private int yieldTo_; -} diff --git a/java/JACE/Concurrency/Semaphore.java b/java/JACE/Concurrency/Semaphore.java deleted file mode 100644 index 5e558035aee..00000000000 --- a/java/JACE/Concurrency/Semaphore.java +++ /dev/null @@ -1,263 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * Semaphore.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Concurrency; - -import java.util.*; -import JACE.ASX.*; - -/** - * Implementation of Dijkstra's counting semaphore in java. - * <P> - * <EM>This class does not support recursive semantics.</EM> - */ -public class Semaphore extends LockAdapter -{ - static class TimedWaitSAdapter extends JACE.ASX.TimedWait - { - TimedWaitSAdapter (Object obj) - { - super (obj); - } - - // Check to see if there are any semaphores available. - public boolean condition () - { - return this.count_ > 0; - } - - // Increment the count by one - public void increment () - { - this.count_++; - } - - // Decrement the count by one - public void decrement () - { - this.count_--; - } - - // Set the count - public void count (int c) - { - this.count_ = c; - } - - public int count () - { - return this.count_; - } - - private int count_ = 0; - } - - /** - * Create a Semaphore. - *@param count semaphore count - */ - public Semaphore (int c) - { - this.monitor_.count (c); - this.owners_ = new Hashtable (c); - } - - /** - * Create a binary Semaphore. - */ - public Semaphore () - { - this.monitor_.count (1); - this.owners_ = new Hashtable (1); - } - - public synchronized int tryAcquire () - { - if (this.monitor_.condition ()) { - this.monitor_.decrement (); - setOwner (); - return AbstractLock.SUCCESS; - } else - return AbstractLock.FAILURE; - } - - /** - * Acquire the Semaphore. Throws a TimeoutException if the semaphore - * isn't acquired before the given absolute time. - *@param tv time (TimeValue) to wait until before throwing a - * TimeoutException (unless the semaphore is acquired before that) - *@exception TimeoutException wait timed out exception - *@exception InterruptedException exception during wait - */ - public synchronized int acquire (TimeValue tv) - throws TimeoutException, InterruptedException - { - if (this.monitor_.condition ()) { - this.monitor_.decrement (); - setOwner (); - return AbstractLock.SUCCESS; - } - - numberOfWaiters_++; - - try { - sleepHook (); - this.monitor_.timedWait (tv); - } finally { - numberOfWaiters_--; - } - - this.monitor_.decrement (); - setOwner (); - - return AbstractLock.SLEEPHOOK; - } - - public synchronized int release () - { - if (!isOwner ()) - return AbstractLock.FAILURE; - - if (!signalNextRenewer ()) { - this.monitor_.increment (); - this.monitor_.signal (); - clearOwner (); - } - - return AbstractLock.SUCCESS; - } - - /** - * Checks any objects in the renewers queue, giving one of them - * the lock if it is appropriate. Assumes the synchronization - * lock is already held. - * - *@return true if a renewer was signaled, else false - */ - protected boolean signalNextRenewer () - { - // First find the renewer with the minimum yieldTo count, processing - // all of them along the way. - if (this.renewers_.size() > 0) { - - RenewObject renewer = (RenewObject)renewers_. - elementAt (renewers_.size () - 1); - - renewer.decrementYieldTo (); - - for (int i = this.renewers_.size() - 2; i >=0; i--) { - - RenewObject rwo = (RenewObject)renewers_.elementAt (i); - - rwo.decrementYieldTo (); - - renewer = renewer.min (rwo); - } - - // If the renewer with the minimum yieldTo count has yielded to - // enough threads, or if there are no waiting threads, it should - // be signaled (thus, it wakes up and obtains the lock again). - - if (renewer.condition () || numberOfWaiters_ == 0) { - // Note that we leave monitor_.inUse in the true state so - // we are assured that only the renewer (and not another - // Thread that does an acquire) will gain control. This - // is important since the renew method can't be synchronized - // in its current implementation. - renewers_.removeElement(renewer); - - synchronized (renewer) { - renewer.signal (); - } - - return true; - } - } - - return false; - } - - public int renew (int requeuePosition, - JACE.ASX.TimeValue timeout) - throws InterruptedException, - TimeoutException - { - RenewObject rwo; - - synchronized (this) { - - if (!this.isOwner ()) - return AbstractLock.FAILURE; - - if (numberOfWaiters_ == 0 || - requeuePosition == 0 || - this.monitor_.condition ()) - return AbstractLock.SUCCESS; - - if (requeuePosition < 0 || requeuePosition > numberOfWaiters_) - requeuePosition = numberOfWaiters_; - - rwo = new RenewObject (requeuePosition); - - this.release (); - this.renewers_.addElement (rwo); - } - - boolean exceptionOccured = true; - try { - synchronized (rwo) { - rwo.timedWait (timeout); - - exceptionOccured = false; - } - } finally { - synchronized (this) { - - if (exceptionOccured) { - if (!renewers_.removeElement (rwo)) { - setOwner (); - release (); - } - } else { - setOwner(); - } - } - } - - // By this point, we should know that we have the lock. The inUse - // flag is never set to false in the release() call from the Thread - // that gave us control. That thread also set the owner value. - - return AbstractLock.SUCCESS; - } - - protected boolean isOwner () - { - return owners_.containsKey (accessorID()); - } - - protected void setOwner () - { - owners_.put (accessorID(), this); - } - - protected void clearOwner () - { - owners_.remove (accessorID()); - } - - private TimedWaitSAdapter monitor_ = new TimedWaitSAdapter (this); - // The monitor (adapter) to wait on - - private Hashtable owners_; - private Vector renewers_ = new Vector (); - private int numberOfWaiters_ = 0; -} diff --git a/java/JACE/Concurrency/ThreadManager.java b/java/JACE/Concurrency/ThreadManager.java deleted file mode 100644 index d23e2410676..00000000000 --- a/java/JACE/Concurrency/ThreadManager.java +++ /dev/null @@ -1,113 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * ThreadManager.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Concurrency; - -import java.util.*; -import JACE.OS.*; - -/** - * Wrapper for a ThreadGroup which provides additional methods for - * creating a certain number of Runnable instances. - */ -public class ThreadManager -{ - /** - * Default constructor - */ - public ThreadManager () - { - this (ACE.DEFAULT_THREAD_GROUP_NAME); - } - - /** - * Create a Thread Manager. - *@param groupName name of the thread group that the Thread Manager - * will manage - */ - public ThreadManager (String groupName) - { - this.thrGrp_ = new ThreadGroup (groupName); - if (this.thrGrp_ == null) - ACE.ERROR ("Thread group create failed"); - } - - /** - * Create a new thread. - *@param thr the caller whose run method will be invoked when the - * thread has been spawned - *@param daemon flag indicating whether the thread should be - * spawned off as a daemon thread - */ - public void spawn (Runnable thr, - boolean daemon) - { - Thread t = new Thread (this.thrGrp_, thr); - if (daemon) // Set the thread to be a daemon thread - t.setDaemon (true); - t.start (); - } - - /** - * Create a new thread and also give it a name. - *@param thr the caller whose run method will be invoked when the - * thread has been spawned - *@param threadName the name of the new thread - *@param daemon flag indicating whether the thread should be - * spawned off as a daemon thread - */ - public void spawn (Runnable thr, - String threadName, - boolean daemon) - { - Thread t = new Thread (this.thrGrp_, thr, threadName); - if (daemon) // Set the thread to be a daemon thread - t.setDaemon (true); - t.start (); - } - - - /** - * Create <n> new threads. - *@param n the number of threads to spawn - *@param thr the caller whose run method will be invoked by each of - * the <n> threads - *@param daemon flag indicating whether the threads should be - * spawned off as daemon threads - */ - public void spawnN (int n, - Runnable thr, - boolean daemon) - { - // Spawn off all the threads. - for (int i = 0; i < n; i++) - { - this.spawn (thr, daemon); - } - } - - /** - * Get the thread group containing all the threads. Note that the - * thread group can be used to get information regarding number of - * active threads as well as to suspend/resume all the threads in - * the group. - *@return the thread group that contains all the threads managed by - * the Thread Manager - */ - public ThreadGroup thrGrp () - { - return this.thrGrp_; - } - - private ThreadGroup thrGrp_; - // Thread Group that contains all the spawned threads - -} diff --git a/java/JACE/Concurrency/Token.java b/java/JACE/Concurrency/Token.java deleted file mode 100644 index c9080b47fbe..00000000000 --- a/java/JACE/Concurrency/Token.java +++ /dev/null @@ -1,301 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * Token.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Concurrency; - -import java.util.*; -import JACE.ASX.*; - -import JACE.OS.*; - -/** - * Class that acquires, renews, and releases a synchronization - * token that is serviced in strict FIFO ordering. - * <P> - * This is a general-purpose synchronization mechanism that offers - * several benefits. For example, it implements "recursive mutex" - * semantics, where a thread that owns the token can reacquire it - * without deadlocking. In addition, threads that are blocked - * awaiting the token are serviced in strict FIFO order as other - * threads release the token. The solution makes use of the - * Specific Notification pattern presented by Tom Cargill in - * "Specific Notification for Java Thread Synchronization," PLoP96. - * - * <P> - * This class DOES support recursive semantics. - */ -public class Token extends LockAdapter -{ - /** - * Acquire ownership of the lock, blocking indefinitely if necessary. - * <P> - *@return AbstractLock.FAILURE or AbstractLock.SUCCESS - *@exception InterruptedException indicates another thread has - * interrupted this one during wait - */ - public int acquire () throws InterruptedException - { - try - { - return this.acquire (null); - } - catch (TimeoutException e) - { - // This really shouldn't happen since we are supposed to - // block. - return AbstractLock.FAILURE; - } - } - - /** - * Acquire the token by the given absolute time time-out. The - * method uses synchronized blocks internally to avoid race conditions. - *@param timeout time to wait until before throwing a - * TimeoutException (unless the token is acquired before that). - * Performs a blocking acquire if the given timeout is null. - *@return AbstractLock.SUCCESS if acquires without calling <sleepHook> - * AbstractLock.SLEEPHOOK if <sleepHook> is called. - * AbstractLock.FAILURE if failure occurs - *@exception TimeoutException if time-out occurs - *@exception InterruptedException exception during wait - */ - public int acquire (TimeValue timeout) throws TimeoutException, - InterruptedException - { - int result = AbstractLock.SUCCESS; - WaitObject snl = new WaitObject (); - boolean mustWait; - synchronized (snl) - { - synchronized (this) - { - mustWait = !this.snq_.isEmpty (); - - if (mustWait && isOwner ()) - { - // I am the one who has the token. So just increment - // the nesting level - this.nestingLevel_++; - return AbstractLock.SUCCESS; - } - // Add local lock to the queue - this.snq_.addElement (snl); - } - if (mustWait) - { - result = AbstractLock.SLEEPHOOK; - sleepHook(); - - boolean exceptionOccured = true; - try { - snl.timedWait(timeout); - exceptionOccured = false; - } finally { - if (exceptionOccured) { - synchronized (this) { - if (!snq_.removeElement (snl)) { - setOwner (); - release (); - } - } - } - } - } - - // Set the owner of the token - synchronized (this) { - setOwner(); - } - } - - return result; - } - - /** - * Try to acquire the token. Implements a non-blocking acquire. - * - *@return AbstractLock.SUCCESS if acquires - * AbstractLock.FAILURE if failure occurs - */ - public synchronized int tryAcquire () - { - int result = AbstractLock.SUCCESS; - - if (this.snq_.isEmpty ()) - { - // No one has the token, so acquire it - this.snq_.addElement (new WaitObject ()); - - setOwner(); - } - else if (isOwner()) - { - this.nestingLevel_++; - } - // Someone else has the token. - else - { - // Would have to block to acquire the token, so return - // failure. - result = AbstractLock.FAILURE; - } - return result; - } - - /** - * An optimized method that efficiently reacquires the token if no - * other threads are waiting. This is useful for situations where - * you don't want to degrade the quality of service if there are - * other threads waiting to get the token. If the given TimeValue - * is null, it's the same as calling renew(int requeuePosition). - *@param requeuePosition Position in the queue where to insert the - * lock. If requeuePosition == -1 and there are other threads - * waiting to obtain the token we are queued at the end of the list - * of waiters. If requeuePosition > -1 then it indicates how many - * entries to skip over before inserting our thread into the list of - * waiters (e.g.,requeuePosition == 0 means "insert at front of the - * queue"). - *@param timeout Throw a TimeoutException if the token isn't renewed - * before this absolute time timeout. - *@return AbstractLock.SUCCESS if renewed the lock - * AbstractLock.FAILURE if failure occurs - *@exception TimeoutException exception if timeout occurs - *@exception InterruptedException exception during wait - */ - public int renew (int requeuePosition, TimeValue timeout) - throws TimeoutException, InterruptedException - { - WaitObject snl = null; - int saveNestingLevel = 0; - - synchronized (this) - { - if (!isOwner ()) - return AbstractLock.FAILURE; - - // Check if there is a thread waiting to acquire the token. If - // not or if requeuePosition == 0, then we don't do anything - // and we simply keep the token. - if (this.snq_.size () > 1 && requeuePosition != 0) - { - // Save the nesting level - saveNestingLevel = this.nestingLevel_; - this.nestingLevel_ = 0; - - // Reinsert ourselves at requeuePosition in the queue - snl = (WaitObject) this.snq_.firstElement (); - this.snq_.removeElementAt (0); - - if (requeuePosition < 0) - this.snq_.addElement (snl); // Insert at end - else - this.snq_.insertElementAt (snl, Math.min(requeuePosition, - this.snq_.size())); - - synchronized (this.snq_.firstElement ()) - { - // Notify the first waiting thread in the queue - WaitObject obj = (WaitObject) this.snq_.firstElement (); - // Set its condition to be true so that it falls out - // of the for loop - obj.condition (true); - // Now signal the thread - obj.signal (); - } - } - } - - // Check if we reinserted the lock in the queue and therefore need - // to do a wait - if (snl != null) - { - synchronized (snl) - { - // Set the condition to be false so that we can begin the - // wait - snl.condition (false); - // Wait until the given absolute time (or until notified - // if the timeout is null) - - boolean exceptionOccured = true; - try { - - snl.timedWait (timeout); - - exceptionOccured = false; - - } finally { - if (exceptionOccured) { - synchronized (this) { - if (!snq_.removeElement (snl)) { - setOwner (); - release (); - } - } - } - } - } - - synchronized (this) { - // Restore the nesting level and current owner of the lock - this.nestingLevel_ = saveNestingLevel; - - // Set the owner of the token - setOwner(); - } - } - - return AbstractLock.SUCCESS; - } - - /** - * Release the token. It is safe for non-owners to call - * this. - *@return AbstractLock.SUCCESS on success - * AbstractLock.FAILURE on failure (for instance, a non-owner - * calling release) - */ - public synchronized int release () - { - if (!isOwner()) - return AbstractLock.FAILURE; - - // Check if nestingLevel > 0 and if so, decrement it - if (this.nestingLevel_ > 0) - this.nestingLevel_--; - else - { - clearOwner (); - this.snq_.removeElementAt (0); - if (!this.snq_.isEmpty ()) - { - synchronized (this.snq_.firstElement ()) - { - // Notify the first waiting thread in the queue - WaitObject obj = (WaitObject) this.snq_.firstElement (); - // Set its condition to be true so that it falls out - // of the for loop - obj.condition (true); - // Now signal the thread - obj.signal (); - } - } - } - - return AbstractLock.SUCCESS; - } - - private Vector snq_ = new Vector (); - // Vector of lock objects - - private int nestingLevel_ = 0; - // Current Nesting Level -} diff --git a/java/JACE/Concurrency/WaitObject.java b/java/JACE/Concurrency/WaitObject.java deleted file mode 100644 index b7c8cbc7191..00000000000 --- a/java/JACE/Concurrency/WaitObject.java +++ /dev/null @@ -1,39 +0,0 @@ -package JACE.Concurrency; - -import JACE.ASX.TimedWait; - -class WaitObject extends TimedWait -{ - public WaitObject () - { - super (); - } - - public WaitObject (Object obj) - { - super (obj); - } - - public WaitObject (boolean initialState) - { - condition_ = initialState; - } - - public WaitObject (boolean initialState, Object obj) - { - super (obj); - condition_ = initialState; - } - - public boolean condition () - { - return this.condition_; - } - - public void condition (boolean c) - { - this.condition_ = c; - } - - private boolean condition_ = false; -} diff --git a/java/JACE/Concurrency/package.html b/java/JACE/Concurrency/package.html deleted file mode 100644 index ceadb36f662..00000000000 --- a/java/JACE/Concurrency/package.html +++ /dev/null @@ -1,15 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Collection of concurrency mechanisms and a Thread manager. -<P> -JACE concurrency mechanisms now inherit from a common base class, -AbstractLock. This allows users to write code without regard to -whether a lock is local or remote. - -@see JACE.netsvcs.Token.RemoteLock -@see <a href="http://www.cs.wustl.edu/~schmidt/ACE-papers.html#concurrency">Documents on ACE concurrency components</a> -</BODY> -</HTML> - - diff --git a/java/JACE/Connection/AcceptStrategy.java b/java/JACE/Connection/AcceptStrategy.java deleted file mode 100644 index 3af87865c79..00000000000 --- a/java/JACE/Connection/AcceptStrategy.java +++ /dev/null @@ -1,87 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * AcceptStrategy.java - * - *@author Prashant Jain - *@author Everett Anderson - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; - -/** - * Interface for specifying a passive connection - * acceptance strategy for a - * <a href="ACE.Connection.SvcHandler.html"><tt>SvcHandler</tt></a> - * . - * <P> - * This class provides a strategy that manages passive - * connection setup for an application, and can be extended - * to define new strategies. - * <P> - * - * The default implementation delegates to a generic Acceptor. - * - *@see SvcHandler - *@see Acceptor - */ -public class AcceptStrategy -{ - /** - * Create an instance of AcceptStrategy that delegates to the given - * Acceptor. - *@param port port number where the server will listen for connections - *@param peer Acceptor instance to delegate to - */ - AcceptStrategy (int port, Acceptor peer) throws IOException - { - this.acceptor_ = peer; - this.open (port); - } - - /** - * Create an instance of Accept Strategy that delegates to Acceptor. - *@param port port number where the server will listen for connections - *@exception IOException couldn't open port - */ - AcceptStrategy (int port) throws IOException - { - this.acceptor_ = new Acceptor (); - this.open (port); - } - - /** - * Initialize AcceptStrategy. - *@param port port number where the server will listen for connections - *@exception IOException couldn't open port - */ - public void open (int port) throws IOException - { - this.acceptor_.open (port); - } - - /** - * Accept connections into the SvcHandler. Note that subclasses - * should overwrite this method to provide a different accept - * strategy. - *@param sh Svc Handler in which to accept the connection - *@exception SocketException Socket error - *@exception IOException Socket error - *@return 0 - */ - public int acceptSvcHandler (SvcHandler sh) throws - SocketException, IOException - { - return this.acceptor_.acceptSvcHandler (sh); - } - - // The Acceptor we delegate to (if any) - private Acceptor acceptor_; -} diff --git a/java/JACE/Connection/Acceptor.java b/java/JACE/Connection/Acceptor.java deleted file mode 100644 index 00dbed4c056..00000000000 --- a/java/JACE/Connection/Acceptor.java +++ /dev/null @@ -1,215 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * Acceptor.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.SOCK_SAP.*; -import JACE.ServiceConfigurator.*; - -/** - * Abstract factory for creating a service handler - * (<a href="ACE.Connection.SvcHandler.html"><tt>SvcHandler</tt></a>), - * accepting into the - * <a href="ACE.Connection.SvcHandler.html"><tt>SvcHandler</tt></a>, and activating the - * <a href="ACE.Connection.SvcHandler.html"><tt>SvcHandler</tt></a>. - * <P> - * - * Implements the basic strategy for passively establishing - * connections with applications. The <tt>Acceptor</tt> - * is a factory for <tt>SvcHandler</tt> instances, and, by default - * generates a new <tt>SvcHandler</tt> instance for each connection - * esablished. - * - * <p> - * - * The user of this class <em>must</em> provide a - * reference to a handler factory prior to calling <a - * href="#accept()"><tt>accept</tt></a>, or an exception will be - * thrown. The handler factory is identified by the meta-class for - * the <tt>SvcHandler</tt>, and is typically obtained by calling <a - * href="java.lang.Class#classForName(java.lang.String)"><tt>Class.classForName("SvcHandler")</tt></a>. - * - * <p> - * - * TCP is the transport mechanism used, via - * <a href="ACE.SOCK_SAP.SOCKAcceptor.html#_top_"><tt>SOCKAcceptor</tt></a>, - * <em>et.al.</em> The SvcHandler is instantiated with a concrete type - * that performs the application-specific service. - * - * <P> - * - * This class is not directly related to the - * <tt>AcceptorStrategy</tt> class. - * - * - * @see java.lang.Class - * @see JACE.Connection.SvcHandler - * @see JACE.SOCK_SAP.SOCKAcceptor - */ -public class Acceptor extends ServiceObject -{ - /** - * Create an instance of Acceptor. Default constructor. Note that if - * an instance is created via this method, <tt>setHandlerFactory</tt> - * must be called prior to using <tt>accept</tt>. - * - * @see JACE.Connection.Acceptor#setHandlerFactory - */ - public Acceptor () - { - } - - /** - * Create an instance of Acceptor. - *@param handlerFactory meta-class reference used to create - * an instance of a SvcHandler when a connection is accepted - * (typically obtained by calling <tt>Class.classForName</tt>). - * - *@see java.lang.Class#forName - */ - public Acceptor (Class handlerFactory) - { - this.handlerFactory_ = handlerFactory; - } - - /** - * Set the handler factory. This is provided to aid the default - * no-arg constructor. - *@param handlerFactory meta-class reference used to create - * an instance of a SvcHandler when a connection is accepted - * (typically obtained by calling <tt>Class.forName</tt>). - * - *@see java.lang.Class#forName - */ - public void setHandlerFactory (Class handlerFactory) - { - this.handlerFactory_ = handlerFactory; - } - - /** - * Initialize the Acceptor. - *@param port TCP port number where the Acceptor will listen for connections - *@exception IOException socket level exception - */ - public void open (int port) throws IOException - { - this.port_ = port; - this.sockAcceptor_ = new SOCKAcceptor (port); - } - - /** - * Template method for accepting connections. Delegates operational - * activities to the following bridge methods: - * <ul> - * <li><tt>makeSvcHandler</tt></li> - * <li><tt>acceptSvcHandler</tt></li> - * <li><tt>activateSvcHandler</tt></li> - * </ul> - * - * <p> - * - * The method first obtains a <tt>SvcHandler</tt> via - * <tt>makeSvcHandler</tt>, accepts the connection <q>into</q> the - * handler using <tt>acceptSvcHandler</tt>, and finally turns over - * control to the handler with <tt>activateSvcHandler</tt>. - * - *@exception SocketException socket level error - *@exception InstantiationException <tt>makeSvcHandler</tt> failure - *@exception IllegalAccessException <tt>makeSvcHandler</tt> failure - *@exception IOException socket level error - */ - public void accept () throws SocketException, - InstantiationException, - IllegalAccessException, - IOException - { - - // Create a Svc_Handler using the appropriate Creation_Strategy - SvcHandler sh = this.makeSvcHandler (); - - // Accept a connection into the SvcHandler using the appropriate - // Accept_Strategy - this.acceptSvcHandler (sh); - - // Activate the SvcHandler using the appropriate ActivationStrategy - this.activateSvcHandler (sh); - } - - /** - * Bridge method for creating a <tt>SvcHandler</tt>. The default is to - * create a new <SvcHandler>. However, subclasses can override this - * policy to perform <SvcHandler> creation in any way that they like - * (such as creating subclass instances of <SvcHandler>, using a - * singleton, etc.) - *@return a new instance of the SvcHandler - *@exception InstantiationException could not create new SvcHandler - *@exception IllegalAccessException no SvcHandler factory provided - */ - protected SvcHandler makeSvcHandler () - throws InstantiationException, IllegalAccessException - { - // Create a new handler for the connection - return (SvcHandler) handlerFactory_.newInstance (); - } - - /** - * Bridge method for accepting the new connection into the - * <tt>SvcHandler</tt>. The default behavior delegates the work to - * <tt>SOCKAcceptor.accept</tt>. However, subclasses can override this - * strategy. - *@param sh SvcHandler in which to accept the connection - *@return 0 - *@exception SocketException socket level error - *@exception IOException socket level error - */ - protected int acceptSvcHandler (SvcHandler sh) - throws SocketException, IOException - { - // Create a new stream - SOCKStream sockStream = new SOCKStream (); - - // Block in accept. Returns when a connection shows up - this.sockAcceptor_.accept (sockStream); - - // Set the streams for the new handler - sh.setHandle (sockStream); - return 0; - } - - /** - * Bridge method for activating a <tt>SvcHandler</tt>. The default - * behavior of this method is to activate the <tt>SvcHandler</tt> by - * calling its open() method (which allows the <tt>SvcHandler</tt> to - * define its own concurrency strategy). However, subclasses can - * override this strategy to do more sophisticated concurrency - * activations. - *@param sh SvcHandler to activate - *@return 0 - */ - protected int activateSvcHandler (SvcHandler sh) - { - sh.open (null); - return 0; - } - - protected int port_ = ACE.DEFAULT_SERVER_PORT; - - // Handler class that should be instantiated when a connection is - // made with a client - protected Class handlerFactory_; - - // Our connection acceptance factory - protected SOCKAcceptor sockAcceptor_; -} - diff --git a/java/JACE/Connection/ActivateStrategy.java b/java/JACE/Connection/ActivateStrategy.java deleted file mode 100644 index 91072a6c823..00000000000 --- a/java/JACE/Connection/ActivateStrategy.java +++ /dev/null @@ -1,40 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * ActivateStrategy.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - - -/** - * Bridge supporting activation strategy used by - * <a href="ACE.Connection.StrategyAcceptor.html#_top_"><tt>StrategyAcceptor</tt></a> - * <P> - * Subclass and overload - * <a href="#activateSvcHandler(ACE.Connection.SvcHandler)"><tt>activateSvcHandler</tt></a> - * in order change the activation strategy. Then, submit this subclass to - * <a href="ACE.Connection.StrategyAcceptor.html#_top_"><tt>StrategyAcceptor</tt></a> - * as the activation strategy. - * - *@see StrategyAcceptor - */ -public class ActivateStrategy -{ - /** - * Activate the Svc Handler. Note that subclasses should overwrite - * this method to provide a different Activate strategy. - *@param sh Svc Handler to activate - *@return zero if success, non-zero for failure - */ - public int activateSvcHandler (SvcHandler sh) - { - sh.open (null); - return 0; - } -} diff --git a/java/JACE/Connection/Blob.java b/java/JACE/Connection/Blob.java deleted file mode 100644 index d3102c81aa2..00000000000 --- a/java/JACE/Connection/Blob.java +++ /dev/null @@ -1,114 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * Blob.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import JACE.ASX.*; -import JACE.OS.*; - -/** - * Provides a way of reading from or writing to a remote file - * using MessageBlocks. - */ -public class Blob -{ - /** - * Initialize the Blob. - * - *@param filename File to read or write - *@param hostname Host to contact for the file - *@param port Port on which to connect - */ - public int open (String filename, String hostname , int port) - { - this.filename_ = filename; - this.hostname_ = hostname; - this.port_ = port; - return 0; - } - - /** - * Read a certain amount from the file. - */ - public MessageBlock read (int length, int offset) - { - // Check if we have a valid length and a valid offset - if (length < 0 || offset < 0) - { - ACE.ERROR ("Blob::read(): Negative length or offset"); - return null; - } - - // Create a Blob Reader - BlobReader blobReader = new BlobReader (length, - offset, - this.filename_, - this.hostname_, this.port_); - - // Receive data - MessageBlock mb = blobReader.receiveData (); - if (blobReader.bytesRead () != length) - return null; - else - return mb; - } - - /** - * Write a certain amount to the file. - */ - public int write (MessageBlock mb, int length, int offset) - { - // Check if we have a valid length and a valid offset - if (length < 0 || offset < 0) - ACE.ERROR ("Blob::write(): Negative length or offset"); - - // Create a Blob Writer - BlobWriter blobWriter = new BlobWriter (mb, length, offset, this.filename_); - - try - { - // Connect to the server - this.connector_.open (this.hostname_, this.port_); - this.connector_.connect (blobWriter); - } - catch (UnknownHostException e) - { - ACE.ERROR (e); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - - return blobWriter.bytesWritten (); - } - - public int close () - { - return 0; - } - - String filename_; - String hostname_; - int port_; - Connector connector_ = new Connector (); -} diff --git a/java/JACE/Connection/BlobHandler.java b/java/JACE/Connection/BlobHandler.java deleted file mode 100644 index ec282bdeaa9..00000000000 --- a/java/JACE/Connection/BlobHandler.java +++ /dev/null @@ -1,35 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * BlobHandler.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import JACE.ASX.*; -import JACE.OS.*; - -public abstract class BlobHandler extends SvcHandler -{ - public BlobHandler (int length, int offset, String filename) - { - this.length_ = length; - this.offset_ = offset; - this.filename_ = filename; - } - - public abstract int open (Object obj); - - protected int length_ = 0; - protected int offset_ = 0; - protected String filename_ = null; -} - diff --git a/java/JACE/Connection/BlobReader.java b/java/JACE/Connection/BlobReader.java deleted file mode 100644 index 4de6b65bedc..00000000000 --- a/java/JACE/Connection/BlobReader.java +++ /dev/null @@ -1,108 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * BlobReader.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import JACE.ASX.*; -import JACE.OS.*; - -/** - * Provides a way to read from a remote file using - * MessageBlocks (and HTTP). <P> - * - * Created by Blob during a call to read. - */ -public class BlobReader -{ - public BlobReader (int length, - int offset, - String filename, - String hostname, - int port) - { - this.length_ = length; - this.offset_= offset; - this.filename_ = filename; - this.hostname_ = hostname; - this.port_ = port; - } - - - public MessageBlock receiveData () - { - String hostname = this.hostname_; - String filename = this.filename_; - - // Check if the filename begins with a "/" and if so, remove it - // since we are concatenating a "/" to the hostname. - if (this.filename_.startsWith ("/")) - filename = this.filename_.substring (1); - - hostname = hostname + ":" + this.port_ + "/"; - // System.out.println (hostname + filename); - - // Allocate a buffer to hold the offset worth of data - byte tempBuf [] = new byte [this.offset_]; - // Allocate a buffer to hold the actual data - byte dataBuf [] = new byte [this.length_]; - - try - { - // Create a URL to fetch the file - URL url = new URL (this.protocol_ + hostname + filename); - - // Get the input stream and pipe it to a DataInputStream - DataInputStream iStream = new DataInputStream (url.openStream ()); - - // Read the offset worth of bytes - iStream.readFully (tempBuf, 0, this.offset_); - - // Read length worth of bytes - iStream.readFully (dataBuf, 0, this.length_); - } - catch (MalformedURLException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - // Cache number of bytes read - this.bytesRead_ = this.length_; - return new MessageBlock (new String (dataBuf, 0, this.length_)); - } - - public int close (long flags) - { - return 0; - } - - public int bytesRead () - { - return this.bytesRead_; - } - - private String protocol_ = "http://"; - - int length_ = 0; - int offset_= 0; - String filename_ = null; - String hostname_ = "localhost"; - int port_ = 80; - - int bytesRead_ = 0; -} - - diff --git a/java/JACE/Connection/BlobWriter.java b/java/JACE/Connection/BlobWriter.java deleted file mode 100644 index 18c9b092964..00000000000 --- a/java/JACE/Connection/BlobWriter.java +++ /dev/null @@ -1,224 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * BlobWriter.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import JACE.ASX.*; -import JACE.OS.*; - -/** - * Provides a way to write to a remote file using MessageBlocks - * (and HTTP). <P> - * - * Created by Blob during a write. - */ -public class BlobWriter extends BlobHandler -{ - public BlobWriter (MessageBlock mb, - int length, - int offset, - String filename) - { - super (length, offset, filename); - this.mb_ = mb; - this.returnCode_ = -1; - - } - - /******************************* - * This constructor should be used when using the basic HTTP 1.1 - * authentication scheme - *******************************/ - public BlobWriter (MessageBlock mb, - int length, - int offset, - String filename, - String authentication) - { - super (length, offset, filename); - this.mb_ = mb; - this.returnCode_ = -1; - this.authentication_ = authentication; - } - - - public int open (Object obj) - { - if (this.sendRequest () != 0) - { - ACE.ERROR ("BlobWriter::open():sendRequest failed"); - return -1; - } - else if (this.receiveReply () != 0) - { - ACE.ERROR ("BlobWriter::open():receiveReply failed"); - return -1; - } - return 0; - } - - public int close (long flags) - { - return 0; - } - - public int bytesWritten () - { - return this.bytesWritten_;; - } - - protected int sendRequest () - { - // Check for sanity -- check if we have any data to send. - if (this.offset_+ this.length_ > this.mb_.length ()) - { - ACE.ERROR ("BlobWriter::sendRequest():Invalid offset/length"); - return -1; - } - - if (this.sendHeader () == -1) - { - ACE.ERROR ("BlobWriter::sendHeader failed."); - return -1; - } - else - if (this.sendData () == -1) - { - ACE.ERROR ("BlobWriter::sendData failed."); - return -1; - } - return 0; - } - - // Send the header - protected int sendHeader () - { - String filename = this.filename_; - // Check if the filename begins with a "/" and if it doesn't, add it - if (!this.filename_.startsWith ("/")) - filename = "/" + this.filename_; - - // Create the header, store the actual length in mesglen - String mesg = this.requestPrefix_ + " " + filename + " " + this.requestSuffix_; - - if (this.authentication_ != null) - mesg += "Authorization: Basic " + JACE.Connection.HTTPHelper.EncodeBase64(this.authentication_) + '\n'; - - mesg += "Content-length: " + this.length_ + "\n"; - - try - { - if (this.peer ().send (mesg) < 0) - { - ACE.ERROR ("Error sending request"); - return -1; - } - } - catch (IOException e) - { - ACE.ERROR (e); - return -1; - } - return 0; - } - - // Send the data - protected int sendData () - { - // Get the actual data to send - String data = this.mb_.base ().substring (this.offset_, - this.offset_ + this.length_); - - - try - { - // System.out.println (data); - // Now send the data - if (this.peer ().send (data) != this.length_) - { - ACE.ERROR ("Error sending file"); - return -1; - } - } - catch (IOException e) - { - ACE.ERROR (e); - return -1; - } - this.bytesWritten_ = this.length_; - return 0; - } - - - protected int receiveReply () - { - System.out.println("Waiting for reply"); - - // Receive the reply from the server - StringBuffer reply = new StringBuffer (1024); - - try - { - if (this.peer ().recv (reply) < 0) - { - ACE.ERROR ("Error receiving reply from server"); - return -1; - } - } - catch (IOException e) - { - ACE.ERROR (e); - } - - String s = reply.toString (); - - int index = -1; - // Now parse the reply to see if it was a success or a failure - if ((index = s.indexOf (replyPrefix_)) == -1) - { - ACE.ERROR ("Error receiving reply from server"); - return -1; - } - - int codeIndex = index + replyPrefix_.length () + 1; - - // Assume code is a 3 digit number - String codeString = s.substring (codeIndex, codeIndex + 3); - - returnCode_ = (new Integer (codeString)).intValue (); - // System.out.println (code); - - if (returnCode_ >= 200 && returnCode_ < 300) { // Check if everything went smoothly - System.out.println("We got the goodies!"); - return 0; - } else - return -1; - } - - public int returnCode () - { - return this.returnCode_; - } - - protected String authentication_ = null; - protected String protocol_ = "http://"; - protected int bytesWritten_ = 0; - protected MessageBlock mb_ = null; - protected String requestPrefix_ = "PUT"; - protected String requestSuffix_ = "HTTP/1.0\n"; - protected String replyPrefix_ = "HTTP/1.0"; - protected int returnCode_; -} - - diff --git a/java/JACE/Connection/Connector.java b/java/JACE/Connection/Connector.java deleted file mode 100644 index dbe72b8c359..00000000000 --- a/java/JACE/Connection/Connector.java +++ /dev/null @@ -1,148 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * Connector.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.SOCK_SAP.*; -import JACE.ServiceConfigurator.*; - -/** - * Abstract factory for connecting a - * (<a href="JACE.Connection.SvcHandler.html"><tt>SvcHandler</tt></a>), - * to an application. - * <P> - * Implements the basic strategy for actively establishing connections - * with applications. The <tt>Connector</tt> establishes the connection, - * passing it on to a <tt>SvcHandler</tt> instance, and handing over - * control to that instance. - *<p> - * TCP is the transport mechanism used, via - * <a href="JACE.SOCK_SAP.SOCKConnector.html#_top_"><tt>SOCKConnector</tt></a>. - *<P> - * This class, as currently implemented, does not work like its C++ - * counterpart. - * Future versions are expected to rectify this discrepancy. - * - *@see SOCKConnector - *@see SvcHandler - */ -public class Connector extends ServiceObject -{ - /** - * Create a Connector. Do nothing constructor. Allows user to - * call <a href="#open(java.lang.String)">open</a>() later. - */ - public Connector () - { - } - - /** - * Create a Connector passing in server hostname and port - * number, effectively shorthand for calling - * <a href="#open(java.lang.String)">open</a>(). - *@param hostname server hostname - *@param port server port number - */ - public Connector (String hostname, int port) - { - this.open (hostname, port); - } - - /** - * Initialize the Connector passing in server hostname and port - * number. Note that no connection attempt is made. - *@param hostname server hostname - *@param port server port number - */ - public void open (String hostname, int port) - { - this.hostname_ = hostname; - this.port_ = port; - } - - /** - * Connect to the server. - *@param sh Svc Handler to use to handle the connection - *@exception UnknownHostException Bad host - *@exception SocketException Socket error - *@exception InstantiationException Couldn't create new SOCKConnector - *@exception IllegalAccessException No strategy available - *@exception IOException Socket error - */ - public void connect (SvcHandler sh) throws UnknownHostException, - SocketException, - InstantiationException, - IllegalAccessException, - IOException - { - // Make a connection using the appropriate Connection_Strategy - this.connectSvcHandler (sh); - - // Activate the Svc_Handler using the appropriate Activation_Strategy - this.activateSvcHandler (sh); - } - - /** - * Bridge method for making a new connection. The default behavior - * creates a new SOCKConnector and then calls setHandle() on the - * <SvcHandler> that was passed in. Subclasses can override this - * strategy, if needed. - *@param sh Svc Handler to use to handle the connection - *@return 0 - *@exception SocketException Socket error - *@exception IOException Socket error - */ - protected int connectSvcHandler (SvcHandler sh) throws - SocketException, IOException - { - // Create a new stream - SOCKStream sockStream = new SOCKStream (); - - // Create a SOCK_Connector (note the constructor does the connect for us) - this.sockConnector_ = new SOCKConnector (sockStream, - this.hostname_, - this.port_); - ACE.DEBUG ("Connected to " + - sockStream.socket ().getInetAddress ()); - - // Set the streams for the new handler - sh.setHandle (sockStream); - return 0; - } - - /** - * Bridge method for activating a <SvcHandler>. The default - * behavior of this method is to activate the <SvcHandler> by - * calling its open() method (which allows the SVC_HANDLER to define - * its own concurrency strategy). However, subclasses can override - * this strategy to do more sophisticated concurrency activations. - *@param sh Svc Handler to activate - *@return 0 - */ - protected int activateSvcHandler (SvcHandler sh) - { - sh.open (null); - return 0; - } - - - // Port server is listening on - private int port_; - - // Server hostname - private String hostname_; - - // Our connection factory - private SOCKConnector sockConnector_; -} diff --git a/java/JACE/Connection/CreationStrategy.java b/java/JACE/Connection/CreationStrategy.java deleted file mode 100644 index f4828d5bff5..00000000000 --- a/java/JACE/Connection/CreationStrategy.java +++ /dev/null @@ -1,57 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * CreationStrategy.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -/** - * Defines the interface for specifying a creation strategy for a - * <a href="ACE.Connection.SvcHandler.html#_top_"><tt>SvcHandler</tt></a> to the - * <a href="ACE.Connection.StrategyAcceptor.html#_top_"><tt>StrategyAcceptor</tt></a>. - * <P> - * The default behavior is to make a new SvcHandler. However, - * subclasses can override this strategy to perform SvcHandler - * creation in any way that they like (such as creating subclass - * instances of SvcHandler, using a singleton, dynamically - * linking the handler, etc.). - * - *@see SvcHandler - *@see StrategyAcceptor - *@see AcceptStrategy - *@see ActivateStrategy - */ -public class CreationStrategy -{ - /** - * Create an instance of Creation Strategy. - *@param handlerFactory Svc Handler factory that is used to create - * an instance of a Svc Handler - */ - public CreationStrategy (Class handlerFactory) - { - this.handlerFactory_ = handlerFactory; - } - - /** - * Create a new SvcHandler. Note that subclasses should override - * this method to provide a new creation strategy. - *@return reference to a new instance of the SvcHandler (or subclass) - *@exception InstantiationException Unable to instantiate. - *@exception IllegalAccessException No handler factory available. - */ - public SvcHandler makeSvcHandler () throws InstantiationException, - IllegalAccessException - { - // Create a new Svc_Handler - return (SvcHandler) handlerFactory_.newInstance (); - } - - private Class handlerFactory_; -} diff --git a/java/JACE/Connection/HTTPHelper.java b/java/JACE/Connection/HTTPHelper.java deleted file mode 100644 index 2901d74a14a..00000000000 --- a/java/JACE/Connection/HTTPHelper.java +++ /dev/null @@ -1,182 +0,0 @@ -package JACE.Connection; - -import JACE.OS.*; - -/** - * Collection of methods concerning HTTP. - */ -public class HTTPHelper -{ - /** - * Alphabet used in encoding and decoding basic base64 authentication. - * See the HTTP 1.1 RFC for details. - */ - public static String Alphabet - = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - /** - * Decode a secret encrypted with the basic base64 HTTP 1.1 authentication - * scheme. - * - *@param secret Message to decode - *@return null on error, decoded String on success - */ - public static String DecodeBase64 (String secret) - { - StringBuffer output = new StringBuffer (); - boolean inalphabet [] = new boolean[256]; - char decoder [] = new char [256]; - - for (int i = 0; i < 256; i++) { - inalphabet [i] = false; - decoder [i] = 0; - } - - for (int i = Alphabet.length () - 1; - i >= 0; - i--) - { - inalphabet [(int)Alphabet.charAt (i)] = true; - decoder [(int)Alphabet.charAt (i)] = (char)i; - } - - int inidx = 0; - int c = 0; - int char_count = 0; - int bits = 0; - boolean error = false; - - while (inidx < secret.length ()) - { - c = secret.charAt (inidx++); - - if (c == '=') - break; - - if (c > 255 || !inalphabet[(int)c]) - continue; - - bits += decoder[c]; - char_count++; - if (char_count == 4) { - output.append ((char) (bits >> 16)); - output.append ((char) ((bits >> 8) & 0xff)); - output.append ((char) (bits & 0xff)); - bits = 0; - char_count = 0; - } else - bits <<= 6; - } - - if (c == '\0') { - if (char_count != 0) { - ACE.DEBUG ("base64 encoding incomplete: at least " - + ((4 - char_count) * 6) + " bits truncated"); - error = true; - } - } else { - // c == '=' - switch (char_count) - { - case 1: - ACE.DEBUG ("output so far: " + output.toString ()); - ACE.DEBUG ("base64 encoding incomplete: at least 2 bits missing"); - error = true; - break; - case 2: - output.append ((char) (bits >> 10)); - break; - case 3: - output.append ((char) (bits >> 16)); - output.append ((char) ((bits >> 8) & 0xff)); - break; - } - } - - if (!error) - return output.toString (); - else - return null; - } - - /** - * Encode a message with the basic base64 HTTP 1.1 authentication - * scheme. Adapted from James' JAWS HTTP_Helpers code. - * - *@param secret Message to encode - *@return null on error, an encoded String on success - */ - public static String EncodeBase64 (String secret) - { - StringBuffer output = new StringBuffer (); - - // Index of the input string - int inidx = 0; - - // character value - int c; - - int char_count = 0; - int bits = 0; - boolean error = false; - - while (inidx < secret.length()) - { - c = secret.charAt(inidx++); - - // This will mess up internationalization. I wonder if it is really - // necessary for HTTP? - if (c > 255) - { - ACE.DEBUG ("encountered char > 255 (decimal %d): " + c); - error = true; - break; - } - - bits += c; - char_count++; - - if (char_count == 3) - { - output.append(HTTPHelper.Alphabet.charAt(bits >> 18)); - output.append(HTTPHelper.Alphabet.charAt((bits >> 12) & 0x3f)); - output.append(HTTPHelper.Alphabet.charAt((bits >> 6) & 0x3f)); - output.append(HTTPHelper.Alphabet.charAt(bits & 0x3f)); - - bits = 0; - char_count = 0; - } - else - bits <<= 8; - } - - if (!error) - { - if (char_count != 0) - { - bits <<= 16 - (8 * char_count); - output.append(HTTPHelper.Alphabet.charAt(bits >> 18)); - output.append(HTTPHelper.Alphabet.charAt((bits >> 12) & 0x3f)); - - if (char_count == 1) - { - output.append("=="); - } - else - { - output.append(HTTPHelper.Alphabet.charAt((bits >> 6) & 0x3f)); - output.append('='); - } - } - - return output.toString(); - } - - // Returns null on error - return null; - } - - private HTTPHelper () {} -} - - diff --git a/java/JACE/Connection/StrategyAcceptor.java b/java/JACE/Connection/StrategyAcceptor.java deleted file mode 100644 index 743d384776f..00000000000 --- a/java/JACE/Connection/StrategyAcceptor.java +++ /dev/null @@ -1,174 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * StrategyAcceptor.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.SOCK_SAP.*; - -/** - * Abstract factory for creating, accepting into, and activating - * a service handler. - * <P> - * Uses instances of CreationStrategy, AcceptStrategy, and - * ActivateStrategy. - * - *@see SvcHandler - *@see CreationStrategy - *@see AcceptStrategy - *@see ActivateStrategy - */ -public class StrategyAcceptor extends Acceptor -{ - /** - * Create an instance of StrategyAcceptor. The caller must - * call setHandlerFactory before open! - */ - public StrategyAcceptor () - { - this (null, null, null, null); - } - - /** - * Create an instance of StrategyAcceptor. - *@param handlerFactory Svc Handler factory that is used to create - * an instance of a Svc Handler when a connection is accepted. - */ - public StrategyAcceptor (Class handlerFactory) - { - this (handlerFactory, null, null, null); - } - - /** - * Create an instance of StrategyAcceptor. Use the creation - * strategy and the handlerFactory passed in to creae a new instance - * of the Svc Handler. - *@param handlerFactory Svc Handler factory that is used to create - * an instance of a Svc Handler when a connection is accepted. - *@param creStrategy Creation strategy to use to create a new - * instance of the Svc Handler. - *@param acceptStrategy Accept strategy to use to accept a new - * connection into the Svc Handler. - *@param activateStrategy Activate strategy to use to activate the - * instance of the Svc Handler. - */ - public StrategyAcceptor (Class handlerFactory, - CreationStrategy creStrategy, - AcceptStrategy acceptStrategy, - ActivateStrategy activateStrategy) - { - // Cache everything - this.handlerFactory_ = handlerFactory; - this.creStrategy_ = creStrategy; - this.acceptStrategy_ = acceptStrategy; - this.activateStrategy_ = activateStrategy; - } - - /** - * Initialize the Strategy Acceptor. The method creates the - * appropriate strategies as needed. - *@param port port number where the server will listen for connections - *@exception IOException Socket level error - */ - public void open (int port) throws IOException - { - if (this.creStrategy_ == null) - this.creStrategy_ = new CreationStrategy (this.handlerFactory_); - if (this.acceptStrategy_ == null) - this.acceptStrategy_ = new AcceptStrategy (port); - else - this.acceptStrategy_.open (port); - if (this.activateStrategy_ == null) - this.activateStrategy_ = new ActivateStrategy (); - } - - /** - * Accept a connection using the appropriate strategies. - * - *@exception SocketException Socket level error - *@exception InstantiationException Problem creating a handler - *@exception IllegalAccessException No strategy available - *@exception IOException Socket level error - */ - public void accept () throws SocketException, - InstantiationException, - IllegalAccessException, - IOException - { - // Create a Svc_Handler using the appropriate Creation_Strategy - SvcHandler sh = this.makeSvcHandler (); - - // Accept a connection into the Svc_Handler - this.acceptSvcHandler (sh); - - // Activate the Svc_Handler - this.activateSvcHandler (sh); - } - - /** - * Bridge method for creating a SvcHandler. The strategy for - * creating a SvcHandler is configured into the Acceptor via it's - * creStrategy_. If no strategy is passed in, the default behavior - * of this method is to use the default CreationStrategy. - *@return a new instance of the Svc Handler - *@exception InstantiationException Couldn't create SvcHandler - *@exception IllegalAccessException No strategy available - */ - protected SvcHandler makeSvcHandler () - throws InstantiationException, IllegalAccessException - { - // Create a new handler for the connection - return this.creStrategy_.makeSvcHandler (); - } - - - /** - * Bridge method for accepting the new connection into the - * <SvcHandler>. The strategy for accepting into a SvcHandler is - * configured into the Acceptor via it's acceptStrategy_. If no - * strategy is passed in, the default behavior of this method is to - * use the default AcceptStrategy. - *@param sh Svc Handler in which to accept the connection - *@return result of accepting a connection using the accept strategy - *@exception SocketException Socket level error - *@exception IOException Socket level error - */ - protected int acceptSvcHandler (SvcHandler sh) throws SocketException, IOException - { - // Delegate responsibility to the appropriate strategy - return this.acceptStrategy_.acceptSvcHandler (sh); - } - - /** - * Bridge method for activating a <SvcHandler>. The strategy for - * activating a SvcHandler is configured into the Acceptor via it's - * activateStrategy_. If no strategy is passed in, the default - * behavior of this method is to use the default ActivateStrategy. - *@param sh Svc Handler to activate - *@return result of activating the Svc Handler - */ - protected int activateSvcHandler (SvcHandler sh) - { - // Delegate responsibility to the appropriate strategy - return this.activateStrategy_.activateSvcHandler (sh); - } - - // Creation Strategy - private CreationStrategy creStrategy_; - - // Accept Strategy - private AcceptStrategy acceptStrategy_; - - // Activation Strategy - private ActivateStrategy activateStrategy_; -} diff --git a/java/JACE/Connection/SvcHandler.java b/java/JACE/Connection/SvcHandler.java deleted file mode 100644 index 1df62247baa..00000000000 --- a/java/JACE/Connection/SvcHandler.java +++ /dev/null @@ -1,101 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * SvcHandler.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import JACE.ASX.*; -import JACE.Reactor.*; - -/** - * Defines the interface for a service that exchanges data with its - * connected peer. - * <P> - * This class provides a well-defined interface that the Acceptor and - * Connector pattern factories use as their target. Typically, client - * applications will subclass SvcHandler and do all the interesting work - * in the subclass. One thing that the SvcHandler does contain is a - * peer SOCKStream endpoint that is initialized by Acceptor or Connector - * when a connection is established successfully. This endpoint is used - * to exchange data between a SvcHandler and the peer it is connected - * with. - */ -public abstract class SvcHandler extends Task -{ - - /** - * Do nothing constructor. - */ - public SvcHandler () - { - } - - /** - * Set the stream using the SOCKStream passed in. This sets the - * underlying peer - *@param s SOCK Stream to use for the connection - */ - public void setHandle (SOCKStream s) throws IOException - { - this.stream_ = s; - } - - /** - * Get the underlying peer - *@return the underlying peer - */ - public SOCKStream peer () - { - return this.stream_; - } - - /** - * Abstract method that subclasses must define to allow - * initialization to take place. - */ - public abstract int open (Object obj); - - /** - * Provide a default implementation to simplify ancestors. - *@return 0 - */ - public int close (long flags) - { - return 0; - } - - /** - * Provide a default implementation to simplify ancestors. - *@return -1 - */ - public int put (MessageBlock mb, TimeValue tv) - { - return -1; - } - - /** - * Provide a default implementation to simplify ancestors. - *@param tv Time Value when the event occured - *@param obj An arbitrary object that was passed to the Timer Queue - * (Asynchronous Completion Token) - */ - public int handleTimeout (TimeValue tv, Object obj) - { - return -1; - } - - /** - * Underlying peer socket stream. - */ - protected SOCKStream stream_; -} diff --git a/java/JACE/Connection/package.html b/java/JACE/Connection/package.html deleted file mode 100644 index 429904216d5..00000000000 --- a/java/JACE/Connection/package.html +++ /dev/null @@ -1,7 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Collection of factories for services. -@see <a href="http://www.cs.wustl.edu/~schmidt/ACE-papers.html#initialize">Documents on ACE object and service initialization components</a> -</BODY> -</HTML> diff --git a/java/JACE/Makefile b/java/JACE/Makefile deleted file mode 100644 index fd8d7b7a68a..00000000000 --- a/java/JACE/Makefile +++ /dev/null @@ -1,234 +0,0 @@ -# Makefile -# $Id$ - -.SUFFIXES: .java .class - -VERSION = 1.5 -JACE_WRAPPER = .. -CLASSDIR = $(JACE_WRAPPER)/classes -DOCDIR = $(JACE_WRAPPER)/doc - -JC = javac -JCOPTS = -d $(CLASSDIR) -JD = javadoc -JDOPTS = -classpath $(CLASSDIR) -sourcepath $(JACE_WRAPPER) -windowtitle \ - "Java ACE $(VERSION) Documentation" -bottom \ - "Java ACE Version $(VERSION)<BR> \ - <A HREF="http://www.cs.wustl.edu/~schmidt"> \ - http://www.cs.wustl.edu/~schmidt</A>" \ - -doctitle "Java ACE Version $(VERSION) Documentation" -d $(DOCDIR) \ - -overview overview.html - -COMPILE.java = $(JC) $(JCOPTS) $(filter %.java,$?) - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: asx os concurrency connection timers misc reactor svcconfig socksap netsvcs - -pkg_all = $(pkg_asx_timestuff) $(pkg_asx) $(pkg_os) $(pkg_concurrency) \ - $(pkg_connection) $(pkg_timers) $(pkg_misc) $(pkg_reactor) \ - $(pkg_socksap) $(pkg_svcconfig) $(pkg_netsvcs) - -doc: - $(JD) $(JDOPTS) $(packages) - -docclean: - find ${JACE_WRAPPER}/doc -name '*.html' -print | xargs ${RM} - -clean: - find ${JACE_WRAPPER}/classes/JACE -name '*.class' -print | xargs ${RM} - -realclean: clean docclean - - -pkg_asx_timestuff = \ - TimeValue \ - TimeoutException \ - TimedWait - -asx_timestuff: $(addprefix ASX/,$(addsuffix .java,$(pkg_asx_timestuff))) - $(COMPILE.java) - -pkg_asx = \ - IOCntlCmds \ - IOCntlMsg \ - Task \ - TaskFlags \ - ThruTask \ - Module \ - MessageType \ - MessageBlock \ - MessageQueue \ - StreamHead \ - StreamTail \ - Stream - -asx: os asx_timestuff reactor concurrency \ - $(addprefix ASX/,$(addsuffix .java,$(pkg_asx))) - $(COMPILE.java) - -pkg_os = \ - OS \ - ACE - -os: $(addprefix OS/,$(addsuffix .java,$(pkg_os))) - $(COMPILE.java) - -pkg_concurrency = \ - AbstractLock \ - LockAdapter \ - LockException \ - WaitObject \ - RenewObject \ - Condition \ - Mutex \ - RWMutex \ - Semaphore \ - ThreadManager \ - Token - -concurrency: $(addprefix Concurrency/,$(addsuffix .java,\ - $(pkg_concurrency))) asx_timestuff os - $(COMPILE.java) - -pkg_connection = \ - SvcHandler \ - Acceptor \ - Connector \ - AcceptStrategy \ - ActivateStrategy \ - CreationStrategy \ - StrategyAcceptor \ - Blob \ - BlobHandler \ - BlobReader \ - BlobWriter \ - HTTPHelper - -connection: os socksap svcconfig $(addprefix Connection/,\ - $(addsuffix .java,$(pkg_connection))) - $(COMPILE.java) - -pkg_timers = \ - ProfileTimer - -timers: $(addprefix Timers/,$(addsuffix .java,$(pkg_timers))) - $(COMPILE.java) - -pkg_misc = \ - GetOpt - -misc: $(addprefix Misc/,$(addsuffix .java,$(pkg_misc))) - $(COMPILE.java) - -pkg_reactor = \ - EventHandler \ - TimerQueue - -reactor: asx_timestuff $(addprefix Reactor/,\ - $(addsuffix .java,$(pkg_reactor))) - $(COMPILE.java) - -pkg_socksap = \ - INETAddr \ - SOCKStream \ - SOCKAcceptor \ - SOCKConnector - -socksap: os $(addprefix SOCK_SAP/,\ - $(addsuffix .java,$(pkg_socksap))) - $(COMPILE.java) - -pkg_svcconfig = \ - Service \ - ServiceLoader \ - ServiceObject \ - ServiceConfig \ - ServiceRepository - -svcconfig: os reactor misc $(addprefix ServiceConfigurator/,\ - $(addsuffix .java,$(pkg_svcconfig))) - $(COMPILE.java) - -netsvcs: netsvcs_base netsvcs_logger netsvcs_naming netsvcs_time \ - netsvcs_token - -pkg_netsvcs = $(pkg_netsvcs_base) $(pkg_netsvcs_logger) \ - $(pkg_netsvcs_time) $(pkg_netsvcs_naming) $(pkg_netsvcs_token) - -pkg_netsvcs_base = \ - Server \ - Handler - -netsvcs_base: os asx concurrency connection socksap svcconfig \ - $(addprefix netsvcs/,$(addsuffix .java,$(pkg_netsvcs_base))) - $(COMPILE.java) - -pkg_netsvcs_logger = \ - LogRecord \ - LoggingStrategy \ - StderrStrategy \ - ServerLoggingHandler \ - ServerLoggingAcceptor - -netsvcs_logger: netsvcs_base $(addprefix netsvcs/Logger/,\ - $(addsuffix .java,$(pkg_netsvcs_logger))) - $(COMPILE.java) - -pkg_netsvcs_naming = \ - NameRequest \ - NameReply \ - NameProxy \ - NameHandler \ - NameAcceptor - -netsvcs_naming: netsvcs_base $(addprefix netsvcs/Naming/,\ - $(addsuffix .java,$(pkg_netsvcs_naming))) - $(COMPILE.java) - -pkg_netsvcs_time = \ - TimeInfo \ - TimeRequest \ - TSClerkHandler \ - TSClerkProcessor \ - TSServerHandler \ - TSServerAcceptor - -netsvcs_time: netsvcs_base $(addprefix netsvcs/Time/,\ - $(addsuffix .java,$(pkg_netsvcs_time))) - $(COMPILE.java) - -pkg_netsvcs_token = \ - TokenRequest \ - TokenReply \ - TokenRequestHandler \ - LockHandler \ - LockHandlerAdapter \ - LockOperations \ - LockTypes \ - TokenAcceptor \ - RemoteLock \ - RemoteMutex \ - RemoteRWMutex \ - MutexHandler \ - RWMutexHandler - -netsvcs_token: netsvcs_base $(addprefix netsvcs/Token/,\ - $(addsuffix .java,$(pkg_netsvcs_token))) - $(COMPILE.java) - -packages = \ - JACE.ASX \ - JACE.Connection \ - JACE.Concurrency \ - JACE.Misc \ - JACE.OS \ - JACE.Reactor \ - JACE.SOCK_SAP \ - JACE.ServiceConfigurator \ - JACE.Timers \ - JACE.netsvcs \ - JACE.netsvcs.Logger \ - JACE.netsvcs.Naming \ - JACE.netsvcs.Time \ - JACE.netsvcs.Token diff --git a/java/JACE/Misc/GetOpt.java b/java/JACE/Misc/GetOpt.java deleted file mode 100644 index e373baedb67..00000000000 --- a/java/JACE/Misc/GetOpt.java +++ /dev/null @@ -1,171 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Misc - * - * = FILENAME - * GetOpt.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Misc; - -import java.io.*; -import java.util.Hashtable; -import java.util.StringTokenizer; - -/** - * Iterator for parsing command-line arguments. - * <P> - * This version of `get_opt' appears to the caller like standard - * Unix `get_opt' but it behaves differently for the user, since - * it allows the user to intersperse the options with the other - * arguments. - * - * <p> As `get_opt' works, it permutes the elements of `argv' so that, - * when it is done, all the options precede everything else. Thus - * all application programs are extended to handle flexible argument - * order. - */ -public class GetOpt -{ - /** - * Constructor - *@param args command line arguments - *@param optstring string containing the legitimate option - * characters. A colon in optstring means that the previous character - * is an option that wants an argument which is then taken from the - * rest of the current args-element. Here is an example of what - * optstring might look like: "c:dP:p". - */ - public GetOpt (String[] args, String optstring) - { - this (args, optstring, false); - } - - /** - * Constructor - *@param args command line arguments - *@param optstring string containing the legitimate option - * characters. A colon in optstring means that the previous character - * is an option that wants an argument which is then taken from the - * rest of the current args-element. Here is an example of what - * optstring might look like: "c:dP:p". - *@param returnAllArgs specify true if next() should return any - * arguments, even if not in the optstring. This is useful for - * providing an error message. - */ - public GetOpt (String[] args, String optstring, boolean returnAllArgs) - { - returnAllArgs_ = returnAllArgs; - - // Cache the arguments - this.args_ = args; - this.hasArg_ = false; - - // Build the arg hashtable - this.buildArgTable (optstring); - } - - /** - * Scan elements specified in optstring for next option flag. - *@return The character corresponding to the next flag. - */ - public int next () - { - if (this.args_ == null) - return -1; - - if (this.index_ < this.args_.length) - { - String arg = this.args_[this.index_++]; - - // Make sure flag starts with "-" - if (!arg.startsWith ("-")) - return -1; - - // Check if there is more than one character specified as flag - if (arg.length () > 2) - return -1; - - // So far so good - // Check if the flag is in the arg_table and if it is get the - // associated binding. - Character c = (Character) this.argTable_.get - (new Character (arg.charAt (1))); - - if (c == null) { - if (returnAllArgs_) - return arg.charAt (1); - else - return -1; - } - - if (c.charValue () == '#') - { - this.hasArg_ = false; - return arg.charAt (1); - } - else if (c.charValue () == ':') - { - this.hasArg_ = true; - return arg.charAt (1); - } - else // This should not happen - return -1; - } - return -1; - } - - /** - * Get the argument (if any) associated with the flag. - *@return the argument associated with the flag. - */ - public String optarg () - { - if (this.hasArg_) - return this.args_[this.index_++]; - else - return null; - } - - // Build the argument table - private void buildArgTable (String s) - { - this.argTable_ = new Hashtable (); - StringTokenizer tokens = new StringTokenizer (s, ":"); - while (tokens.hasMoreTokens ()) - { - // Get the next token - String t = tokens.nextToken (); - - // First add all flags except the one with ":" after it - // Note "#" is an arbitrary character we use to distinguish - // the two cases - for (int i = 0; i < t.length () - 1; i++) - this.argTable_.put (new Character (t.charAt (i)), - new Character ('#')); - - // Now Add the flag just before ":" to the arg_table - this.argTable_.put (new Character (t.charAt (t.length () - 1)), - new Character (':')); - } - } - - private String [] args_; - // Copy of the args passed in - - private boolean hasArg_; - // Indicator that the flag has an argument following it - - private int index_; - // Index into the array of arguments - - private Hashtable argTable_; - // Table of flags that take arguments after them - - private boolean returnAllArgs_; - // When true, GetOpt returns arguments even if not present in the - // given optstring. -} diff --git a/java/JACE/Misc/package.html b/java/JACE/Misc/package.html deleted file mode 100644 index 31803472e19..00000000000 --- a/java/JACE/Misc/package.html +++ /dev/null @@ -1,6 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Miscellaneous utility classes. -</BODY> -</HTML> diff --git a/java/JACE/OS/ACE.java b/java/JACE/OS/ACE.java deleted file mode 100644 index 3979fa6c2d2..00000000000 --- a/java/JACE/OS/ACE.java +++ /dev/null @@ -1,156 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.OS - * - * = FILENAME - * JACE.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.OS; - -/** - * Constants, utility "functions", etc. - * <P> - * Defines default constants for ACE. Many of these are used for the - * ACE tests and applications. You may want to change some of these to - * correspond to your environment. Also, routines for error handling, - * debugging and bit manipulation are included. - * <P> - * This class is non-instantiable, and intended only to provide a constrained - * namespace. - */ -public abstract class ACE -{ - /** - * Default port on which a server listens for connections. - */ - public static final int DEFAULT_SERVER_PORT = 10002; - - /** - * Default name to use for a thread group. - */ - public static final String DEFAULT_THREAD_GROUP_NAME = "ace_thread_group"; - - /** - * Disable debugging. Once debugging is disabled, all ACE.DEBUG - * statements would be ignored. - */ - public static final void disableDebugging () - { - ACE.debug_ = false; - } - - /** - * Enable debugging. Once debugging is enabled, all ACE.DEBUG - * statements get printed. - */ - public static final void enableDebugging () - { - ACE.debug_ = true; - } - - /** - * Print the string representation of Java Exception. - *@param e Java exception - */ - public static final void ERROR (Exception e) - { - System.err.println (e); - } - - /** - * Print the string being passed in. - *@param s a Java String - */ - public static final void ERROR (String s) - { - System.err.println (s); - } - - /** - * Print the string being passed in. - *@param s A Java String - *@return Error value passed in - */ - public static final int ERROR_RETURN (String s, int errorVal) - { - System.err.println (s); - return errorVal; - } - - /** - * Print the string being passed in. Note the behavior will vary - * depending upon whether debugging is enabled or disabled. - *@param s a Java String - */ - public static final void DEBUG (String s) - { - if (ACE.debug_) - System.out.println (s); - } - - /** - * Flush out any data that may be buffered. - */ - public static final void FLUSH () - { - System.out.flush (); - } - - /** - * Set the bits of WORD using BITS as the mask. - *@param WORD the bits to be set. - *@param BITS the mask to use. - *@return The value obtained after setting the bits. - */ - public static final long SET_BITS (long WORD, long BITS) - { - return WORD | BITS; - } - - /** - * Clear the bits of WORD using BITS as the mask. - *@param WORD the bits to clear. - *@param BITS the mask to use. - *@return The value obtained after clearing the bits. - */ - public static final long CLR_BITS (long WORD, long BITS) - { - return WORD & ~BITS; - } - - /** - * Check if bits are enabled in WORD. - *@param WORD the bits to check. - *@param BIT the bit to check to see if it is enabled or not. - *@return true if bit is enabled, false otherwise. - */ - public static final boolean BIT_ENABLED (long WORD, long BIT) - { - return (WORD & BIT) != 0; - } - - /** - * Check if bits are disabled in WORD. - *@param WORD the bits to check. - *@param BIT the bit to check to see if it is disabled or not. - *@return true if bit is disabled, false otherwise. - */ - public static final boolean BIT_DISABLED (long WORD, long BIT) - { - return (WORD & BIT) == 0; - } - - // Debug flag (turn debugging on/off) - private static boolean debug_ = false; - - // Default private constructor to avoid instantiation - private ACE () - { - } -} - - diff --git a/java/JACE/OS/OS.java b/java/JACE/OS/OS.java deleted file mode 100644 index 3f15a028cc2..00000000000 --- a/java/JACE/OS/OS.java +++ /dev/null @@ -1,65 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.OS - * - * = FILENAME - * OS.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.OS; - -import java.util.StringTokenizer; - -/** - * Methods to extend the capabilities of the Java runtime system. - * <P> - * This non-instantiable class contains little <q>utility functions</q> - * that should have been in Java to begin with :-) - */ -public class OS -{ - /** - * Create an array of Strings from a single String using <delim> as - * the delimiter. - *@param args the String to break up to make an array of Strings - *@param delim the delimeter to use to break the String up - *@return an array containing the original String broken up - */ - public static String [] createStringArray (String args, String delim) - { - // First determine the number of arguments - int count = 0; - StringTokenizer tokens = new StringTokenizer (args, delim); - while (tokens.hasMoreTokens ()) - { - tokens.nextToken (); - count++; - } - if (count == 0) - return null; - - // Create argument array - String [] argArray = new String [count]; - int index = 0; - tokens = new StringTokenizer (args, " "); - while (tokens.hasMoreTokens ()) - { - argArray [index] = tokens.nextToken (); - index++; - } - - // Assert index == count - if (index != count) - return null; - else - return argArray; - } - - // Default private constructor to avoid instantiation - private OS () - { - } -} diff --git a/java/JACE/OS/package.html b/java/JACE/OS/package.html deleted file mode 100644 index 01245ef0b51..00000000000 --- a/java/JACE/OS/package.html +++ /dev/null @@ -1,6 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Extensions to the Java runtime system. -</BODY> -</HTML> diff --git a/java/JACE/Reactor/EventHandler.java b/java/JACE/Reactor/EventHandler.java deleted file mode 100644 index 220f999fcb5..00000000000 --- a/java/JACE/Reactor/EventHandler.java +++ /dev/null @@ -1,43 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Reactor - * - * = FILENAME - * EventHandler.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Reactor; - -import JACE.ASX.TimeValue; - -/** - * Provides an abstract interface for handling timer events. - * <P> - * Classes implementing this interface handle a timer's - * expiration. - * <P> - * Users of C++ ACE will notice that this defines a substantially - * smaller interface than the C++ counterpart. Signal events are - * absent due to the complete absence of this feature from Java itself. - * Moreover, at this point - * there is still some question regarding whether or not the I/O - * portion will make any sense or fit into the Java model for I/O. - * - *@see JACE.Reactor.TimerQueue - *@see JACE.Reactor - */ -public interface EventHandler -{ - /** - * Called when timer expires. - *@param tv Time Value for which timer was set - *@param obj An arbitrary object that was passed to the Timer Queue - * (Asynchronous Completion Token) - */ - public int handleTimeout (TimeValue tv, Object obj); -} - -// Note that more methods will be added as needed diff --git a/java/JACE/Reactor/TimerQueue.java b/java/JACE/Reactor/TimerQueue.java deleted file mode 100644 index 638cffe3391..00000000000 --- a/java/JACE/Reactor/TimerQueue.java +++ /dev/null @@ -1,437 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Reactor - * - * = FILENAME - * TimerQueue.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Reactor; - -import java.util.*; -import JACE.ASX.*; - -import JACE.OS.*; - -/** - * Timer Queue implementation which calls back to the handleTimeout - * method on EventHandler implementations when their timers expire. - * <P> - * This is a simple implementation that keeps a linked list of - * absolute timers. It allows multiple timers to be scheduled - * and returns a timer id for each timer scheduled. In addition, - * it allows periodic timers to be scheduled. - * <P> - * Note that timeouts given to the TimerQueue are relative time - * ("2 seconds from now", etc). - */ -public class TimerQueue implements Runnable -{ - static class TimerNode - { - public TimerNode (EventHandler handler, - Object arg, - TimeValue timerValue, - TimeValue interval, - TimerNode next, - int timerId) - { - this.handler_ = handler; - this.arg_ = arg; - this.timerValue_ = timerValue; - this.interval_ = interval; - this.next_ = next; - this.timerId_ = timerId; - } - - public EventHandler handler_; - // Handler to invoke <handleTimeout> on when a timeout occurs. - - public Object arg_; - // Argument to pass to <handleTimeout>. - - public TimeValue timerValue_; - // Time until the timer expires. - - public TimeValue interval_; - // If this is a periodic timer this holds the time until the next - // timeout. - - public TimerNode next_; - // Pointer to next timer. - - public int timerId_; - // Id of this timer (used to cancel timers before they expire). - } - - static class WaitObject extends TimedWait - { - public boolean condition () - { - return this.condition_; - } - - public void condition (boolean c) - { - this.condition_ = c; - } - - private boolean condition_ = false; - } - - /** - * Constructor. The caller is responsible for calling handleEvents () - * to run the event loop. - */ - public TimerQueue () - { - this (false); - } - - /** - * Constructor. - *@param createInternalThread flag specifying whether to create an - * internal thread that runs the event loop. If it is true, a thread - * is spawned and it runs the event loop, handling all timeout - * events. If it is false, the caller is then responsible for calling - * handleEvents () to run the event loop. The thread that is created - * is set to be a daemon thread. - */ - public TimerQueue (boolean createInternalThread) - { - this.eventLoopRunning_ = false; - if (createInternalThread) { - Thread queueThread = new Thread (this, "Timer Queue"); - queueThread.setDaemon (true); - queueThread.start (); - } - } - - /** - * The thread run method. Do *NOT* call this method! It gets called - * automatically. - */ - public void run () - { - this.handleEvents (); - } - - /** - * Handle timeout events. This forms the event loop and takes care - * of all scheduling. This method should only be called if the Timer - * Queue was constructed with the value of createInternalThread as - * false. - */ - public void handleEvents () - { - if (!this.eventLoopRunning_) - { - // Set the flag indicating that the event loop is now running - this.eventLoopRunning_ = true; - - for (;;) - { - synchronized (this.obj_) - { - try { - // Extract the earliest time from the queue and do a - // timed wait - - this.obj_.timedWait (this.earliestTime ()); - - // We have been notified. Check to see if we need to - // restart the wait with a different timeout - if (this.reset_) - { - this.reset_ = false; - this.obj_.condition (false); - } - - } catch (TimeoutException e) { - // Timeout occurred. Call handleTimeout on appropriate - // Event Handlers - this.dispatchHandlers (); - - } catch (InterruptedException e) { - ACE.ERROR ("TimerQueue was interrupted"); - return; - } - } - } - } - } - - /** - * Check if the queue is empty. - *@return true if queue is empty, else false. - */ - boolean isEmpty () - { - return this.head_ == null; - } - - /** - * Get the node of the earliest node in the TimerQueue. - *@return the time of the earlier node in the TimerQueue. - */ - TimeValue earliestTime () - { - synchronized (this.obj_) - { - if (!this.isEmpty ()) - return this.head_.timerValue_; - else - return null; - } - } - - /** - * Schedule an <EventHandler> that will expire after <delta> amount - * of time. If it expires then <obj> is passed in as the value to - * the <EventHandler>'s <handleTimeout> callback method. This method - * returns a timer id that uniquely identifies the timer and can be - * used to cancel the timer before it expires. - *@param handler Event Handler that is to be scheduled with the timer - *@param obj Object that is passed back to the Event Handler when - * timeout occurs (Asynchronous Completion Token) - *@param delta amount of time for which to schedule the timer - *@return id of the timer scheduled - */ - public int scheduleTimer (EventHandler handler, - Object obj, - TimeValue delta) - { - return this.scheduleTimer (handler, obj, delta, TimeValue.zero); - } - - /** - * Schedule an <EventHandler> that will expire after <delta> amount - * of time. If it expires then <obj> is passed in as the value to - * the <EventHandler>'s <handleTimeout> callback method. If - * <interval> is != to <TimeValue.zero> then it is used to - * reschedule the <EventHandler> automatically. This method - * returns a timer id that uniquely identifies the timer and can be - * used to cancel the timer before it expires. - *@param handler Event Handler that is to be scheduled with the timer - *@param arg Object that is passed back to the Event Handler when - * timeout occurs (Asynchronous Completion Token) - *@param timeout amount of time for which to schedule the timer - *@param interval amount of time to use to reschedule the timer - *@return id of the timer scheduled - */ - public int scheduleTimer (EventHandler handler, - Object arg, - TimeValue timeout, - TimeValue interval) - { - - // Increment the sequence number (it will wrap around). - this.timerId_++; - - ACE.DEBUG("scheduleTimer (" + this.timerId_ + "): " + - timeout + ", " + interval); - - - TimeValue futureTime = TimeValue.plus (timeout, TimeValue.getTimeOfDay ()); - TimerNode node = new TimerNode (handler, - arg, - futureTime, - interval, - null, - this.timerId_); - synchronized (this.obj_) - { - // Check if event loop is running. If it is not, then we can - // just place it at the appropriate place in the queue and - // don't need to do any notification. If event loop is - // running, then check if the node is the first node in the - // queue (either because the queue is empty or because the - // time for the node is earlier than the currently scheduled - // timer node). - if (this.eventLoopRunning_ && - (this.isEmpty () || futureTime.lessThan (this.earliestTime ()))) - { - // Insert the node into (the beginning of) the queue to be - // scheduled. - this.reschedule (node); - - // Notify the waiting thread so that it can reschedule - // using the earliest timeout - this.obj_.notify (); - } - else // Place in the appropriate position in the queue. - { - this.reschedule (node); - } - } - return this.timerId_; - } - - - /** - * Cancel the single timer associated with <timerId>. - *@param timerId id of the timer that needs to be cancelled. - *@return Object that was passed in when timer was scheduled - * (Asynchronous Completion Token). - */ - public Object cancelTimer (int timerId) - { - TimerNode prev = null; - TimerNode curr = null; - - synchronized (this.obj_) - { - // Try to locate the TimerNode that matches the timerId. - for (curr = this.head_; - curr != null && curr.timerId_ != timerId; - curr = curr.next_) - prev = curr; - - if (curr != null) - { - if (prev == null) - this.head_ = curr.next_; - else - prev.next_ = curr.next_; - - return curr.arg_; - } - } - return null; - } - - /** - * Cancel all timers associated with <Event Handler>. - *@param handler Event Handler whose associated timers need to be cancelled. - */ - public void cancelTimer (EventHandler handler) - { - TimerNode prev = null; - TimerNode curr = this.head_; - - synchronized (this.obj_) - { - while (curr != null) - { - if (curr.handler_ == handler) - { - if (prev == null) - { - this.head_ = curr.next_; - curr = this.head_; - } - else - { - prev.next_ = curr.next_; - curr = prev.next_; - } - } - else - { - prev = curr; - curr = curr.next_; - } - } - } - } - - // Call handleTimeout() on all handlers whose timers have expired. - private void dispatchHandlers () - { - TimeValue currentTime = TimeValue.getTimeOfDay (); - - for (;;) - { - if (this.isEmpty () || this.earliestTime ().greaterThan (currentTime)) - break; // There aren't any more timers eligible to expire. - - TimerNode expired = this.head_; - EventHandler handler = expired.handler_; - Object arg = expired.arg_; - int result; - - this.head_ = this.head_.next_; - - // Check whether this is an interval timer. - if (expired.interval_.greaterThan (TimeValue.zero)) - { - // Make sure that we skip past values that have already - // "expired". - do - expired.timerValue_.plusEquals (expired.interval_); - while (expired.timerValue_.lessThanEqual (currentTime)); - - // Since this is an interval timer, we need to reschedule - // it. - this.reschedule (expired); - } - - ACE.DEBUG("Calling handleTimeout for ID " + expired.timerId_); - - // Perform the callback. - result = handler.handleTimeout (currentTime, arg); - - if (result == -1) - this.cancelTimer (handler); - } - } - - // Reschedule a TimerNode by inserting it at the appropriate - // position in the queue. - private void reschedule (TimerNode expired) - { - if (this.isEmpty () || - expired.timerValue_.lessThan (this.earliestTime ())) - { - expired.next_ = this.head_; - this.head_ = expired; - // Set the condition to true so that the waiting thread can be - // notified and it can reschedule. - this.obj_.condition (true); - this.reset_ = true; - } - else - { - TimerNode prev = this.head_; - TimerNode after = this.head_.next_; - - // Locate the proper position in the queue. - - while (after != null - && expired.timerValue_.greaterThan (after.timerValue_)) - { - prev = after; - after = after.next_; - } - - expired.next_ = after; - prev.next_ = expired; - } - } - - public boolean eventLoopRunning () - { - return eventLoopRunning_; - } - - private WaitObject obj_ = new WaitObject (); - // Synchronization object (as well as object to use to do wait on) - - private TimerNode head_; - // Pointer to linked list of TimerHandles. - - private int timerId_; - // Keeps track of the timer id that uniquely identifies each timer. - // This id can be used to cancel a timer via the <cancel (int)> - // method. - - private boolean reset_; - // Flag indicating whether to start the wait again - - private boolean eventLoopRunning_; - // Flag indicating whether the event loop is running or not -} - diff --git a/java/JACE/Reactor/package.html b/java/JACE/Reactor/package.html deleted file mode 100644 index 8cf9b2a941a..00000000000 --- a/java/JACE/Reactor/package.html +++ /dev/null @@ -1,6 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Timer queue implementation and a system for handling timeout events. -</BODY> -</HTML> diff --git a/java/JACE/SOCK_SAP/INETAddr.java b/java/JACE/SOCK_SAP/INETAddr.java deleted file mode 100644 index 11b74a2b0ba..00000000000 --- a/java/JACE/SOCK_SAP/INETAddr.java +++ /dev/null @@ -1,96 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.SOCK_SAP - * - * = FILENAME - * INETAddr.java - * - *@author Chris Cleeland - * - *************************************************/ -package JACE.SOCK_SAP; - -import java.io.*; -import java.net.*; -import JACE.OS.*; - -/** - * Defines an endpoint of a connection, encapsulating host and port. - * This is only a part-way implementation of C++ ACE's ACE_INET_Addr. - * <P> - * Currently the class is very limited in its capabilities; it will - * be expanded in future revisions of ACE. - */ -public class INETAddr // extends Addr -{ - private InetAddress addr_; - private int port_ = 0; - /** - */ - public INETAddr () - { - // Do nothing constructor - } - - /** - * Create an INETAddr from a port/hostname - *@param port port number to connect with server at - *@param hostname hostname of the server - */ - public INETAddr (int port, String hostname) throws UnknownHostException - { - super(); - port_ = port; - addr_ = InetAddress.getByName(hostname); - // Should really use getAllByName(), - // but I don't think we do that in - // C++ ACE, even. - } - - /** - * Create an INETAddr from an address. - * @param address an address in the form "ip-number:port-number", <em>e.g.</em> <pre>tango.cs.wustl.edu:1234</pre> or <pre>128.252.166.57:1234</pre>; if no ':' is present address is assumed to be <b>INADDR_ANY</b> and address contains only the port number - * @throws UnknownHostException - */ - public INETAddr (String address) throws UnknownHostException - { - int colon = address.indexOf(':'); - if (colon != 0) - { - addr_ = InetAddress.getByName(address.substring(0, colon)); - address = address.substring(colon+1); - } - - port_ = Integer.parseInt(address); - } - - /** - * Return the name of the host. - */ - public String getHostName() - { - return addr_.getHostName(); - } - - /** - * Return the dotted Internet address. - */ - public String getHostAddr() - { - return addr_.toString(); - } - - /** - * Return the port number. - */ - public int getPortNumber() - { - return port_; - } - - public String toString() - { - return getHostAddr() + Integer.toString(port_); - } -} diff --git a/java/JACE/SOCK_SAP/SOCKAcceptor.java b/java/JACE/SOCK_SAP/SOCKAcceptor.java deleted file mode 100644 index dc9e12c8496..00000000000 --- a/java/JACE/SOCK_SAP/SOCKAcceptor.java +++ /dev/null @@ -1,113 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.SOCK_SAP - * - * = FILENAME - * SOCKAcceptor.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.SOCK_SAP; - -import java.io.*; -import java.net.*; -import JACE.OS.*; - -/** - * Defines a factory that creates new SOCKStreams passively. - */ -public class SOCKAcceptor -{ - // = Initialization - - /** - * Create a SOCKAcceptor. Do nothing constructor. Allows user to - * call open() later and pass in the port number. - */ - public SOCKAcceptor () - { - } - - /** - * Create a SOCKAcceptor. - *@param port port number where the server will listen for connections - */ - public SOCKAcceptor (int port) throws IOException - { - this.open (port); - } - - /** - * Create socket to listen for connections on. - *@param port port number where the server will listen for connections - */ - public void open(int port) throws IOException - { - // Close old socket (if there is one) - this.close (); - - // Create a new server socket - this.listenSocket_ = new ServerSocket (port); - // ACE.DEBUG ("Server listening on port " + port); - } - - /** - * Close the socket and do any necessary cleanup. - */ - public void close () throws IOException - { - if (this.listenSocket_ != null) - { - this.listenSocket_.close (); - this.listenSocket_ = null; - } - } - - /** - * Accept a connection. The streams are set when the method returns. - *@param sockStream SOCK Stream to use for the connection - */ - public void accept (SOCKStream sockStream) throws SocketException, IOException - { - // Block in accept. Returns when a connection shows up and sets - // the streams - sockStream.socket (this.listenSocket_.accept ()); - ACE.DEBUG ("Accepted connection from " + - sockStream.socket ().getInetAddress ()); - } - - /** - * Get the underlying listen socket. - *@return the underlying listen socket - */ - public ServerSocket listenSocket () - { - return this.listenSocket_; - } - - /** - * Set the underlying listen socket. - *@param s the underlying listen socket - */ - public void listenSocket (ServerSocket s) - { - this.listenSocket_ = s; - } - - /** - * Clean up when the garbage collector gets run (if at all). Note - * that there is no guarantee that finalize () will get called. - *@exception Throwable (Probably IOException from the socket level) - */ - protected void finalize () throws Throwable - { - super.finalize (); - this.close (); - } - - // Socket on which listen for connections (by default initialized to - // null) - private ServerSocket listenSocket_; -} diff --git a/java/JACE/SOCK_SAP/SOCKConnector.java b/java/JACE/SOCK_SAP/SOCKConnector.java deleted file mode 100644 index cc3a558f77f..00000000000 --- a/java/JACE/SOCK_SAP/SOCKConnector.java +++ /dev/null @@ -1,73 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.SOCK_SAP - * - * = FILENAME - * SOCKConnector.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.SOCK_SAP; - -import java.io.*; -import java.net.*; -import JACE.OS.*; - -/** - * Defines an active connection factory for the socket wrappers. - */ -public class SOCKConnector -{ - // = Initialization - - /** - * Create a SOCKConnector. Do nothing constructor. Allows user to - * call connect() later. - */ - public SOCKConnector () - { - // Do nothing constructor - } - - /** - * Create a SOCKConnector and connect to the server. - *@param sockStream SOCK Stream to use for the connection - *@param hostname hostname of the server - *@param port port number to connect with server at - */ - public SOCKConnector (SOCKStream sockStream, - String hostname, - int port) throws SocketException, IOException - { - this.connect (sockStream, - hostname, - port); - } - - /** - * Connect to the server. - *@param sockStream SOCK Stream to use for the connection - *@param hostname hostname of the server - *@param port port number to connect with server at - */ - public void connect (SOCKStream sockStream, - String hostname, - int port) throws SocketException, IOException - { - sockStream.socket (new Socket (hostname, port)); - } - - /** - * Connect to the server. - *@param sockStream SOCK Stream to use for the connection - *@param addr INETAddr instance specifying host/port - */ - public void connect (SOCKStream sockStream, - INETAddr addr) throws SocketException, IOException - { - sockStream.socket (new Socket (addr.getHostName(), - addr.getPortNumber())); - } -} diff --git a/java/JACE/SOCK_SAP/SOCKStream.java b/java/JACE/SOCK_SAP/SOCKStream.java deleted file mode 100644 index 05e2535e62a..00000000000 --- a/java/JACE/SOCK_SAP/SOCKStream.java +++ /dev/null @@ -1,227 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.SOCK_SAP - * - * = FILENAME - * SOCKStream.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.SOCK_SAP; - -import java.io.*; -import java.net.*; -import JACE.OS.*; - -/** - * This adds additional wrapper methods atop the java Socket class. - */ -public class SOCKStream -{ - /** - * Create a default SOCK Stream. Do nothing constructor. - */ - public SOCKStream () - { - } - - /** - * Create a SOCK Stream. - *@param s Socket to initialize SOCK Stream with. - */ - public SOCKStream (Socket s) throws IOException - { - this.socket (s); - } - - /** - * Set the socket and the underlying streams. - *@param s Socket associated with the SOCK Stream. - */ - public void socket (Socket s) throws IOException - { - this.socket_ = s; - // Note that if s is not a valid socket or is null, the - // following calls will throw exceptions - - this.iStream_ = - new DataInputStream(new BufferedInputStream(s.getInputStream())); - - this.oStream_ = - new DataOutputStream(new BufferedOutputStream(s.getOutputStream())); - } - - /* Get the underlying Socket. - *@return the underlying socket - */ - public Socket socket () - { - return this.socket_; - } - - /** - * Close the streams and the underlying socket. - */ - public void close () throws IOException - { - if (this.socket_ != null) - this.socket_.close (); - this.socket_ = null; - } - - // = The following send and recv methods are overloaded to provide a - // flexible interface - - /** - * Send a StringBuffer. Note that the method blocks. - *@param s the StringBuffer to send - *@return the length of the StringBuffer - */ - public int send (StringBuffer s) throws IOException - { - // Get the data out - String buf = s.toString (); - - //this.oStream_.println(buf); - this.oStream_.writeChars(buf.toString()); - this.oStream_.writeChar('\n'); - this.oStream_.flush (); - - return buf.length (); - } - - /** - * Send a String. Note that the method blocks. - *@param s the String to send - *@return the length of the String - */ - public int send (String s) throws IOException - { - this.oStream_.writeChars(s); - this.oStream_.writeChar('\n'); - - //this.oStream_.println(s); - this.oStream_.flush(); - - return s.length (); - } - - /** - * Send an array of bytes. Note that the method blocks. - *@param b array of bytes to send - *@param offset offset into the byte array to start sending from - *@param length number of bytes to send - *@return number of bytes sent - */ - public int sendN (byte[] b, int offset, int length) throws IOException - { - this.oStream_.write (b, offset, length); - this.oStream_.flush (); - return length; - } - - /** - * Receive data and append it to the StringBuffer that was passed - * in. Note that the method blocks. - *@param s the StringBuffer to append the result of the recv to - *@return the length of the String received - */ - public int recv (StringBuffer s) throws IOException - { - int len = 0; - char in = (char)this.iStream_.readByte(); - - while (in != '\n') { - s.append(in); - in = (char)this.iStream_.readByte(); - len++; - } - - return len; - } - - /** - * Receive an array of characters. This method blocks until either - * all the bytes are read, the end of the stream is detected, or - * an exception is thrown. - *@param b byte array to receive the data in - *@param offset the start offset of the data in the byte array. - *@param n number of bytes to receive - *@return n - */ - public int recvN (byte[] b, int offset, int n) throws IOException - { - this.iStream_.readFully (b, offset, n); - return n; - } - - /** - * Set the underlying input stream. - *@param iStream the input stream - */ - public void inputStream (InputStream iStream) - { - this.iStream_ = new DataInputStream(new BufferedInputStream(iStream)); - } - - /** - * Get the underlying input stream. - *@return the underlying input stream - */ - public InputStream inputStream () - { - return this.iStream_; - } - - /** - * Set the underlying output stream. - *@param iStream the output stream - */ - public void outputStream (OutputStream oStream) - { - this.oStream_ = new DataOutputStream(new BufferedOutputStream(oStream)); - } - - /** - * Get the underlying output stream. - *@return the underlying output stream - */ - public OutputStream outputStream () - { - return this.oStream_; - } - - /** - * Get the underlying stream wrapped in a buffered DataOutputStream - */ - public DataOutputStream dataOutputStream () - { - return this.oStream_; - } - - /** - * Get the underlying stream wrapped in a buffered DataInputStream - */ - public DataInputStream dataInputStream () - { - return this.iStream_; - } - - /** - * Cleanup when the SOCK Stream is garbage collected. - *@exception Throwable (Probably IOException from the socket level) - */ - protected void finalize () throws Throwable - { - super.finalize (); - this.close (); - } - - private Socket socket_; - - // = The input and output streams (by default null) - private DataInputStream iStream_; - private DataOutputStream oStream_; -} diff --git a/java/JACE/SOCK_SAP/package.html b/java/JACE/SOCK_SAP/package.html deleted file mode 100644 index fa4b9346aab..00000000000 --- a/java/JACE/SOCK_SAP/package.html +++ /dev/null @@ -1,8 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Wrappers for the sockets system. - -@see JACE.Connection.Acceptor -</BODY> -</HTML> diff --git a/java/JACE/ServiceConfigurator/Service.java b/java/JACE/ServiceConfigurator/Service.java deleted file mode 100644 index fac0b0fc54b..00000000000 --- a/java/JACE/ServiceConfigurator/Service.java +++ /dev/null @@ -1,96 +0,0 @@ -package JACE.ServiceConfigurator; - -/** - * Interface common to all services loaded with the - * Service Configurator. - * <P> - * In order to create a completely new type of service, all that - * is necessary is to implement this interface, and ServiceConfig - * will be able to load it. A concrete example is ServiceObject, - * the base class for the network services. - * <P> - * Implementing classes must also: - * <UL> - * <LI> Provide a default constructor - * <LI> Begin in their own thread (probably in init (String[])) - * </UL> - * <P> - * Implementing classes should also: - * <UL> - * <LI> Shut down completely when close () has been called. That - * means ending thread activity. - * </UL> - * - *@see JACE.ServiceConfigurator.ServiceObject - *@see JACE.ServiceConfigurator.ServiceConfig - *@author Everett Anderson - */ -public interface Service -{ - /** - * Temporarily disable this service. This will only be called for a - * service which returns false from its suspended() method. - * <P> - *@return -1 on failure, 0 on success - */ - int suspend (); - - /** - * Re-enable this service. This will only be called for a service - * which returns true from its suspended() method. - * <P> - *@return -1 on failure, 0 on success - */ - int resume (); - - /** - * Initialize this service. The arguments will be given as if they - * were from the command line, separated into Strings using spaces - * as the delimiters. - * <P> - *@param args set of command line arguments - *@return -1 on failure, 0 on success - */ - int init (String [] args); - - /** - * Close this service and free any internal resources. - * <P> - *@return -1 on failure, 0 on success - */ - int fini (); - - /** - * Provide a status message for this service. - * <P> - *@return status message - */ - String info (); - - /** - * Return the name of this service. The name is typically set - * in ServiceConfig to a name supplied in a configuration file. - * <P> - *@return name of this service - */ - String name (); - - /** - * Set the name of this service. This is typically caled in - * ServiceConfig, setting the name to one supplied in a configuration - * file. - * <P> - *@param name new name for this service - */ - void name (String name); - - /** - * Returns whether or not this service is suspended. The result - * determines whether or not this service's resume() and suspend() - * methods will be called by ServiceConfig. (For instance, while - * a service returns true, its suspend() method will not be called.) - * <P> - *@return true if suspended, else false - */ - boolean suspended (); -} diff --git a/java/JACE/ServiceConfigurator/ServiceConfig.java b/java/JACE/ServiceConfigurator/ServiceConfig.java deleted file mode 100644 index 894cf415f06..00000000000 --- a/java/JACE/ServiceConfigurator/ServiceConfig.java +++ /dev/null @@ -1,482 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ServiceConfig.java - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import java.util.*; -import java.net.*; -import JACE.OS.*; -import JACE.Misc.*; - -/** - * Provide the base class that supplies common server daemon - * operations. Also provides a global point for interacting with - * the service repository. Services can be suspended, resumed, - * removed, and reloaded. - * <P> - * ServiceConfig files contain lines of the following forms: - * - * <PRE> - * load (Service Name) (Class Name) (Type) "argument list" (opt URL path) - * - * resume (Service Name) - * suspend (Service Name) - * remove (Service Name) - * - * where (Type) is currently only ServiceObject or Service_Object - * [Note: This is not enforced by the ServiceConfig program, but - * something must be there.] - * </PRE> - * <P> - * <B>Valid command line arguments:</B> - * <PRE> - * -f (filename) Specify name of the service config file - * -d Enable debugging - * -p (URL path) If not found locally, search this URL path - * for classes (multiple -p options allowed) - * </PRE> - * - *@author Prashant Jain - *@author Everett Anderson - */ -public class ServiceConfig -{ - /** Begins the process of loading a service configurator file: - * parses the command line and calls processDirectives - * - *@param args command line arguments to the Service Configurator - *@exception FileNotFoundException Couldn't find service config file - *@exception IOException Problem reading or parsing the config file - *@exception ClassNotFoundException Couldn't find a certain class - *@exception IllegalAccessException Inappropriate method call on a class - *@exception InstantiationException Couldn't create a certain class instance - *@return -1 on failure, 0 on success - */ - public static int open (String [] args) - throws FileNotFoundException, IOException, ClassNotFoundException, - IllegalAccessException, InstantiationException - { - // Parse the command line - if (ServiceConfig.parseArgs (args) < 0) { - printUsage (); - return -1; - } - - return ServiceConfig.processDirectives (); - } - - protected static void printUsage () - { - ACE.ERROR ("Valid options:\n"); - ACE.ERROR ("-f <filename> Specify name of the service config file"); - ACE.ERROR ("-d Enable debugging"); - ACE.ERROR ("-p <URL path> If not found locally, search this URL path"); - ACE.ERROR (" for classes (multiple -p options allowed)"); - } - - /** Parse the command line. - * <P> - * Currently, valid command line options are the following: - * <PRE> - * -d Debug mode - * -f (filename) Load services in the given file - * -p (URL path) If not found locally, search this URL path for classes - * (there can be multiple -p URL options) - * </PRE> - *@param args command line arguments - *@exception ClassNotFoundException Couldn't find a specified Service - *@exception IllegalAccessException Inappropriate method call on a Service - *@exception InstantiationException Couldn't create a Service instance - */ - protected static int parseArgs (String [] args) - throws ClassNotFoundException, IllegalAccessException, - InstantiationException - { - GetOpt getopt = new GetOpt (args, "df:p:", true); - for (int c; (c = getopt.next ()) != -1; ) - switch (c) - { - case 'p': - // Specify a URL path - try { - ServiceConfig.loader_.addURLPath (getopt.optarg ()); - } catch (MalformedURLException e) { - ACE.ERROR ("Invalid URL: " + getopt.optarg ()); - } - break; - /* - Not supported: - - case 'b': - ServiceConfig.beADaemon_ = true; - break; - case 'n': - break; - */ - case 'd': - ACE.enableDebugging (); - ACE.DEBUG ("Debugging is enabled"); - break; - case 'f': - // Specify the file name of the config file - ServiceConfig.serviceConfigFile_ = getopt.optarg (); - break; - default: - ACE.ERROR ((char ) c + " is not a ServiceConfig option"); - return -1; - } - - return 0; - } - - /** - * Uses the Service Repository to suspend a service with the given name. - * - *@param name name of the Service to suspend - *@return -1 on failure, 0 on success - */ - public static int suspend (String name) - { - return ServiceConfig.svcRep_.suspend (name); - } - - /** - * Uses the Service Repository to resume a service with the given name. - * - *@param name name of the Service to resume - *@return -1 on failure, 0 on success - */ - public static int resume (String name) - { - return ServiceConfig.svcRep_.resume (name); - } - - /** - * Removes the specified Service from the Service Repository. - * - *@param name name of the Service to remove - *@return -1 on failure, 0 on success - */ - public static int remove (String name) - { - return ServiceConfig.svcRep_.remove (name); - } - - /** - * Returns the info String from the specified Service. - * - *@param name name of the Service to query - *@return information about the Service - */ - public static String info (String name) - { - return ServiceConfig.svcRep_.info (name); - } - - /** - * Call fini on the specified Service. - * - *@param name name of the Service to shut down - *@return -1 on failure, 0 on success - */ - public static int fini (String name) - { - return ServiceConfig.svcRep_.fini (name); - } - - /** - * Call init on the specified Service. This is only needed - * when a user wants to add a Service to the repository without - * using service config files. - * - *@param name name of the Service to initialize - *@param args command line arguments to pass to the Service - *@return -1 on failure, 0 on success - *@see ServiceConfig#insert - */ - public static int init (String name, String [] args) - { - return ServiceConfig.svcRep_.init (name, args); - } - - /** - * Adds the given Service to the Service Repository. This is - * only needed when a user wants to add a Service to the repository - * without using service config files. - * - *@param service Service to insert - *@see ServiceConfig#init - */ - public static void insert (Service service) - { - ServiceConfig.svcRep_.insert (service); - } - - /** - * Check to see if the specified Service is suspended. - * - *@param name name of the Service to check - *@return true if it is suspended, else false - */ - public static boolean suspended (String name) - { - return ServiceConfig.svcRep_.suspended (name); - } - - /** - * Check to see if the repository contains a service with the given - * name. - * - *@param name name of the Service to check - *@return true if it is in the repository, else false - */ - public static boolean contains (String name) - { - return (ServiceConfig.svcRep_.find (name) == null ? false : true); - } - - /** - * Get an Enumeration of all of the names of the Services in the - * repository. - * - *@return Enumeration of Service names - */ - public static Enumeration serviceNames () - { - return ServiceConfig.svcRep_.serviceNames (); - } - - /** - * Get an Enumeration of all Services in the repository. - * - *@return Enumeration of Services - */ - public static Enumeration services () - { - return ServiceConfig.svcRep_.services (); - } - - /** - * Load a service of the given name, type, and arguments, then - * initialize it with the given arguments. - * - * Should be aware that this could also throw a class cast exception if - * the author of the service didn't implement the Service interface. - * - *@param serviceName name of the service to load - *@param className class name to load - *@param args command line arguments to initialize the service - *@exception ClassNotFoundException couldn't find the specified class file - *@exception IllegalAccessException problem calling a method on the service - *@exception InstantiationException problem creating an instance - *@exception IOException problem reading the class file - *@return -1 on failure, 0 on success - */ - public static int load (String serviceName, - String className, - String [] args) - throws ClassNotFoundException, IllegalAccessException, - InstantiationException, IOException - { - Class svcClass = ServiceConfig.loader_.loadClass (className); - - Service svc = (Service)(svcClass.newInstance()); - - svc.name (serviceName); - - ServiceConfig.svcRep_.insert (svc); - - return ServiceConfig.svcRep_.init (serviceName, args); - } - - /** - * Same as load (String, String, String[]) but creates the - * String array from the given args parameter using the space - * character as a delimiter. - * - */ - public static int load (String serviceName, - String className, - String args) - throws ClassNotFoundException, IllegalAccessException, - InstantiationException, IOException - { - return ServiceConfig.load (serviceName, - className, - OS.createStringArray (args, " ")); - } - - /** - * Parse a service configurator file, creating classes as necessary. - * - *@return -1 on failure, 0 on success - *@exception FileNotFoundException Couldn't find the file - *(default "svc.conf") - *@exception IOException Problem reading/parsing - *@exception ClassNotFoundException Couldn't find a certain class - *@exception IllegalAccessException Inappropriate method call - *@exception InstantiationException Couldn't create a class instance - */ - protected static int processDirectives () - throws FileNotFoundException, IOException, ClassNotFoundException, - IllegalAccessException, InstantiationException - { - ACE.DEBUG("Processing directives in file " + - ServiceConfig.serviceConfigFile_); - - File configFile = new File (ServiceConfig.serviceConfigFile_); - - // Check if file exists and is a normal file - if (!configFile.exists () || !configFile.isFile ()) - throw new FileNotFoundException ("File " + - ServiceConfig.serviceConfigFile_ + - " not found"); - - // Check if the file is readable - if (!configFile.canRead ()) - throw new IOException ("File " + - ServiceConfig.serviceConfigFile_ + - " not readable"); - - // Set up the stream - FileInputStream fileIn = new FileInputStream (configFile); - - // Parse the file - Reader r = new BufferedReader(new InputStreamReader(fileIn)); - StreamTokenizer in = new StreamTokenizer (r); - - // Set characters in ASCII range 32 to 47, ASCII range 91 to 96, - // and ASCII range 123 to 126 as ordinary characters - in.wordChars ('.', '/'); // ASCII range 32 to 47 - in.wordChars (':', '@'); // ASCII range 58 to 64 - in.wordChars ('[', '`'); // ASCII range 91 to 96 - in.wordChars ('{', '~'); // ASCII range 123 to 126 - in.quoteChar ('\"'); - in.commentChar ('#'); - in.eolIsSignificant(true); - in.lowerCaseMode(false); - - Vector strs = new Vector(); - int lineNumber = 1; - - while (in.nextToken () != StreamTokenizer.TT_EOF) { - - if (in.ttype == StreamTokenizer.TT_EOL) { - - String command = ((String)strs.elementAt(COMMAND_NAME)).toLowerCase(); - String name = (String)strs.elementAt(SERVICE_NAME); - - if (strs.size() == 2) { - if (command.equals("remove")) - ServiceConfig.remove(name); - else - if (command.equals("suspend")) - ServiceConfig.suspend(name); - else - if (command.equals("resume")) - ServiceConfig.resume(name); - } else { - - if (!command.equals("load")) - throw new IOException ("Unknown command: " + - command + - " at line " + - lineNumber); - - if (strs.size() < 5) - throw new IOException ("Line " + lineNumber + - " requires 5 values, not " + - strs.size()); - - // Type is currently unenforced since everything must descend - // from Service anyway. - //String type = (String)strs.elementAt (SERVICE_TYPE); - String className = (String)strs.elementAt (CLASS_NAME); - - if (strs.size () > CODE_BASE) { - try { - String url = (String)strs.elementAt (CODE_BASE); - - ServiceConfig.loader_.addURLPath (url); - - } catch (MalformedURLException e) { - ACE.ERROR("Bad code base on line " + lineNumber); - } - } - - ServiceConfig.load(name, - className, - (String)strs.elementAt(ARGS)); - } - - lineNumber++; - strs.removeAllElements(); - continue; - } - - // Skip over non-strings - if ((in.ttype == StreamTokenizer.TT_WORD) || - (in.ttype == '\"')) - strs.addElement(new String(in.sval)); - else - ACE.DEBUG ("Invalid string on line " + lineNumber + - " element " + strs.size() + - " type " + in.ttype); - } - - return 0; - } - - /** - * Close all services. - */ - public static void close () - { - ServiceConfig.svcRep_.close (); - } - - /** - * Return a reference to the ServiceLoader used to load - * classes. - * - *@return ServiceLoader used internally by ServiceConfig. - */ - public static ServiceLoader loader () - { - return ServiceConfig.loader_; - } - - /** - * Specify the ServiceLoader to be used by ServiceConfig. - * - *@param loader ServiceLoader instance to use (should support remote - * loading) - */ - public static void loader (ServiceLoader loader) - { - ServiceConfig.loader_ = loader; - } - - // Set by command line options - private static boolean beADaemon_ = false; - - private static String serviceConfigFile_ = "svc.conf"; - - private static ServiceRepository svcRep_ = new ServiceRepository (); - private static ServiceLoader loader_ = new ServiceLoader (); - - // Order for the commands on a line in the config file - private final static int COMMAND_NAME = 0; - private final static int SERVICE_NAME = 1; - private final static int CLASS_NAME = 2; - private final static int SERVICE_TYPE = 3; - private final static int ARGS = 4; - private final static int CODE_BASE = 5; -} diff --git a/java/JACE/ServiceConfigurator/ServiceLoader.java b/java/JACE/ServiceConfigurator/ServiceLoader.java deleted file mode 100644 index 75297f9631d..00000000000 --- a/java/JACE/ServiceConfigurator/ServiceLoader.java +++ /dev/null @@ -1,254 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ServiceLoader.java - * - * Implementation of a network-capable class loader - * - *@author Prashant Jain - *@author Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import java.util.*; -import java.net.*; -import JACE.OS.*; -import JACE.Misc.*; - -/** - * ClassLoader that can load classes from across the network - * via provided URL search paths, or from the local machine. - * <P> - * This operates in the same way as the JDK 1.2 ClassLoader by - * first checking for preloaded classes, then trying to use the system - * loader, and finally trying to load it via the network. The user can also - * provide URL search paths, or explicitly call the loadClass method which - * takes a URL. - * - *@see java.lang.ClassLoader - *@see java.lang.Class - */ -public class ServiceLoader extends ClassLoader -{ - /** - * Creates a loader that will only search the local machine for classes - * until URL paths are registered via addURLPath. - */ - public ServiceLoader () - { - this.URLSearchPaths_ = new Vector(); - } - - /** - * Creates a loader that will search the local machine followed by - * this array of URL paths when loading classes. Note that additional - * paths can be added later with the addURLPath method. - *@param remotePaths array of URLs to search when loading classes, after - *attempts to load from the local machine have failed - */ - public ServiceLoader (URL remotePaths[]) - { - this(); - - if (remotePaths == null) - return; - - for (int i = 0; i < remotePaths.length; i++) - this.addURLPath(remotePaths[i]); - } - - /** - * Add the given URL to the list of URL paths to search when loading - * classes. - *@param url URL ending in '/' where classes can be found - */ - public void addURLPath (URL url) - { - if (!URLSearchPaths_.contains(url)) - URLSearchPaths_.addElement(url); - } - - /** - * Add the given URL to the list of URL paths to search when loading - * classes. - *@param String representation of a URL ending in '/' - *@exception MalformedURLException the given String wasn't a valid URL - */ - public void addURLPath (String url) throws MalformedURLException - { - URL resource = new URL (url); - this.addURLPath (resource); - } - - /** - * Tries to load the given class by following the example of JDK 1.2 - * ClassLoader. First check loaded classes, then try to use the system - * loader, and only then perform the user defined subclass behavior - * from findClass (in this case, it's searching over the network). - *@param name name of the class to load - *@param resolve whether or not to resolve the class - *@exception ClassNotFoundException if the class could not be found - *@return loaded Class instance - */ - protected Class loadClass(String name, - boolean resolve) - throws ClassNotFoundException - { - - Class c = null; - - // Has this class already been loaded once? - c = findLoadedClass(name); - if (c != null) - return c; - - try { - - // Can the system loader find it? - c = findSystemClass(name); - return c; - - } catch (ClassNotFoundException e2) { - // The system loader couldn't find it - } - - // If none of the above, try searching our way - return findClass(name); - } - - /** - * This should duplicate the behavior of this class in JDK 1.2. It is - * called by the protected loadClass method after trying to load the - * class in other ways. It simply calls loadClassData and then defines - * the class. - *@param name name of the class to load - *@exception ClassNotFoundException couldn't find the class - *@return loaded Class - */ - protected Class findClass(String name) throws ClassNotFoundException - { - byte[] b = loadClassData(name); - return defineClass(name, b, 0, b.length); - } - - /** - * Try loading a class with the given name, searching the remote - * URL paths that have been registered. Note that this will only - * be called after first checking to see if the class has already - * been loaded, then checking to see whether or not the system - * loader can find it. - * <P> - * This could be overriden by subclasses to define different - * loading behavior. - * - *@param className name of the class (not file name) of the class to load - *@exception ClassNotFoundException couldn't find the class - *@return bytes of a .class file - */ - private byte[] loadClassData(String className) throws ClassNotFoundException - { - byte data[] = null; - - // Try to load it by reading in the bytes from the net - Enumeration e = URLSearchPaths_.elements(); - - while (e.hasMoreElements()) - { - try - { - URL path = (URL)e.nextElement(); - URL classFileURL; - - try - { - classFileURL = new URL(path.toExternalForm() + - className + - ".class"); - } catch (MalformedURLException ex) { - ACE.ERROR("Bad URL: " + ex.getMessage()); - continue; - } - - ACE.DEBUG("Looking for " + classFileURL.toExternalForm()); - URLConnection urlConnection = classFileURL.openConnection (); - - // Get the input stream associated with the URL connection and - // pipe it to a newly created DataInputStream - DataInputStream i = new DataInputStream - (urlConnection.getInputStream ()); - - // Allocate a buffer big enough to hold the contents of the - // data we are about to read - data = new byte [urlConnection.getContentLength ()]; - - // Now read all the data into the buffer - i.readFully (data); - - } catch (IOException ex) { - // Either the URL wasn't there or we couldn't get the data - continue; - } - } - - // Couldn't find it or it loaded improperly - if (data == null) - throw new ClassNotFoundException("Can't obtain " + className); - - return data; - } - - /** - * Load a class from across the network - * - * The newer way to do this is similar to JDK 1.2 URLClassLoader: - * Add URLs that end in '/' via the addURLPath method - * Call loadClass (class name without .class extension) method - * - *@param url URL of the class to load - *@exception ClassNotFoundException Couldn't find the class - *@return loaded Class - */ - public Class loadClass (URL url) throws ClassNotFoundException - { - // Extract the name of the class from the URL - String URLPath = url.getFile(); - - // Get the class name by removing any directory information - int idx = URLPath.lastIndexOf("/"); - if (idx == -1) - throw new ClassNotFoundException("Can't find " + URLPath); - String className = URLPath.substring(idx + 1); - URLPath = URLPath.substring(0, idx + 1); - - // Get rid of the class suffix - idx = className.lastIndexOf(".class"); - if (idx != -1) - className = className.substring(0, idx); - - ACE.DEBUG("The name of the class about to load is " + className); - - try { - // Add the URL to the list of URL search paths - URL path = new URL(URLPath); - - this.addURLPath(path); - - } catch (MalformedURLException e) { - throw new ClassNotFoundException("Can't find " + URLPath); - } - - // Try to load the class - return loadClass(className); - } - - /** - * Collection of URLs which end in the HTTP path separator. Used - * for searching for classes across the network. - */ - protected Vector URLSearchPaths_; -} diff --git a/java/JACE/ServiceConfigurator/ServiceObject.java b/java/JACE/ServiceConfigurator/ServiceObject.java deleted file mode 100644 index 4538698e8a6..00000000000 --- a/java/JACE/ServiceConfigurator/ServiceObject.java +++ /dev/null @@ -1,130 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ServiceObject.java - * - *@author Prashant Jain - *@author Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import JACE.ASX.*; -import JACE.Reactor.*; - -/** - * Provides a default implementation of the Service interface, and can also - * be registered with the Reactor. - * - *@see JACE.Reactor - *@see Service - */ -public class ServiceObject implements EventHandler, Service -{ - /** - * Initialize object when dynamic loading occurs. Overwrite this - * method to do anything useful. - *@return -1 (default implementation) - */ - public int init (String [] args) - { - return -1; - } - - /** - * Terminate the object. Note that an object can not be explicitly - * unloaded. Overwrite this method to do anything useful. - *@return -1 (default implementation) - */ - public int fini () - { - return -1; - } - - /** - * Get information on an active object. Overwrite this method to do - * anything useful. - *@return null (default implementation) - */ - public String info () - { - return null; - } - - /** - * Called when timer expires. Overwrite this method to do - * anything useful. - *@param tv Time Value for when timer expired - *@param obj An arbitrary object that was passed to the Timer Queue - * (Asynchronous Completion Token) - *@return -1 - */ - public int handleTimeout (TimeValue tv, Object obj) - { - return -1; - } - - /** - * Request that this service suspend activity. Overwrite this - * method to do anything useful. Currently, this sets an internal - * state variable to true. - */ - public int suspend () - { - this.suspended_ = true; - - return 0; - } - - /** - * Request that this service resume activity. Currently, this sets - * an internal state variable to false. - */ - public int resume () - { - this.suspended_ = false; - - return 0; - } - - /** - * Is this service suspended? - */ - public boolean suspended () - { - return this.suspended_; - } - - /** - * Return the name of the Service. Implementation provided. - */ - public String name () - { - return this.name_; - } - - /** - * Set the name of the Service. Should be called when a Service is - * created -- this is done automatically by ServiceConfig when loading - * from a file. Implementation provided. - */ - public void name (String name) - { - this.name_ = name; - } - - /** - * Name of this ServiceObject. - */ - protected String name_ = null; - - /** - * Status of whether this ServiceObject is suspended or not. - * (Initially false) - */ - protected boolean suspended_ = false; -} diff --git a/java/JACE/ServiceConfigurator/ServiceRepository.java b/java/JACE/ServiceConfigurator/ServiceRepository.java deleted file mode 100644 index 33f9a088077..00000000000 --- a/java/JACE/ServiceConfigurator/ServiceRepository.java +++ /dev/null @@ -1,274 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ServiceRepository.java - * - * The service repository stores the network services, allowing them to be - * removed, suspended, resumed, etc. - * - *@see JACE.ServiceConfigurator.ServiceConfig; - *@see JACE.ServiceConfigurator.Service; - * - *@author Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import java.util.*; - -/** - * Stores Services, providing operations such as remove, suspend, resume, etc. - */ -public class ServiceRepository -{ - /** - * Constructor - */ - public ServiceRepository () - { - this.serviceMap_ = new Hashtable (); - this.serviceNames_ = new Vector (); - } - - /** - * Constructor - * - *@param initialSize Initial vector size for the repository - */ - public ServiceRepository (int initialSize) - { - this.serviceMap_ = new Hashtable (initialSize); - this.serviceNames_ = new Vector (initialSize); - } - - /** - * Shut down all the services, closing them in reverse order of insertion. - * This calls fini on each service. - *@return -1 on failure, 0 on sucess - */ - public int close() - { - int result = 0; - - for (int i = this.size() - 1; i >= 0; i--) { - - String name = (String)this.serviceNames_.elementAt (i); - - Service s = (Service)this.serviceMap_.get (name); - - result = (s.fini () == -1 ? -1 : result); - } - - this.serviceMap_.clear (); - this.serviceNames_.removeAllElements (); - - return result; - } - - /** - * Insert a Service into the repository. - * (If already in, calls fini() and replaces) - * - *@param service Service to add - */ - public void insert (Service service) - { - String name = service.name (); - Service alreadyIn = this.find (name); - - if (alreadyIn != null) { - - alreadyIn.fini (); - this.remove (alreadyIn); - - } else { - - this.serviceMap_.put (name, service); - this.serviceNames_.addElement (name); - - } - } - - /** - * Returns an enumeration of all the Service objects. - * - */ - public Enumeration services () - { - return this.serviceMap_.elements (); - } - - /** - * Returns an enumeration of all the Service names - */ - public Enumeration serviceNames () - { - return this.serviceMap_.keys (); - } - - /** - * Convenience method that returns null when the service isn't - * found. - */ - public Service find (String name) - { - Object serviceObj = this.serviceMap_.get (name); - - if (serviceObj == null) - return null; - - return (Service)serviceObj; - } - - /** - * Finds the Service associated with a given - * name. - * - *@param name Name of the service to find - *@exception NoSuchElementException if the given service is not found - */ - protected Service findService (String name) throws NoSuchElementException - { - Object serviceObj = this.serviceMap_.get (name); - - if (serviceObj == null) - throw new NoSuchElementException ("Service " + name + " not found."); - - return (Service)serviceObj; - } - - /** - * Removes the given Service and calls its fini () method. - *@param service Service to remove - *@return -1 on failure, 0 on success - */ - protected int remove (Service service) - { - String name = service.name (); - - this.serviceMap_.remove (name); - - int index = this.serviceNames_.indexOf (name); - - this.serviceNames_.removeElementAt (index); - - return service.fini (); - } - - /** - * Shut down the specified Service. - * - *@param name name of the Service to shut down - *@return -1 on failure, 0 on success - */ - public int fini (String name) - { - Service service = this.findService (name); - - return service.fini (); - } - - /** - * Remove the specified Service, calling its fini () method. - * - *@param name name of the Service to remove - *@return -1 on failure, 0 on success - */ - public int remove (String name) - { - Service service = this.findService (name); - - return this.remove (service); - } - - /** - * Resume a suspended service - *@param name Name of the service to resume - *@return -1 on failure, 0 on success - */ - public int resume (String name) - { - Service service = this.findService (name); - - return service.resume(); - } - - /** - * Suspend a service - *@param name Name of the service to suspend - *@return -1 on failure, 0 on success - */ - public int suspend (String name) - { - Service service = this.findService (name); - - if (service.suspended ()) - return 0; - - return service.suspend (); - } - - /** - * Returns status information about the specified Service. - * - *@param name name of the Service to query - *@return String of information about the Service's status - */ - public String info (String name) - { - Service service = this.findService (name); - - return service.info (); - } - - /** - * Check to see if the specified Service is suspended or not - */ - public boolean suspended (String name) - { - Service service = this.findService (name); - - return service.suspended (); - } - - /** - * Initialize the specified Service with the given command - * line arguments. - */ - public int init (String name, String [] args) - { - Service service = this.findService (name); - - return service.init (args); - } - - /** - * Returns the number of items in the repository - */ - public int size () - { - return this.serviceNames_.size(); - } - - /** - * Stores the Service names in order of insertion - */ - Vector serviceNames_; - - /** - * A mapping between Service names and Service objects - */ - Hashtable serviceMap_; -}; - - - - - - - - diff --git a/java/JACE/ServiceConfigurator/package.html b/java/JACE/ServiceConfigurator/package.html deleted file mode 100644 index 2092fc34f5a..00000000000 --- a/java/JACE/ServiceConfigurator/package.html +++ /dev/null @@ -1,10 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Point for loading and managing services. -<P> -See also: -<a href="http://www.cs.wustl.edu/~schmidt/ACE-papers.html#config"> -Documents on the ACE Service Configurator</a> -</BODY> -</HTML> diff --git a/java/JACE/Timers/ProfileTimer.java b/java/JACE/Timers/ProfileTimer.java deleted file mode 100644 index 210d8887907..00000000000 --- a/java/JACE/Timers/ProfileTimer.java +++ /dev/null @@ -1,46 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Timers - * - * = FILENAME - * ProfileTimer.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Timers; - -/** - * A Java wrapper for interval timers. - */ -public class ProfileTimer -{ - /** - * Start the timer. - */ - public void start () - { - this.startTime_ = java.lang.System.currentTimeMillis (); - } - - /** - * Stop the timer. - */ - public void stop () - { - this.stopTime_ = java.lang.System.currentTimeMillis (); - } - - /** - * Determine elapsed time between start and stop. - *@return Total elapsed time (stop - start). - */ - public long elapsedTime () - { - return this.stopTime_ - this.startTime_; - } - - private long startTime_; - private long stopTime_; -} diff --git a/java/JACE/Timers/package.html b/java/JACE/Timers/package.html deleted file mode 100644 index 4aa67ec1fd6..00000000000 --- a/java/JACE/Timers/package.html +++ /dev/null @@ -1,8 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Time related classes. - -@see JACE.ASX.TimeValue -</BODY> -</HTML> diff --git a/java/JACE/makebat.zip b/java/JACE/makebat.zip Binary files differdeleted file mode 100644 index a05c72f274e..00000000000 --- a/java/JACE/makebat.zip +++ /dev/null diff --git a/java/JACE/netsvcs/Handler.java b/java/JACE/netsvcs/Handler.java deleted file mode 100644 index 7bf73f01206..00000000000 --- a/java/JACE/netsvcs/Handler.java +++ /dev/null @@ -1,185 +0,0 @@ -package JACE.netsvcs; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.Connection.*; - -/** - * Abstract class representing a handler for a Server. Provides - * default implementations and template methods. - * - *@see Server - *@author Everett Anderson - */ -public abstract class Handler extends SvcHandler -{ - /** - * Initialize this Handler. The default implementation sets the - * done flag to false. - * - *@return -1 on failure, 0 on success - */ - public int open (Object obj) - { - done_ = false; - return 0; - } - - /** - * Shut down this handler. Default implementation calls close (). - */ - public int close (long flags) - { - return close (); - } - - /** - * Shut down this handler, setting the done flag, and removing it - * from the parent Server's handler list. - */ - public synchronized int close () - { - if (!done ()) { - try { - done_ = true; - parent_.removeHandler (this); - peer ().close (); - } catch (IOException e) { - return -1; - } - } - - return 0; - } - - /** - * Returns the name of the host that is connected to this handler, - * or null if not connected. - */ - public String hostName () - { - if (done ()) - return null; - else - return this.peer().socket().getInetAddress().getHostName(); - } - - /** - * Process a single request and handle any errors. The default - * implementation calls handleRequest with an Object from - * newRequest (). - */ - public void handleRequest () - { - handleRequest (newRequest ()); - } - - /** - * Process a single request and handle any errors. The default - * implementation calls processRequest with the given request - * Object, and then handles exceptions appropriately. Subclasses - * normally just implement processRequest rather than override - * this method. - * - *@param request request to process - */ - public void handleRequest (Object request) - { - try { - - processRequest (request); - - } catch (NullPointerException e) { - if (!done ()) { - ACE.ERROR("Failure: " + e); - close (); - } - } catch (SocketException e) { - if (!done ()) { - ACE.DEBUG (hostName () + " disconnected"); - close (); - } - } catch (EOFException e) { - if (!done ()) { - ACE.DEBUG (hostName () + " disconnected"); - close (); - } - } catch (IOException e) { - if (!done ()) { - ACE.ERROR ("Lost connection: " + e); - close (); - } - } - } - - /** - * Process a single request (including reading it from the wire) - * without handling errors. Subclasses must define the behavior. - * - *@param requestObject request to process - *@exception SocketException problem with the socket - *@exception EOFException end of connection, - * usually means client disconnected - *@exception IOException error during transmission - */ - protected abstract void processRequest (Object requestObject) - throws SocketException, EOFException, IOException; - - /** - * Returns a new instance of a request object. Subclasses must - * define the behavior. - */ - public abstract Object newRequest (); - - /** - * Called by the JVM when a Handler is run in its own Thread. The - * default implementation creates a single request object which is - * reused during multiple handleRequest calls. The loop exits - * when the Handler's done() method returns true. - */ - public void run() - { - Object request = newRequest (); - - while (!done ()) - handleRequest (request); - - close (); - } - - /** - * Set the Server parent of this Handler. - */ - public void parent (Server parent) - { - parent_ = parent; - } - - /** - * Return the Server parent of this Handler. - */ - public Server parent () - { - return parent_; - } - - /** - * Check to see if this Handler should shut down. - */ - protected synchronized boolean done () - { - return done_; - } - - /** - * Closes the handler, freeing resources. - */ - protected void finalize () throws Throwable - { - close (); - } - - private boolean done_ = true; - private Server parent_; -} diff --git a/java/JACE/netsvcs/Logger/LogRecord.java b/java/JACE/netsvcs/Logger/LogRecord.java deleted file mode 100644 index 972cf45af74..00000000000 --- a/java/JACE/netsvcs/Logger/LogRecord.java +++ /dev/null @@ -1,290 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.netsvcs.Logger - * - * = FILENAME - * LogRecord.java - * - *@author Chris Cleeland, Everett Anderson - * - *************************************************/ -package JACE.netsvcs.Logger; - -import java.util.*; -import java.io.*; -import JACE.OS.*; - -/** - * Communicates logging information. Compatible with the C++ ACE - * ACE_Log_Record class. - */ -public class LogRecord -{ - /** - * Maximum size of a LogRecord - */ - final public int MAXLOGMSGLEN = 4 * 1024; - - private int type_; - private int length_; - private long msec_; - private int pid_; - private byte[] msgData_; - private final static int numIntMembers = 5; - private final static int sizeofIntInBytes = 4; - - /** - * Create a default instance. - */ - public LogRecord() - { - type(0); - timeStamp((int)new Date().getTime()); - length(0); - pid(0); - } - - /** - * Create a LogRecord. This is the designated initializer. - * @param priority a numeric specification of the priority (ascending) - * @param milliseconds time attached to the log entry in Unix <pre>time_t</pre> format - * @param pid the process ID - */ - public LogRecord(int priority, - long milliseconds, - int pid) - { - type(priority); - timeStamp(milliseconds); - length(0); - pid(pid); - } - - /** - * Create a LogRecord with the current time and the given message. - * - *@param message message to log - */ - public LogRecord (String message) - { - this (); - - msgData (message); - } - - /** - * Conversion to string. Only includes the <pre>msgData_</pre> member. - */ - public String toString() - { - String result = null; - try { - result = new String (msgData_, - "US-ASCII"); - } catch (UnsupportedEncodingException e) { - result = new String (msgData_); - } - - return result; - } - - /** - * Place a textual representation of the record on a PrintStream. - * When verbose is specified to be true, the output takes the form - * <PRE>(Date)@(host name)@(PID)@(type)@(message)</PRE> - * Otherwise it just prints the message. - * @param hostname name of the host generating this record - * @param verbose specify how much information to print (see above) - * @param ps A PrintStream instance to which the output should go. - */ - public void print(String hostname, - boolean verbose, - PrintStream ps) - { - String toprint; - if (verbose) - { - Date now = new Date(this.timeStamp()); - - /* 01234567890123456789012345 */ - /* Wed Oct 18 14:25:36 1989n0 */ - toprint = now.toString().substring(4) + "@" - + hostname + "@" + pid_ + "@" + type_ + "@" - + this.toString(); - } - else - { - toprint = this.toString(); - } - ps.println(toprint); - } - - /** - * Read in the data for this LogRecord from the given InputStream. - * - *@param is InputStream to read from - *@exception IOException error during transmission - */ - public void streamInFrom (InputStream is) throws IOException - { - BufferedInputStream bis = new BufferedInputStream (is); - - DataInputStream dis = new DataInputStream (bis); - - streamInFrom (dis); - } - - /** - * Read in the data for this LogRecord from the given DataInputStream. - * - *@param dis DataInputStream to read from - *@exception IOException error during transmission - */ - public void streamInFrom(DataInputStream dis) throws IOException - { - // Order here must match layout order in the C++ class. - length(dis.readInt()); - type(dis.readInt()); - this.timeStamp((long)dis.readInt() * 1000); - - // Skip smaller time resolution info since we're lucky if Java's - // timer can handle more than millisecond precision, anyway - dis.skipBytes(4); - - pid(dis.readInt()); - - int dataLength = (int) (length_ - numIntMembers * sizeofIntInBytes); - - msgData_ = new byte[dataLength]; - - dis.readFully(msgData_, 0, dataLength); - } - - /** - * Write this LogRecord out to the given OutputStream. - * - *@param os OutputStream to write to - *@exception IOException error during transmission - */ - public void streamOutTo (OutputStream os) throws IOException - { - BufferedOutputStream bos = new BufferedOutputStream (os); - - DataOutputStream dos = new DataOutputStream (bos); - - streamOutTo (dos); - } - - /** - * Write this LogRecord out to the given DataOutputStream. - * - *@param dos OutputStream to write to - *@exception IOException error during transmission - */ - public void streamOutTo(DataOutputStream dos) throws IOException - { - dos.writeInt(length()); - dos.writeInt(type()); - dos.writeInt((int)(this.msec_ / 1000)); - dos.writeInt(0); - dos.writeInt(pid()); - - dos.write(msgData_); - - dos.flush (); - } - - /** - * Return the LogRecord type. - */ - public int type() { return type_; } - - /** - * Set the LogRecord type. - */ - public void type(int t) { type_ = t; } - - /** - * Return the length of this LogRecord. - */ - public int length() { return length_; } - - /** - * Set the length of this LogRecord. - */ - public void length(int l) { length_ = l; } - - /** - * Calculate the length of this LogRecord from the size of - * the message and the header. - */ - private void setLen(int msgLen) - { length(msgLen + numIntMembers * sizeofIntInBytes); } - - /** - * Return the millisec time stamp of this LogRecord. - */ - public long timeStamp() { return this.msec_; } - - /** - * Set the millisec time stamp of this LogRecord. - */ - public void timeStamp(long msec){ this.msec_ = msec; } - - /** - * Return the PID of this LogRecord. - */ - public int pid() { return pid_; } - - /** - * Set the PID of this LogRecord. - */ - public void pid(int p) { pid_ = p; } - - /** - * Return the message of this LogRecord as a byte array. - */ - public byte[] msgData() { return msgData_; } - - /** - * Set the message of this LogRecord to a given byte array. - */ - public void msgData(byte[] m) - { - int size = m.length; - - if (size > MAXLOGMSGLEN) - size = MAXLOGMSGLEN; - - this.msgData_ = new byte[size]; - - System.arraycopy(m, 0, msgData_, 0, size); - - setLen(size); - } - - /** - * Set the message of this LogRecord to a given byte array. First - * tries to use US-ASCII encoding, then uses the default encoding - * if that fails. The toString method is essentially the opposite - * version. - */ - public void msgData(String m) - { - byte temp[] = null; - try { - temp = m.getBytes("US-ASCII"); - } catch (UnsupportedEncodingException e) { - temp = m.getBytes (); - } - if (temp.length > MAXLOGMSGLEN) { - this.msgData_ = new byte[MAXLOGMSGLEN]; - - System.arraycopy(temp, 0, msgData_, 0, MAXLOGMSGLEN); - } else - this.msgData_ = temp; - - setLen(msgData_.length); - } -} diff --git a/java/JACE/netsvcs/Logger/LoggingStrategy.java b/java/JACE/netsvcs/Logger/LoggingStrategy.java deleted file mode 100644 index b7912499385..00000000000 --- a/java/JACE/netsvcs/Logger/LoggingStrategy.java +++ /dev/null @@ -1,35 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Logger - * - * = FILENAME - * LogMessageReceiver.java - * - *@author Everett Anderson - * - *************************************************/ -package JACE.netsvcs.Logger; - -import java.io.*; - -/** - * Encapsulates the handling of a LogRecord from a given host, allowing - * easy swapping of behavior in the logging service. Strategies could - * be developed to save to a file, print on a certain stream, forward - * to another service, etc. - * - *@see StderrStrategy - *@see LogRecord - */ -public interface LoggingStrategy -{ - /** - * Process the given LogRecord. - * - *@param hostname host from which this LogRecord originated - *@param record LogRecord instance to process - */ - public void logRecord (String hostname, - LogRecord record); -} diff --git a/java/JACE/netsvcs/Logger/ServerLoggingAcceptor.java b/java/JACE/netsvcs/Logger/ServerLoggingAcceptor.java deleted file mode 100644 index c0ef8831fc6..00000000000 --- a/java/JACE/netsvcs/Logger/ServerLoggingAcceptor.java +++ /dev/null @@ -1,147 +0,0 @@ -package JACE.netsvcs.Logger; - -import java.util.*; -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import JACE.Connection.*; -import JACE.OS.*; -import JACE.Misc.*; -import JACE.netsvcs.Server; - -/** - * Server for the logging service. Sets the default logging strategy - * to StderrStrategy so that logging requests are printed on the - * System.err stream. Other strategies can be specified on the - * command line. - * <P> - * <B>Valid command line arguments:</B> - * <PRE> - * -r (class name) Specify a LoggingStrategy - * (Default is StdErrStrategy) - * -p (port) Port to listen on for clients - * -d Enable debugging messages - * -a (class name) Specify ActivateStrategy - * (Default is thread per connection) - * </PRE> - * - *@see LoggingStrategy - *@see StderrStrategy - */ -public class ServerLoggingAcceptor extends Server -{ - /** - * Default constructor. Sets the default LoggingStrategy to - * StderrStrategy. - */ - public ServerLoggingAcceptor () - { - name ("Logging Service"); - logStrategy_ = new StderrStrategy (); - } - - /** - * Simple main program for running the logging service without the - * service configurator. - * - *@param args command line arguments - */ - public static void main (String [] args) - { - ServerLoggingAcceptor sla = new ServerLoggingAcceptor(); - - sla.init(args); - } - - /** - * Accessor for the LoggingStrategy - */ - public LoggingStrategy loggingStrategy () - { - return this.logStrategy_; - } - - /** - * Creates a new ServerLoggingHandler instance. - */ - protected SvcHandler makeSvcHandler () - { - return new ServerLoggingHandler (); - } - - /** - * Prints out the valid command line arguments. See the class - * description for more information. Called by Server.init when - * parseArgs returns -1. - */ - protected void printUsage () - { - ACE.ERROR ("Valid options:\n"); - ACE.ERROR ("-r <class name> Specify a LoggingStrategy"); - ACE.ERROR (" (Default is StdErrStrategy"); - ACE.ERROR ("-p <port> Port to listen on for clients"); - ACE.ERROR ("-d Enable debugging messages"); - ACE.ERROR ("-a <class name> Specify ActivateStrategy"); - ACE.ERROR (" (Default is single threaded"); - } - - /** - * Parses the command line arguments. See the class description - * for more information. - * - *@param args command line arguments - *@return -1 on failure, 0 on success - */ - protected int parseArgs (String args[]) - { - String s; - Object strategy; - GetOpt opt = new GetOpt (args, "p:r:da:", true); - int c = 0; - - try { - - while ((c = opt.next ()) != -1) - { - switch (c) - { - case 'd': - ACE.enableDebugging (); - ACE.DEBUG ("Debugging is enabled"); - break; - case 'p': - if (!port (opt.optarg ())) - return -1; - break; - case 'a': - strategy = newStrategyInstance (opt.optarg (), - "ActivateStrategy"); - if (strategy == null) - return -1; - - activateStrategy ((ActivateStrategy) strategy); - break; - case 'r': - // Load the Strategy with the given name - strategy = newStrategyInstance (opt.optarg (), - "LoggingStrategy"); - if (strategy == null) - return -1; - - logStrategy_ = (LoggingStrategy)strategy; - break; - default: - ACE.ERROR ("Unknown argument: " + c); - return -1; - } - } - } catch (ArrayIndexOutOfBoundsException e) { - ACE.ERROR ("Option -" + (char)c + " requires an argument"); - return -1; - } - - return 0; - } - - private LoggingStrategy logStrategy_; -} diff --git a/java/JACE/netsvcs/Logger/ServerLoggingHandler.java b/java/JACE/netsvcs/Logger/ServerLoggingHandler.java deleted file mode 100644 index 88a564c2c34..00000000000 --- a/java/JACE/netsvcs/Logger/ServerLoggingHandler.java +++ /dev/null @@ -1,60 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Logger - * - * = FILENAME - * ServerLoggingHandler.java - * - *@author Everett Anderson - * - *************************************************/ -package JACE.netsvcs.Logger; - -import java.io.*; -import java.util.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import JACE.Connection.*; -import JACE.OS.*; -import JACE.netsvcs.Handler; - -/** - * - * Created by ServerLoggingAcceptor to handle logging requests. This - * simply reads the record and hands it to the registered LoggingStrategy. - * - * @see JACE.netsvcs.Logger.ServerLoggingAcceptor - */ -public class ServerLoggingHandler extends Handler -{ - /** - * Reads in the given LogRecord request and hands it to the - * LoggingStrategy registered with the ServerLoggingAcceptor parent. - * - *@param request LogRecord instance to use - */ - public void processRequest (Object request) - throws SocketException, EOFException, IOException - { - LogRecord rec = (LogRecord)request; - - rec.streamInFrom (this.peer ().dataInputStream ()); - - ServerLoggingAcceptor parent = (ServerLoggingAcceptor)parent (); - - parent.loggingStrategy ().logRecord (this.hostName (), rec); - } - - /** - * Creates a new instance of LogRecord. - */ - public Object newRequest () - { - return new LogRecord (); - } -} - - - - diff --git a/java/JACE/netsvcs/Logger/StderrStrategy.java b/java/JACE/netsvcs/Logger/StderrStrategy.java deleted file mode 100644 index ee927e19062..00000000000 --- a/java/JACE/netsvcs/Logger/StderrStrategy.java +++ /dev/null @@ -1,36 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Logger - * - * = FILENAME - * DefaultLMR.java - * - * - *@author Everett Anderson - * - *************************************************/ -package JACE.netsvcs.Logger; - -import java.io.*; - -/** - * Default LoggingStrategy for the logging service. This prints out the - * LogRecord on the System.err stream. - * - * @see JACE.netsvcs.Logger.LogRecord - */ -public class StderrStrategy implements LoggingStrategy -{ - /** - * Process the given LogRecord by printing it on the System.err stream. - * - *@param hostname host from which this LogRecord originated - *@param record LogRecord instance to process - */ - public void logRecord (String hostname, - LogRecord record) - { - record.print(hostname, true, System.err); - } -} diff --git a/java/JACE/netsvcs/Logger/c.bat b/java/JACE/netsvcs/Logger/c.bat deleted file mode 100644 index 6600766df1d..00000000000 --- a/java/JACE/netsvcs/Logger/c.bat +++ /dev/null @@ -1,2 +0,0 @@ -@echo off -javac -d C:\Everett\JACE\classes *.java diff --git a/java/JACE/netsvcs/Logger/package.html b/java/JACE/netsvcs/Logger/package.html deleted file mode 100644 index 84bffb246d9..00000000000 --- a/java/JACE/netsvcs/Logger/package.html +++ /dev/null @@ -1,17 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Logging Service for processing logging records received from remote hosts. -<P> -The strategy for how to process the records can be easily changed via the -command line. -<P> -A simple test client is available in the tests directory under netsvcs\Logger. -The service itself can either be run on the command line (by running -ServerLoggingAcceptor) or by loading it with a ServiceConfig file (see -the tests for the service configurator). - -@see JACE.netsvcs.Logger.LoggingStrategy -@see <a href="http://www.cs.wustl.edu/~schmidt/ACE-netsvcs.html">ACE Network Services</a> -</BODY> -</HTML> diff --git a/java/JACE/netsvcs/Naming/NameAcceptor.java b/java/JACE/netsvcs/Naming/NameAcceptor.java deleted file mode 100644 index 7e7be457d70..00000000000 --- a/java/JACE/netsvcs/Naming/NameAcceptor.java +++ /dev/null @@ -1,313 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Naming - * - * = FILENAME - * NameAcceptor.java - * - *************************************************/ -package JACE.netsvcs.Naming; - -import java.io.*; -import java.net.*; -import java.util.*; -import JACE.OS.*; -import JACE.Misc.*; -import JACE.Connection.*; -import JACE.Reactor.*; -import JACE.ASX.TimeValue; -import JACE.netsvcs.Server; - -/** - * Server for the naming service. - * Listens on the specified port (command line option) and launches - * NameHandlers when connections are made. - * <P> - * The hash table for the mapping and a timer queue are created here. - * Periodically, if it has been changed, the mapping is saved to a file. - * If the data file exists at load time, it is read from disk. Currently, - * the service stores the entire mapping in one Hashtable (which is probably - * kept in memory at all times). - * <P> - * <B>Valid command line arguments:</B> - * <PRE> - * -f (file name) File name of the database - * (Default is namedata.dat) - * -p (port number) Port to listen on for clients - * -d Enable debugging - * -t (time sec) How often to save the database (default 60 sec) - * -a (class name) Specify ActivateStrategy - * (Default is multi-threaded) - * </PRE> - * - *@see NameHandler - * - *@author Everett Anderson - * - */ -public class NameAcceptor extends Server -{ - /** - * Constructor - */ - public NameAcceptor () - { - // Set the name in case we are not using the service - // configurator - name ("Naming Service"); - - // Create the hash table and timer queue - this.mapping_ = new Hashtable (); - this.tq_ = new TimerQueue (true); - } - - /** - * Simple main program. See the class description for more - * information about command line arguments. - */ - public static void main (String [] args) - { - // Simple main program to get things rolling - NameAcceptor na = new NameAcceptor(); - - na.init(args); - } - - /** - * Check to see if the mapping has been modified since the last - * save. - */ - synchronized boolean modifiedMapping () - { - return mappingWasModified_; - } - - /** - * Set the modified state of the mapping. - */ - synchronized void modifiedMapping (boolean value) - { - mappingWasModified_ = value; - } - - /** - * Cancels the timer which was used to save the mapping, then delegates - * to Server.fini (). - * - *@return -1 on failure, 0 on success - */ - public int fini () - { - if (!done () && tq_ != null) - tq_.cancelTimer (this); - - return super.fini (); - } - - /** - * Read the data file (if it exists) and schedule a periodic timer - * to save it at intervals. At the end, this delegates to - * Server.initialize () (which currently sets the default - * activation scheme if it wasn't defined on the command line). - * - *@see Server#initialize - *@return -1 on failure, 0 on success - */ - protected int initialize () - { - this.loadTable (); - - this.tq_.scheduleTimer (this, - null, - new TimeValue (this.updateInterval_), - new TimeValue (this.updateInterval_)); - - // Use whatever default ActivateStrategy is defined in the - // Server class (unless specified in parseArgs) - return super.initialize (); - } - - /** - * Create a new NameHandler instance. - */ - protected SvcHandler makeSvcHandler () - { - return new NameHandler (mapping_); - } - - /** - * Prints out the valid command line arguments. See the class - * description for more information. Called by Server.init when - * parseArgs returns -1. - */ - protected void printUsage () - { - ACE.ERROR ("Valid options:\n"); - ACE.ERROR ("-f <file name> File name of the database"); - ACE.ERROR (" (Default is namedata.dat)"); - ACE.ERROR ("-p <port number> Port to listen on for clients"); - ACE.ERROR ("-d Enable debugging"); - ACE.ERROR ("-t <time sec> How often to save the database"); - ACE.ERROR (" (Default is 60 seconds)"); - ACE.ERROR ("-a <class name> Specify ActivateStrategy"); - ACE.ERROR (" (Default is multi-threaded"); - } - - /** - * Parses the command line arguments. See the class description - * for more information. - * - *@param args command line arguments - *@return -1 on failure, 0 on success - */ - protected int parseArgs (String [] args) - { - int c = 0; - String s; - GetOpt opt = new GetOpt (args, "p:f:t:da:", true); - - try { - - while ((c = opt.next ()) != -1) { - switch (c) - { - case 'f': - this.filename_ = opt.optarg (); - break; - case 't': - try { - this.updateInterval_ = Integer.parseInt (opt.optarg ()); - } catch (NumberFormatException e) { - ACE.ERROR ("Invalid interval specified: " + e.getMessage ()); - return -1; - } - break; - case 'd': - ACE.enableDebugging (); - ACE.DEBUG ("Debugging is enabled"); - break; - case 'p': - if (!port (opt.optarg ())) - return -1; - break; - case 'a': - Object strategy = newStrategyInstance (opt.optarg (), - "ActivateStrategy"); - if (strategy == null) - return -1; - - activateStrategy ((ActivateStrategy) strategy); - break; - default: - ACE.ERROR ("Unknown argument: " + (char)c); - return -1; - } - } - } catch (ArrayIndexOutOfBoundsException e) { - ACE.ERROR ("Option -" + (char)c + " requires an argument"); - return -1; - } - - return 0; - } - - /** - * Loads the hash table into memory from the specified - * file. Uses ObjectInputStream. - */ - protected void loadTable () - { - File file = new File(this.filename_); - FileInputStream fis; - ObjectInputStream ois; - - Hashtable ht = null; - - try { - - if ((file.exists()) && (file.canRead())) { - - fis = new FileInputStream (file); - - ois = new ObjectInputStream(fis); - - ht = (Hashtable)ois.readObject(); - } else - return; - } catch (ClassNotFoundException e) { - ACE.ERROR(e); - } catch (StreamCorruptedException e) { - ACE.ERROR(e); - } catch (SecurityException e) { - ACE.ERROR(e); - } catch (IOException e) { - ACE.ERROR(e); - } - - if (ht != null) - this.mapping_ = ht; - - } - - /** - * Writes the table out to the specified file if it has been modified. - */ - protected void saveTable () - { - if (!modifiedMapping ()) - return; - - FileOutputStream fos; - ObjectOutputStream oos; - - try { - - fos = new FileOutputStream(this.filename_); - oos = new ObjectOutputStream(fos); - - synchronized (this.mapping_) { - oos.writeObject(this.mapping_); - - modifiedMapping (false); - } - - oos.flush(); - - oos.close(); - - } catch (OptionalDataException e) { - ACE.ERROR(e); - } catch (NotSerializableException e) { - ACE.ERROR(e); - } catch (IOException e) { - ACE.ERROR(e); - } - } - - /** - * Call back for the TimerQueue. This calls the method to save the - * hash table. The default time out is 60 seconds. - */ - public int handleTimeout (TimeValue tv, Object obj) - { - this.saveTable(); - - return 0; - } - - // Mapping data structure - Hashtable mapping_ = null; - - // Default file name - String filename_ = "namedata.dat"; - - // How often to save the table (seconds) - int updateInterval_ = 60; - - // Calls handleTimeout at updateInterval_ intervals - TimerQueue tq_ = null; - - boolean mappingWasModified_ = false; -} - diff --git a/java/JACE/netsvcs/Naming/NameHandler.java b/java/JACE/netsvcs/Naming/NameHandler.java deleted file mode 100644 index 9989e925543..00000000000 --- a/java/JACE/netsvcs/Naming/NameHandler.java +++ /dev/null @@ -1,473 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Naming - * - * = FILENAME - * NameHandler.java - * - *************************************************/ -package JACE.netsvcs.Naming; - -import java.net.SocketException; -import java.io.*; -import java.util.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.Reactor.*; -import JACE.SOCK_SAP.*; -import JACE.netsvcs.Handler; - -/** - * Handlers interaction between a client (NameProxy) and the naming - * service database. Created by NameAcceptor to handle requests. - * <P> - * In general, the user binds a name to a (value, type) pair. The type is just - * treated as just another String (in the C++ version the name and value are - * arrays of 16 bit data types and the type is an array of 8 bit chars). - * <P> - * For this to work in the hash table scheme, the type and value are wrapped in - * a ValueType class defined as a nested top level class within the - * NameHandler. - * <P> - * This is compatible with the C++ ACE remote name service. - * - *@see JACE.netsvcs.Naming.NameAcceptor - *@see JACE.netsvcs.Naming.NameRequest - *@see JACE.netsvcs.Naming.NameReply - * - *@author Everett Anderson - */ -public class NameHandler extends Handler -{ - /** - * Constructor - * - * @param mapping Hash table created in NameAcceptor - */ - public NameHandler (Hashtable mapping) - { - this.mapping_ = mapping; - } - - /** - * Read in the given NameRequest and calls dispatch. - */ - public void processRequest (Object request) - throws SocketException, EOFException, IOException - { - NameRequest nameRequest = (NameRequest)request; - - nameRequest.streamInFrom (peer ().dataInputStream ()); - - this.dispatch (nameRequest); - } - - /** - * Create a new instance of NameRequest. - */ - public Object newRequest () - { - return new NameRequest (); - } - - /** - * This is the point at which a request is sent to the various methods - * that fulfill it. It switches on the request type -- bind, - * rebind, resolve, etc. - * - *@param nameRequest The request to respond to - */ - void dispatch (NameRequest nameRequest) throws IOException - { - NameAcceptor parent = (NameAcceptor)parent (); - - // Call the various other member functions based on the - // message type of the request -- bind, rebind, etc. - switch (nameRequest.requestType()) - { - case NameRequest.BIND: - this.bind(nameRequest, false); - parent.modifiedMapping (true); - break; - case NameRequest.REBIND: - this.bind(nameRequest, true); - parent.modifiedMapping (true); - break; - case NameRequest.RESOLVE: - this.resolve(nameRequest); - break; - case NameRequest.UNBIND: - this.unbind(nameRequest); - parent.modifiedMapping (true); - break; - case NameRequest.LIST_NAMES: - this.listByName(nameRequest.name(), false); - break; - case NameRequest.LIST_VALUES: - this.listByValue(nameRequest.name(), false); - break; - case NameRequest.LIST_TYPES: - this.listByType(nameRequest.name(), false); - break; - case NameRequest.LIST_NAME_ENTRIES: - this.listByName(nameRequest.name(), true); - break; - case NameRequest.LIST_VALUE_ENTRIES: - this.listByValue(nameRequest.name(), true); - break; - case NameRequest.LIST_TYPE_ENTRIES: - this.listByType(nameRequest.name(), true); - break; - default: - ACE.ERROR("Unknown type: " + nameRequest.requestType()); - - // Send a failure message. This will only work if the other - // side is expecting something like a NameReply rather than - // a NameRequest. It would've been better to have everything - // use NameRequests to avoid this kind of thing. - NameReply reply = new NameReply (NameReply.FAILURE, 0); - reply.streamOutTo(peer ().dataOutputStream ()); - break; - } - - } - - /** - * - * Bind a name and a (value, type) pair. All this data is given in the - * NameRequest from the client. Returns a NameReply back to the client - * with either Reply.SUCCESS or Reply.FAILURE as the type. - * - *@param request NameRequest given by the client - *@param rebind Is this a rebind or not? - */ - void bind (NameRequest request, - boolean rebind) throws IOException - { - // The hash table entries consists of (String name, ValueType data) - // pairs, so create the appropriate ValueType - ValueType vt = new ValueType(request.type(), - request.value()); - - // Reply to tell sender of success or failure - NameReply reply = new NameReply(); - - // If it's a rebind request, overwrite the old entry. If the key doesn't - // exist, add it. If it does exist and it's not a bind request, return - // a failure code via a NameReply. - if ((rebind) || (!this.mapping_.containsKey(request.name()))) { - - ACE.DEBUG ("Binding: " + request.name() + " and " + vt.value_); - - // Add/Update the entry in the hash table - this.mapping_.put(request.name(), vt); - - // Set the reply code to success - reply.type(NameReply.SUCCESS); - - } else { - - ACE.DEBUG ("Key " + request.name() + " already exists"); - - // Set reply code to failure - reply.type(NameReply.FAILURE); - - // reply error code unused as far as I know - } - - reply.streamOutTo(peer ().dataOutputStream ()); - } - - /** - * Given a name, this looks up and returns the type and value. This is - * done by sending back a full NameRequest with the correct info. If - * there is a problem, an "empty" NameRequest is returned -- it has no - * name, type, or value fields. - * - *@param request NameRequest sent by the client (has the name to lookup) - */ - void resolve (NameRequest request) throws IOException - { - // A NameRequest is also used in response - NameRequest result; - - // If the requested name is in the hash table, return the data - if (this.mapping_.containsKey(request.name())) { - - // Get the data pair based on the name - ValueType vt = (ValueType)this.mapping_.get(request.name()); - - ACE.DEBUG("Good resolve: " + vt.value_); - - // Fill the reply structure - result = new NameRequest(NameRequest.RESOLVE, - null, - vt.value_, - vt.type_, - null); - - } else { - - // Otherwise return a null response - result = new NameRequest(NameRequest.RESOLVE, - null, - null, - null, - null); - - } - - result.streamOutTo (peer ().dataOutputStream ()); - } - - /** - * - * Given a name, remove its entry in the mapping. Returns a NameReply - * to the client with NameReply.SUCCESS or NameReply.FAILURE. - * - *@param request NameRequest from the client (has the name to remove) - */ - void unbind (NameRequest request) throws IOException - { - NameReply reply = new NameReply(); - - // If the given key isn't in the table, return an error - // Otherwise remove it. Uses a NameReply to respond. - if (!this.mapping_.containsKey(request.name())) - reply.type(NameReply.FAILURE); - else { - this.mapping_.remove(request.name()); - reply.type(NameReply.SUCCESS); - } - - // Send the reply out to the socket - reply.streamOutTo (peer ().dataOutputStream ()); - } - - /** - * - * Given a pattern string (given in NameRequest's name field), this - * finds all the entries in the mapping which have a name that begins with - * the string. Each one is sent back separately via a NameRequest, and this - * sequence is followed by a blank NameRequest. - * - *@param pattern Pattern to find (what result names should - * begin with) - *@param completeLookup Should the value and type be returned as well? - */ - void listByName (String pattern, - boolean completeLookup) throws IOException - { - // Get a listing of all the keys in the hash table - Enumeration enum = this.mapping_.keys(); - - // References used in the loop - String name; - ValueType vt; - - // A NameRequest is used to return each item corresponding to the pattern. - NameRequest result = - new NameRequest((completeLookup ? NameRequest.LIST_NAMES : - NameRequest.LIST_NAME_ENTRIES), - null, - null, - null, - null); - - // Keep ourselves safe from null pointer exceptions - if (pattern == null) - pattern = new String(""); - - // Scan through all the elements - while (enum.hasMoreElements()) { - - // Get a key - name = (String)enum.nextElement(); - - // Does it fit the pattern? - if (name.startsWith(pattern)) { - - // Set the result name - result.name(name); - - // Only make another hash table request if the user - // wants all the data - if (completeLookup) { - - // Get data from the hash table - vt = (ValueType)mapping_.get(name); - - // Set the rest of the data - result.type(vt.type_); - result.value(vt.value_); - } - - // Send it to the socket - result.streamOutTo (peer ().dataOutputStream ()); - } - } - - // Send final null message - result.name(null); - result.type(null); - result.value(null); - result.requestType(NameRequest.MAX_ENUM); - result.streamOutTo (peer ().dataOutputStream ()); - } - - /** - * - * Given a pattern string (given in NameRequest's name field), this - * finds all the entries in the mapping which have a type that begins with - * the string. Each one is sent back separately via a NameRequest, and this - * sequence is followed by a blank NameRequest. - * - *@param pattern Pattern to find (what result types should - * begin with) - *@param completeLookup Should the value be returned as well? This is - * only used to decide between LIST_TYPES and - * LIST_TYPE_ENTRIES since we might as well send - * back both if we look them up together. - */ - void listByType (String pattern, - boolean completeLookup) throws IOException - { - // Get a listing of all the keys in the hash table - Enumeration enum = this.mapping_.keys(); - - // References used in the loop - String name; - ValueType vt; - - // A NameRequest is used to return each item corresponding to the pattern. - NameRequest result = - new NameRequest((completeLookup ? NameRequest.LIST_TYPES : - NameRequest.LIST_TYPE_ENTRIES), - null, - null, - null, - null); - // Keep ourselves safe from null pointer exceptions - if (pattern == null) - pattern = new String(""); - - // Scan through all the elements - while (enum.hasMoreElements()) { - - // Get a key - name = (String)enum.nextElement(); - - // Have to get all the data for this entry to compare - vt = (ValueType)mapping_.get(name); - - // Does it fit the pattern? - if (vt.type_ != null) - if (vt.type_.startsWith(pattern)) { - - // Set the result values - result.name(name); - result.type(vt.type_); - result.value(vt.value_); - - // Send it out to the socket - result.streamOutTo (peer ().dataOutputStream ()); - } - } - - // Send final null message - result.name(null); - result.type(null); - result.value(null); - result.requestType(NameRequest.MAX_ENUM); - result.streamOutTo (peer ().dataOutputStream ()); - } - /** - * - * Given a pattern string (given in NameRequest's name field), this - * finds all the entries in the mapping which have a value that begins with - * the string. Each one is sent back separately via a NameRequest, and this - * sequence is followed by a blank NameRequest. - * - *@param pattern Pattern to find (what result values should - * begin with) - *@param completeLookup Should the value be returned as well? This is - * only used to decide between LIST_TYPES and - * LIST_TYPE_ENTRIES since we might as well send - * back both if we look them up together. - */ - void listByValue (String pattern, - boolean completeLookup) throws IOException - { - // Get a listing of all the keys in the hash table - Enumeration enum = this.mapping_.keys(); - - // References used in the loop - String name; - ValueType vt; - - // A NameRequest is used to return each item corresponding to the pattern. - NameRequest result = - new NameRequest((completeLookup ? NameRequest.LIST_VALUES : - NameRequest.LIST_VALUE_ENTRIES), - null, - null, - null, - null); - // Keep ourselves safe from null pointer exceptions - if (pattern == null) - pattern = new String(""); - - // Scan through all the elements - while (enum.hasMoreElements()) { - - // Get a key - name = (String)enum.nextElement(); - - // Have to get all the data for this entry to compare - vt = (ValueType)mapping_.get(name); - - // Does it fit the pattern? - if (vt.value_ != null) - if (vt.value_.startsWith(pattern)) { - - // Set the result values - result.name(name); - result.type(vt.type_); - result.value(vt.value_); - - // Send it out to the socket - result.streamOutTo (peer ().dataOutputStream ()); - } - } - - // Send final null message - result.name(null); - result.type(null); - result.value(null); - result.requestType(NameRequest.MAX_ENUM); - result.streamOutTo (peer ().dataOutputStream ()); - } - - // References to the hash table and the timer queue - private Hashtable mapping_; - - /** - * A simple wrapper to keep the type and value together in - * the hash table. - */ - static class ValueType implements Serializable - { - /** - * Constructor - * - *@param type Type string to include - *@param value Value string to include - */ - ValueType(String type, String value) - { this.type_ = type; this.value_ = value; } - - public String type_; - public String value_; - } -} diff --git a/java/JACE/netsvcs/Naming/NameProxy.java b/java/JACE/netsvcs/Naming/NameProxy.java deleted file mode 100644 index 9b1b3102f1d..00000000000 --- a/java/JACE/netsvcs/Naming/NameProxy.java +++ /dev/null @@ -1,405 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Naming - * - * = FILENAME - * NameProxy.java - * - *************************************************/ -package JACE.netsvcs.Naming; - -import java.io.*; -import java.net.*; -import java.util.*; -import JACE.OS.*; -import JACE.SOCK_SAP.*; -import JACE.Connection.*; - -/** - * Proxy which clients can use to interact with the naming service. - * Can be used with the Connector. - * - *@see JACE.Connection.Connector - *@see NameAcceptor - *@see NameHandler - * - *@author Everett Anderson - */ -public class NameProxy extends SvcHandler -{ - /** - * Constructor, connects itself using a Connector. - * - *@param host name of the host of the naming service - *@param port port to connect to on the host - */ - public NameProxy (String host, int port) - throws UnknownHostException, - SocketException, - InstantiationException, - IllegalAccessException, - IOException - { - Connector c = new Connector (); - c.open (host, port); - c.connect (this); - } - - /** - * Default constructor. Proxies created with this constructor must - * be connected to use. - */ - public NameProxy () - { - } - - /** - * Constructor taking a SOCKStream to use. - * - *@param sock SOCKStream already open to the naming service - */ - public NameProxy (SOCKStream sock) - { - this.stream_ = sock; - } - - /** - * Initialize this proxy. (Called by Connector) - */ - public int open (Object obj) - { - connected_ = true; - return 0; - } - - /** - * Close the proxy, shutting down the connection to the service. - */ - public int close () - { - if (!connected_) - return 0; - - try { - this.peer ().close (); - } catch (IOException e) { - return -1; - } finally { - connected_ = false; - } - - return 0; - } - - /** - * Attempt to bind the given data pair - * @param name Name/key - * @param value Value to bind - * - * @return True iff bind is successful - */ - public boolean bind(String name, String value) throws IOException - { - return this.bind(name, value, null, false); - } - - /** - * Attempt to bind the given data triplet - * @param name Name/key - * @param value Value to bind - * @param type Type to bind (another string) - * - * @return True iff the bind was successful - */ - public boolean bind(String name, String value, String type) - throws IOException - { - return this.bind(name, value, type, false); - } - - /** - * The most generic of the bind methods. Allows factoring out of - * common code. Not public. - */ - boolean bind (String name, String value, String type, boolean rebind) - throws IOException - { - // Create a new NameRequest with the desired info - NameRequest request = - new NameRequest(rebind ? NameRequest.REBIND : NameRequest.BIND, - name, - value, - type, - null); - - // Send it to the naming service - request.streamOutTo(this.stream_); - - // Create a reply - NameReply reply = new NameReply(); - - // Get the status of the bind from the naming service - reply.streamInFrom(this.stream_); - - // Return true on success - return (reply.type() == NameReply.SUCCESS ? true : false); - } - - /** - * Rebind a name and a value - * @param name Name/key - * @param value Bound value - * - * @return True if the rebind was successful - */ - public boolean rebind (String name, String value) throws IOException - { - return this.bind(name, value, null, true); - } - - /** - * Rebind a name, value, and type - * @param name Name/key - * @param value Bound value - * @param type Bound type - * - * @return True if rebind was successful - */ - public boolean rebind (String name, String value, String type) - throws IOException - { - return this.bind(name, value, type, true); - } - /** - * Look up information bound to the given key/name. - * - * @param name Name/key - * - * @return Vector with three elements: - * 0 Name/key - * 1 Value - * 2 Type - */ - public Vector resolve (String name) throws IOException - { - // Create a new NameRequest with the name & request type - NameRequest request = new NameRequest(NameRequest.RESOLVE, - name, - null, - null, - null); - - // Send it to the naming service - request.streamOutTo(this.stream_); - - // Get a response (hopefully with the value and type) - request.streamInFrom(this.stream_); - - // Dump the result into a vector - Vector result = new Vector(); - - result.addElement(request.name()); - result.addElement(request.value()); - result.addElement(request.type()); - - // Cut it down to the size we need - result.trimToSize(); - - return result; - } - - /** - * Remove the entry in the mapping corresponding to the given name/key. - * - * @param name Name/key - * - * @return True if the unbind was successful - */ - public boolean unbind (String name) throws IOException - { - NameRequest request = new NameRequest(NameRequest.UNBIND, - name, - null, - null, - null); - // Send the request to the naming service - request.streamOutTo(this.stream_); - - NameReply reply = new NameReply(); - - // Get reply - reply.streamInFrom(this.stream_); - - return (reply.type() == NameReply.SUCCESS ? true : false); - } - - /** - * Return a vector that's a list of names (Strings) that begin with - * the given pattern - * @param pattern Search pattern - * @return Vector List of names - */ - public Vector listNames (String pattern) throws IOException - { - return this.requestSimpleList(pattern, NameRequest.LIST_NAMES); - } - - /** - * Return a vector that's a list of types (Strings) that begin with - * the given pattern - * @param pattern Search pattern - * @return Vector List of types - */ - public Vector listTypes (String pattern) throws IOException - { - return this.requestSimpleList(pattern, NameRequest.LIST_TYPES); - } - - /** - * Return a vector that's a list of values (Strings) that begin with - * the given pattern - * @param pattern Search pattern - * @return Vector List of values - */ - public Vector listValues (String pattern) throws IOException - { - return this.requestSimpleList(pattern, NameRequest.LIST_VALUES); - } - - /** - * Non-public generic list gathering method - */ - Vector requestSimpleList (String pattern, int type) throws IOException - { - // Make request for a list of the given type - NameRequest request = new NameRequest(type, - pattern, - null, - null, - null); - request.streamOutTo(this.stream_); - - // Allocate and reuse the DIS here rather than each time we call - // streamInFrom - DataInputStream dis = new DataInputStream(this.stream_.inputStream()); - - request.streamInFrom(dis); - Vector result = new Vector(); - - // Add elements until there's a null message with the MAX_ENUM - // request type - while (request.requestType() != NameRequest.MAX_ENUM) { - if (type == NameRequest.LIST_NAMES) - result.addElement(new String(request.name())); - else - if (type == NameRequest.LIST_VALUES) - result.addElement(new String(request.value())); - else - result.addElement(new String(request.type())); - - request.streamInFrom(dis); - } - - // Adjust the vector to the minimal size - result.trimToSize(); - - return result; - } - - /** - * Get a vector with the entire data set for entries whose name begins with - * the given pattern. Each element in the vector is another vector - * with the following layout: - * 0 Name/key - * 1 Value - * 2 Type - * - * @param pattern Search pattern - * @return Vector of vectors - */ - public Vector listNameEntries (String pattern) throws IOException - { - return this.requestComplexList(pattern, NameRequest.LIST_NAME_ENTRIES); - } - - /** - * Get a vector with the entire data set for entries whose value begins with - * the given pattern. Each element in the vector is another vector - * with the following layout: - * 0 Name/key - * 1 Value - * 2 Type - * - * @param pattern Search pattern - * @return Vector of vectors - */ - public Vector listValueEntries (String pattern) throws IOException - { - return this.requestComplexList(pattern, NameRequest.LIST_VALUE_ENTRIES); - } - - /** - * Get a vector with the entire data set for entries whose type begins with - * the given pattern. Each element in the vector is another vector - * with the following layout: - * 0 Name/key - * 1 Value - * 2 Type - * - * @param pattern Search pattern - * @return Vector of vectors - */ - - public Vector listTypeEntries (String pattern) throws IOException - { - return this.requestComplexList(pattern, NameRequest.LIST_TYPE_ENTRIES); - } - - /** - * Non-public generic method for getting a a vector of vectors with the - * entire data set for entries fitting the given pattern. - */ - Vector requestComplexList (String pattern, int type) throws IOException - { - // Create request with desired type - NameRequest request = new NameRequest(type, - pattern, - null, - null, - null); - // Send it to the naming service - request.streamOutTo(this.stream_); - - // Allocate the DIS here and reuse - DataInputStream dis = new DataInputStream(this.stream_.inputStream()); - - // Get the first response - request.streamInFrom(dis); - Vector result = new Vector(); - - // Loop while we don't see a null response with the MAX_ENUM - //request type - while (request.requestType() != NameRequest.MAX_ENUM) { - Vector entry = new Vector(); - - // Create an element in the main vector - entry.addElement(request.name()); - entry.addElement(request.value()); - entry.addElement(request.type()); - entry.trimToSize(); - - // Add it to the result - result.addElement(entry); - - // Get another NameRequest - request.streamInFrom(dis); - } - - result.trimToSize(); - - return result; - } - - private boolean connected_ = false; -} diff --git a/java/JACE/netsvcs/Naming/NameReply.java b/java/JACE/netsvcs/Naming/NameReply.java deleted file mode 100644 index d20c9ed05f0..00000000000 --- a/java/JACE/netsvcs/Naming/NameReply.java +++ /dev/null @@ -1,169 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Naming - * - * = FILENAME - * NameReply.java - * - *************************************************/ -package JACE.netsvcs.Naming; - -import java.io.*; -import java.util.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.Reactor.*; -import JACE.ASX.*; -import JACE.SOCK_SAP.*; - -/** - * Used by the naming server to give quick status messages - * to the client. This is only used to signal the success or - * failure of bind and unbind requests. The error number seems - * to be unused in the C++ version. - * - *@see NameHandler - *@author Everett Anderson - * - */ -public class NameReply -{ - /** Successful operation indicator */ - public final static int SUCCESS = 0; - - /** Failed operation indicator */ - public final static int FAILURE = -1; - - /** - * Default Constructor (success, errno 0) - */ - public NameReply () - { - this.type_ = this.SUCCESS; - this.errno_ = 0; - } - - /** - * Constructor - * - *@param type Success or failure - *@param err Error number (unused) - */ - public NameReply (int type, int err) - { - this.type_ = type; - this.errno_ = err; - } - - /** - * Length accessor - */ - int length() - { return this.length_; } - - /** - * Type accessor -- success or failure - */ - int type() - { return this.type_; } - - /** - * Error number accessor - */ - int errno() - { return this.errno_; } - - /** - * Set type - * @param type New type - */ - void type(int type) - { this.type_ = type; } - - /** - * Set error number - * @param errno New error number - */ - void errno(int errno) - { this.errno_ = errno; } - - /** - * Send this data to the given SOCKStream. - * - *@param sock SOCKStream to send to - */ - public void streamOutTo (JACE.SOCK_SAP.SOCKStream sock) throws IOException - { - streamOutTo (sock.dataOutputStream ()); - } - - /** - * Send this instance to the given DataOutputStream. - */ - public void streamOutTo (DataOutputStream dos) throws IOException - { - dos.writeInt(this.length_); - dos.writeInt(this.type_); - dos.writeInt(this.errno_); - - dos.flush(); - } - - /** - * Send this instance to the given OutputStream. - */ - public void streamOutTo (OutputStream os) throws IOException - { - BufferedOutputStream bos = new BufferedOutputStream (os); - DataOutputStream dos = new DataOutputStream (bos); - - streamOutTo (dos); - } - - /** - * Fill the fields of this instance from data in the socket - * - *@param sock SOCKStream to read from - */ - public void streamInFrom (JACE.SOCK_SAP.SOCKStream sock) throws IOException - { - this.streamInFrom(sock.dataInputStream ()); - } - - /** - * Fill this instance from the DataInputStream (which should be buffered). - * - *@param dis DataInputStream to use - */ - public void streamInFrom (DataInputStream dis) throws IOException - { - int length = dis.readInt(); - - if (length != this.length_) - throw new IOException("Incorrect NameReply length"); - - type_ = dis.readInt(); - errno_ = dis.readInt(); - } - - /** - * Fill this instance from the given InputStream. - */ - public void streamInFrom (InputStream is) throws IOException - { - BufferedInputStream bis = new BufferedInputStream (is); - DataInputStream dis = new DataInputStream (bis); - - streamInFrom (dis); - } - - final static int length_ = 12; - - int type_; - int errno_; -} - - - - diff --git a/java/JACE/netsvcs/Naming/NameRequest.java b/java/JACE/netsvcs/Naming/NameRequest.java deleted file mode 100644 index 706b14728c5..00000000000 --- a/java/JACE/netsvcs/Naming/NameRequest.java +++ /dev/null @@ -1,373 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Naming - * - * = FILENAME - * NameRequest.java - * - *@see netsvcs.Naming.NameHandler - * - *@author Everett Anderson - * - *************************************************/ -package JACE.netsvcs.Naming; - -import java.io.*; -import java.util.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.Reactor.*; -import JACE.ASX.*; -import JACE.SOCK_SAP.*; - -/** - * Holds information including name, value, type, and request - * type. Used by both client and naming server as detailed in - * NameHandler. Compatible with the C++ ACE_Name_Request. - * - *@see NameHandler - */ -public class NameRequest -{ - /** Bind request type */ - public static final int BIND = 1; - - /** Rebind request type */ - public static final int REBIND = 2; - - /** Resolve request type */ - public static final int RESOLVE = 3; - - /** Unbind request type */ - public static final int UNBIND = 4; - - /** List Names request type */ - public static final int LIST_NAMES = 5; - - /** List Values request type */ - public static final int LIST_VALUES = 13; - - /** List Types request type */ - public static final int LIST_TYPES = 21; - - /** List Name Entries request type */ - public static final int LIST_NAME_ENTRIES = 6; - - /** List Value Entries request type */ - public static final int LIST_VALUE_ENTRIES = 14; - - /** List Type Entries request type */ - public static final int LIST_TYPE_ENTRIES = 22; - - /** Type used to send a final "null" request when returning - * a list of items */ - public static final int MAX_ENUM = 11; - /** - * Maximum length of a NameRequest instance. - * See C++ ACE Name_Request_Reply.h for the details of the - * value of this constant. - */ - public static final int MAX_LEN = 6182; - - /** - * Default constructor. - */ - public NameRequest () - { - this.name_ = this.value_ = this.type_ = null; - this.length_ = 32; - } - - /** - * Constructor - * - * @param requestType Type of request this is (BIND, REBIND, etc) - * @param name Key to bind - * @param value Value to bind - * @param type Type to couple with the value - * @param timeout Timer information (not really used in JACE yet) - */ - public NameRequest(int requestType, - String name, - String value, - String type, - TimeValue timeout) - { - this.requestType_ = requestType; - - if (timeout == null) { - - this.blockForever_ = 1; - this.secTimeout_ = 0; - this.usecTimeout_ = 0; - } else { - - this.blockForever_ = 0; - this.secTimeout_ = (int)timeout.sec(); - this.usecTimeout_ = (int)timeout.getMilliTime() * 1000; - } - - // This is necessary to make sure null pointer exceptions are - // avoided. It makes it more consistent later on - if (name == null) - this.name_ = new String(""); - else - this.name_ = new String(name); - if (value == null) - this.value_ = new String(""); - else - this.value_ = new String(value); - if (type == null) - this.type_ = new String(""); - else - this.type_ = new String(type); - - // Set the length - this.calculateLength(); - } - - /** - * Calculate the transmission length (bytes) of this structure - */ - private void calculateLength() - { - // The type is sent as an 8 bit data type (chars in the C++ version), - // but the name and value are sent as 16 bit chars (ACE_USHORT16's in C++) - - this.length_ = 34 + this.type_.length() + 2 * (this.name_.length() + - this.value_.length()); - } - - /** - * Return the transmission length - */ - public int length() - { return this.length_; } - - /** - * Return the name/key - */ - public String name() - { return new String(this.name_); } - - /** - * Set the name/key - * @param name Name to set to - */ - public void name(String name) - { - if (name == null) - this.name_ = new String(""); - else - this.name_ = new String(name); - - this.calculateLength(); - } - - /** - * Return the value - */ - public String value() - { return new String(this.value_); } - - /** - * Set the value - * @param value New value - */ - public void value(String value) - { - if (value == null) - this.value_ = new String(""); - else - this.value_ = new String(value); - - this.calculateLength(); - } - - /** - * Return the type - */ - public String type() - { return new String(this.type_); } - - /** - * Set the type - * @param type New type - */ - public void type(String type) - { - if (type == null) - this.type_ = new String(""); - else - this.type_ = new String(type); - - this.calculateLength(); - } - - /** - * Fill the fields of this instance with data from the InputStream. - */ - public void streamInFrom (InputStream is) throws IOException - { - BufferedInputStream bis = new BufferedInputStream (is); - - DataInputStream dis = new DataInputStream (bis); - - this.streamInFrom(dis); - } - - /** - * Fill the fields of this instance with data from the SOCKStream. - */ - public void streamInFrom (SOCKStream sock) throws IOException - { - streamInFrom (sock.dataInputStream ()); - } - - /** - * Fill the fields of this instance from the given DataInputStream - * - *@param dis DataInputStream to read from - */ - public void streamInFrom (DataInputStream dis) throws IOException - { - // Read the length (32 bits) - length_ = dis.readInt(); - - if (length_ > MAX_LEN) - throw new IOException ("Invalid NameRequest length " + length_); - - // Read the request type - requestType_ = dis.readInt(); - - // Can we block forever to fulfill this request? (unused) - blockForever_ = dis.readInt(); - - // How long until we should time out this request? (unused) - secTimeout_ = dis.readInt(); - usecTimeout_ = dis.readInt(); - - // The sizes are in bytes, and there are two bytes per char - // (ACE_USHORT16 in C++ land) - int nameLen = dis.readInt() / 2; - int valueLen = dis.readInt() / 2; - - int typeLen = dis.readInt(); - - // Read the name -- just read chars since they're 16 bits. - // Hopefully the SOCKStream has buffered the data - char buf[] = new char[nameLen]; - for (int i = 0; i < nameLen; i++) { - buf[i] = dis.readChar(); - } - this.name_ = new String(buf); - - // Read the value - buf = new char[valueLen]; - for (int i = 0; i < valueLen; i++) - buf[i] = dis.readChar(); - this.value_ = new String(buf); - - // Read the type -- now we can use readFully since - // the type was sent as 8 bit chars - byte tbuf[] = new byte[typeLen]; - dis.readFully(tbuf); - this.type_ = new String(tbuf); - - // Skip the null char at the end - dis.skipBytes(2); - } - - /** - * Write the data of this instance to the given SOCKStream. - */ - public void streamOutTo (SOCKStream sock) throws IOException - { - streamOutTo (sock.dataOutputStream ()); - } - - /** - * Write the data of this instance to the given OutputStream. - */ - public void streamOutTo (OutputStream os) throws IOException - { - BufferedOutputStream bos = new BufferedOutputStream (os); - DataOutputStream dos = new DataOutputStream (bos); - - streamOutTo (dos); - } - - /** - * Send this NameRequest out to the given DataOutputStream - */ - public void streamOutTo (DataOutputStream dos) throws IOException - { - dos.writeInt(length_); - dos.writeInt(requestType_); - dos.writeInt(blockForever_); - dos.writeInt(secTimeout_); - dos.writeInt(usecTimeout_); - - // Byte sizes are sent, and the name and value are stored as - // 16 bit char arrays (ACE_USHORT16 arrays in C++ version) - dos.writeInt(this.name_.length() * 2); - dos.writeInt(this.value_.length() * 2); - dos.writeInt(this.type_.length()); - - // Making sure the name_ wasn't null comes in handy - // in situations like this - dos.writeChars(this.name_); - dos.writeChars(this.value_); - dos.writeBytes(this.type_); - - // Null termination - dos.writeChar(0); - - // Send it for real - dos.flush(); - } - - /** - * Set the requestType - *@param type Type to set to - */ - public void requestType(int type) - { - this.requestType_ = type; - } - - /** - * Get requestType - */ - public int requestType() - { - return this.requestType_; - } - - /** - * Can we block forever to fulfill the request? (unused) - */ - public boolean blockForever() - { - return (this.blockForever_ != 0) ? true : false; - } - - /** - * Allowed timeout (unused) - */ - public int secTimeout() - { - return this.secTimeout_; - } - - int length_; - int requestType_; - int blockForever_; - int secTimeout_; - int usecTimeout_; - - String name_; - String value_; - String type_; -}; diff --git a/java/JACE/netsvcs/Naming/c.bat b/java/JACE/netsvcs/Naming/c.bat deleted file mode 100644 index 2b540b1b051..00000000000 --- a/java/JACE/netsvcs/Naming/c.bat +++ /dev/null @@ -1,2 +0,0 @@ -@echo off -javac -d c:\Everett\JACE\classes *.java diff --git a/java/JACE/netsvcs/Naming/package.html b/java/JACE/netsvcs/Naming/package.html deleted file mode 100644 index b7ee951fc2e..00000000000 --- a/java/JACE/netsvcs/Naming/package.html +++ /dev/null @@ -1,11 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Naming Service for associating names and values in a distributed system. -<P> -A simple test program for NameProxy and the naming service is in -the tests directory under netsvcs\Naming. - -@see <a href="http://www.cs.wustl.edu/~schmidt/ACE-netsvcs.html">ACE Network Services</a> -</BODY> -</HTML> diff --git a/java/JACE/netsvcs/Server.java b/java/JACE/netsvcs/Server.java deleted file mode 100644 index 199a830d0c5..00000000000 --- a/java/JACE/netsvcs/Server.java +++ /dev/null @@ -1,356 +0,0 @@ -package JACE.netsvcs; - -import java.io.*; -import java.net.*; -import java.util.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.Misc.GetOpt; -import JACE.ServiceConfigurator.Service; - -/** - * Abstract class providing default implementations for several - * Service methods. Currently, all the network services - * descend from this class. The real work for a service is done - * by a Handler. - * <P> - * Inner classes are provided for thread per connection - * and single threaded server activation strategies. Currently, - * specifying a single threaded strategy means that the server will - * disconnect the client after handling one request. Acceptor and - * EventHandler may be changed later to incorporate handleInput to - * address this. Thus, the default activation strategy is thread - * per connection. - * - *@see Handler - *@see JACE.Connection.ActivateStrategy - *@author Everett Anderson - */ -public abstract class Server extends Acceptor implements Runnable -{ - /** - * Safely shuts down all the handlers as well as the accepting socket. - * - *@return -1 on failure, 0 on success - */ - public synchronized int fini () - { - if (!done ()) { - ACE.DEBUG ("Shutting down " + name ()); - try { - this.done_ = true; - for (int i = handlers_.size () - 1; i >= 0; i--) - ((Handler)handlers_.elementAt (i)).close (); - - this.sockAcceptor_.close(); - } catch (IOException e) { - ACE.ERROR(e); - return -1; - } - } - - return 0; - } - - /** - * Returns information about the state of the service such as - * suspended, not running, or running. - */ - public String info () - { - if (suspended ()) - return "suspended"; - else - if (done ()) - return "not running"; - else - return "running on port " + port_; - } - - /** - * Provided for extra initialization in subclasses after the - * command line arguments have been parsed but before starting the - * service. This is a good place to set the default ActivateStrategy - * since you can make sure it wasn't set in parseArgs. The default - * implementation sets the strategy to Server.ThreadPerConnection. - * - *@return -1 on error, 0 on success - */ - protected int initialize () - { - if (activateStrategy_ == null) - activateStrategy (new Server.ThreadPerConnection ()); - - return 0; - } - - /** - * Template method for initialization. Calls parseArgs, initialize, - * sets the done() state to false, and starts this Server in its own - * thread. If parseArgs fails, this calls printUsage. - * - *@param args command line arguments - *@return -1 on failure, 0 on success - */ - public int init (String [] args) - { - // Parse arguments - if (this.parseArgs (args) == -1) { - printUsage (); - return -1; - } - - if (initialize () < 0) { - ACE.ERROR (name () + " failed initializing"); - return -1; - } - - ACE.DEBUG ("Using " + activateStrategy_.getClass().getName ()); - ACE.DEBUG ("Starting " + name () + " on port: " + this.port_); - - done_ = false; - - // Run in own thread of control so that we don't block the caller - new Thread (this).start(); - return 0; - } - - /** - * Called by the JVM when this Server starts running in its own - * thread. - */ - public void run () - { - try { - this.open (this.port_); - while (!this.done ()) { - this.accept (); - } - } catch (InstantiationException e) { - ACE.ERROR (e); - } catch (IllegalAccessException e) { - ACE.ERROR (e); - } catch (IOException e) { - if (!done ()) - ACE.ERROR (e); - } finally { - fini (); - } - } - - /** - * Calls the appropriate activation strategy with the given - * service handler. This assumes the SvcHandler is an instance - * of type Handler, and sets its parent accordingly. - * - *@param sh SvcHandler (assumed to be a Handler) to activate - *@return -1 on failure, 0 on success - */ - protected int activateSvcHandler (SvcHandler sh) - { - if (done ()) - return -1; - - addHandler (sh); - ((Handler)sh).parent (this); - - while (suspended () && !done ()) - Thread.yield (); - - if (activateStrategy_.activateSvcHandler (sh) != 0) { - removeHandler (sh); - return -1; - } - - return 0; - } - - /** - * Add the given SvcHandler to this Servers list of handlers. - * @param sh service handler to add (assumed to be a Handler) - */ - protected void addHandler (SvcHandler sh) - { - handlers_.addElement (sh); - } - - /** - * Called by Handler instances during their close () method. - *@param sh service handler to remove - */ - public void removeHandler (SvcHandler sh) - { - handlers_.removeElement (sh); - } - - /** - * Parses the command line arguments. Subclasses must override - * this. - * - *@param args command line arguments - *@return -1 on failure, 0 on success - */ - protected abstract int parseArgs (String [] args); - - /** - * Create the appropriate Handler. Subclasses must override this, - * returning a new instance of the proper subclass of Handler. - * - *@return new Handler instance - */ - protected abstract SvcHandler makeSvcHandler (); - - /** - * Print out the correct syntax and meaning of the command line - * arguments. - */ - protected abstract void printUsage (); - - /** - * Set the ActivateStrategy for handlers. - * - *@param strategy new ActivateStrategy to use - *@see JACE.Connection.ActivateStrategy - */ - protected void activateStrategy (ActivateStrategy strategy) - { - activateStrategy_ = strategy; - } - - /** - * Return the current ActivateStrategy for handlers. - * - *@return current ActivateStrategy instance - */ - protected ActivateStrategy activateStrategy () - { - return activateStrategy_; - } - - /** - * Check to see if this Server has been shut down. - */ - protected synchronized boolean done () - { - return done_; - } - - /** - * Useful method for subclasses when parsing the port command - * line option. - * - *@param port String gathered from the command line representing the port - *@return false if there was an error, true if successful - */ - protected boolean port (String port) - { - try { - - this.port_ = Integer.parseInt (port); - - } catch (NumberFormatException e) { - ACE.ERROR("Invalid port specified: " + e.getMessage ()); - return false; - } catch (ArrayIndexOutOfBoundsException e) { - ACE.ERROR("Port option requires an argument"); - return false; - } - - return true; - } - - /** - * Useful method for subclasses when trying to load and instantiate - * a certain class from a command line argument. This can be used - * when a possible command line argument is what kind of activation - * strategy is used for handlers. - * - *@param classname name of the class to load and create an instance of - *@param descrption descrption of what type of class it is - *@return null if failed loading, a new instance of the class on success - */ - protected Object newStrategyInstance (String classname, - String description) - { - try { - Class factory = Class.forName (classname); - - return factory.newInstance (); - - } catch (ClassNotFoundException e) { - ACE.ERROR("Unable to find " + description + ": " - + e.getMessage ()); - } catch (InstantiationException e) { - ACE.ERROR ("Instantiating " + description + ": " - + e.getMessage ()); - } catch (IllegalAccessException e) { - ACE.ERROR ("Illegal access on " + description + ": " - + e.getMessage ()); - } - - return null; - } - - /** - * Shuts down the Server if it wasn't already done - */ - protected void finalize () throws Throwable - { - fini (); - } - - private boolean done_ = true; - - /** - * List of currently active Handlers - */ - protected Vector handlers_ = new Vector (); - private ActivateStrategy activateStrategy_ = null; - - /** - * Activation strategy in which each Handler is run in its own - * Thread. - */ - public static class ThreadPerConnection extends ActivateStrategy - { - /** - * Opens the given service handler, and runs it in its own - * Thread. - *@param sh service handler to activate - *@return -1 on failure, 0 on success - */ - public int activateSvcHandler (SvcHandler sh) - { - if (sh.open (null) < 0) - return -1; - - new Thread (sh).start (); - return 0; - } - } - - /** - * Activation strategy in which all Handlers are run in the - * Server Thread in sequence. This assumes that the given - * SvcHandler is a Handler instance. - */ - public static class SingleThreaded extends ActivateStrategy - { - /** - * Opens the given service handler, calls Handler.handleRequest, and - * then Handler.close before returning. - *@param sh service handler to activate (assumed to be a Handler) - *@return -1 on failure, 0 on success - */ - public int activateSvcHandler (SvcHandler sh) - { - if (sh.open (null) < 0) - return -1; - - ((Handler)sh).handleRequest (); - ((Handler)sh).close (); - - return 0; - } - } -} diff --git a/java/JACE/netsvcs/Time/TSClerkHandler.java b/java/JACE/netsvcs/Time/TSClerkHandler.java deleted file mode 100644 index e0a2290d81b..00000000000 --- a/java/JACE/netsvcs/Time/TSClerkHandler.java +++ /dev/null @@ -1,195 +0,0 @@ -package JACE.netsvcs.Time; - -import java.io.*; -import java.net.*; - -import JACE.OS.*; -import JACE.Connection.*; -import JACE.ASX.*; - -/** - * Requests a time update from a time server. This is used by the - * TSClerkProcessor to query a server. - */ -public class TSClerkHandler extends SvcHandler -{ - /** - * Constructor. - * - *@param parent TSClerkProcessor which is creating this instance - *@param host name of the machine this handler is connected to - *@param port port on the time server to connect to - */ - public TSClerkHandler (TSClerkProcessor parent, - String host, - int port) - { - parent_ = parent; - host_ = host; - port_ = port; - } - - /** - * Initialize this handler. Called automatically by Connector when a - * successful connection is made. - * - *@return -1 on failure, 0 on success - */ - public int open (Object obj) - { - ACE.DEBUG ("Successful connection to " + host ()); - connected (true); - return 0; - } - - /** - * Safely shut down this handler, closing the socket. - * - *@return -1 on failure, 0 on success - */ - public synchronized int close () - { - if (!connected ()) - return 0; - - ACE.DEBUG ("Shutting down connection to " + host ()); - try { - peer ().close (); - } catch (IOException e) { - return -1; - } finally { - connected (false); - } - - return 0; - } - - /** - * Accessor for the port number of the server. - */ - public int port () - { - return port_; - } - - /** - * Accessor for the host name of the server. - */ - public String host () - { - return host_; - } - - /** - * Check to see if this handler is currently connected to a server. - */ - public synchronized boolean connected () - { - return connected_; - } - - /** - * Set the connected state. - * - *@param state true if connected, false if not - */ - protected synchronized void connected (boolean state) - { - connected_ = state; - } - - /** - * (Isn't used, just fulfills the interface. Returns -1 by - * default) - */ - public int handleTimeout (TimeValue tv, Object obj) - { - return -1; - } - - /** - * (Isn't used, just fulfills the interface.) - */ - public void run () - { - ACE.ERROR ("TSClerkHandler is not setup to run in its own thread"); - } - - /** - * Sends a request to the server and waits for a reply. This is called - * by TSClerkProcessor. - * - *@return -1 on failure, 0 on success - */ - public int sendRequest () - { - // Ask the clerk processor to connect this handler if it isn't - // already. Thus, it tries to reconnect if the server has gone - // down. - if (!connected ()) - parent_.connectHandler (this, host_, port_); - - TimeRequest request = new TimeRequest (); - - long start, stop; - try { - - start = System.currentTimeMillis (); - request.streamOutTo (peer().outputStream ()); - - request.streamInFrom (peer().inputStream ()); - stop = System.currentTimeMillis (); - - } catch (NullPointerException e) { - close (); - return -1; - } catch (IOException e) { - close (); - return -1; - } - - // Compute the difference in the local time and the server time - // (in seconds) - long difference = request.time () - (stop / 1000); - - // Calculate the transmission time (in seconds) - long oneWayTime = (stop - start) / 2000; - - difference += oneWayTime; - - /* - ACE.DEBUG (host() + " reports:"); - ACE.DEBUG (" time difference: " + difference); - ACE.DEBUG (" trans. delay: " + oneWayTime); - */ - - // Set the time difference for this handler - delta (difference); - - return 0; - } - - /** - * Returns the current time difference between local time and - * the server (in seconds). - */ - public synchronized long delta () - { - return delta_; - } - - /** - * Sets the current time difference between local time and the - * server (in seconds). - */ - protected synchronized void delta (long delta) - { - delta_ = delta; - } - - private long delta_; - private TSClerkProcessor parent_; - private boolean connected_ = false; - private String host_; - private int port_; -} diff --git a/java/JACE/netsvcs/Time/TSClerkProcessor.java b/java/JACE/netsvcs/Time/TSClerkProcessor.java deleted file mode 100644 index bec3bd417df..00000000000 --- a/java/JACE/netsvcs/Time/TSClerkProcessor.java +++ /dev/null @@ -1,307 +0,0 @@ -package JACE.netsvcs.Time; - -import java.net.*; -import java.io.*; -import java.util.*; - -import JACE.ASX.TimeValue; -import JACE.Connection.*; -import JACE.OS.*; -import JACE.Reactor.*; -import JACE.Misc.*; - -/** - * Clerk used to query a number of time servers, compute the average - * of the time differences, and report it with a sequence number. This - * can be used to adjust the current local time accordingly. - * <P> - * <B>Valid command line arguments:</B> - * <PRE> - * -h (host name:port) Specify a time server to contact - * -t (time in seconds) Specify how often to query the servers - * (Defaults to five minutes) - * -d Enable debugging messages - * </PRE> - */ -public class TSClerkProcessor implements EventHandler, Runnable -{ - /** - * Prints out the valid command line arguments. See the class - * description for more information. - */ - public void printUsage () - { - ACE.ERROR ("Valid options:"); - ACE.ERROR ("-h <host name>:<port> Specify a time server to contact"); - ACE.ERROR ("-t <time in seconds> How often to query the servers"); - ACE.ERROR ("-d Enable debugging messages"); - } - - /** - * Parses the command line arguments. See the class description - * for more information. - */ - protected int parseArgs (String args[]) - { - GetOpt opt = new GetOpt (args, "h:t:d", true); - for (int c; (c = opt.next ()) != -1; ) - { - switch (c) - { - // Specify a hostname:port pair to query - case 'h': - if (newHandler (opt.optarg ()) == -1) { - printUsage (); - return -1; - } - break; - // Specify time interval to query servers - case 't': - int sec = Integer.parseInt (opt.optarg ()); - updateInterval_ = new TimeValue (sec); - break; - case 'd': - ACE.enableDebugging (); - ACE.DEBUG ("Debugging is enabled"); - break; - default: - ACE.ERROR ("Unknown argument: " + (char)c); - printUsage (); - return -1; - } - } - return 0; - } - - /** - * Safely shut down the clerk and all its handlers. - */ - public synchronized void close () - { - if (!done_) { - done_ = true; - tq_.cancelTimer (this); - - for (int i = 0; i < handlerSet_.size (); i++) { - TSClerkHandler h = (TSClerkHandler)handlerSet_.elementAt (i); - - h.close (); - } - } - } - - /** - * Called by the JVM when the clerk is run in its own thread. If the - * TimerQueue provided to (or created by) this TSClerkProcessor isn't - * running its event loop, it will be run in this thread (by calling - * handleEvents ()). - * - *@see JACE.Reactor.TimerQueue - */ - public void run () - { - if (handlerSet_.size () == 0) { - ACE.DEBUG ("No servers are registered. Call init first."); - return; - } - - if (!tq_.eventLoopRunning ()) - tq_.handleEvents (); - } - - /** - * Initialize this TSClerkProcessor with command line arguments. See - * the class description for more information. This also schedules - * a timeout with the timer queue for when to query the servers. - * - *@return -1 on failure, 0 on success - */ - public int init (String args[]) - { - if (args.length < 2) { - printUsage (); - return -1; - } - - if (parseArgs (args) == -1) - return -1; - - if (handlerSet_.size () == 0) { - ACE.ERROR ("No servers are registered."); - done_ = true; - return -1; - } - - if (tq_ == null) - tq_ = new TimerQueue (true); - - tq_.scheduleTimer (this, - "Time Service Processor", - TimeValue.zero, - updateInterval_); - - return 0; - } - - /** - * Called by TSClerkHandler instances when they need to connect - * (or reconnect) to a server. This uses Connector to make the - * connection. - * - *@param handler TSClerkHandler to connect to the server - *@param host name of the service - *@param port port to connect to on the server - */ - void connectHandler (TSClerkHandler handler, - String host, - int port) - { - // Don't let handlers reconnect if we are in the process of closing - if (done_) - return; - - ACE.DEBUG ("Connecting handler to " + host + " on port " + port); - try { - - Connector c = new Connector (); - c.open (host, port); - c.connect (handler); - - } catch (UnknownHostException e) { - synchronized (this) { - handlerSet_.removeElement (handler); - } - ACE.ERROR (e); - } catch (SocketException e) { - ACE.ERROR (e); - } catch (InstantiationException e) { - ACE.ERROR (e); - } catch (IllegalAccessException e) { - ACE.ERROR (e); - } catch (IOException e) { - ACE.ERROR (e); - } - } - - /** - * Create a new TSClerkHandler for the given (host name):(port) - * combination. See the class description for more information about - * providing a host names and ports on the command line. - * - *@param hostAndPort String with the host name and port separated by - * a colon. - *@return -1 on failure, 0 on success - */ - protected int newHandler (String hostAndPort) - { - int colon = hostAndPort.lastIndexOf (':'); - - if (colon < 1) { - ACE.ERROR ("Invalid -h <host>:<port> parameter: " + hostAndPort); - return -1; - } - - int port = Integer.parseInt (hostAndPort.substring (colon + 1)); - String host = hostAndPort.substring (0, colon); - - ACE.DEBUG ("New handler for server " + host + " on port " + port); - - TSClerkHandler handler = new TSClerkHandler (this, host, port); - handlerSet_.addElement (handler); - - return 0; - } - - /** - * Have each TSClerkHandler query its time server, average the results, - * and set the timeStatus accordingly. This is called by the - * TimerQueue when appropriate. The interval can be specified on the - * command line. - */ - public synchronized int handleTimeout (TimeValue tv, Object obj) - { - if (done_) - return -1; - - // Increment the sequence number - int sequenceNumber = status_.sequenceNumber () + 1; - Enumeration handlers = handlerSet_.elements (); - - long total = 0; - int count = 0; - - // Use each handler to query its server, collecting the time - // difference information. - while (handlers.hasMoreElements ()) { - TSClerkHandler h = (TSClerkHandler)handlers.nextElement (); - - if (h.sendRequest () < 0) - continue; - - total += h.delta (); - count++; - } - - if (count == 0) { - ACE.ERROR ("Could not reach any time servers, will keep trying."); - return 0; - } - - timeStatus (new TimeInfo (sequenceNumber, total / count)); - - ACE.DEBUG ("Status: " + timeStatus ()); - - return 0; - } - - /** - * Return the current sequence number and time difference pair. - */ - public synchronized TimeInfo timeStatus () - { - return status_; - } - - /** - * Set the current sequence number and time difference pair. - */ - protected synchronized void timeStatus (TimeInfo status) - { - status_ = status; - } - - /** - * Default constructor. Results in this TSClerkProcessor creating - * a new timer queue which runs in its own thread. Thus, this - * TSClerkProcessor runs in its own thread. - */ - public TSClerkProcessor () - { - // Effectively runs in its own thread because of the timer queue - } - - /** - * Constructor allowing the timer queue to be specified. If the timer - * queue isn't already running, the caller is responsible for calling - * handleEvents to start the clerk. Be careful since the querying - * process for the servers may take a while. - * - *@param queue TimerQueue to register with - */ - public TSClerkProcessor (TimerQueue queue) - { - tq_ = queue; - } - - private boolean done_ = false; - - // List of the TSClerkHandlers this uses to maintain its - // server connections. - private Vector handlerSet_ = new Vector (); - private TimerQueue tq_ = null; - - // Default is every five minutes - private TimeValue updateInterval_ = new TimeValue (300, 0); - - TimeInfo status_ = new TimeInfo (); -} diff --git a/java/JACE/netsvcs/Time/TSServerAcceptor.java b/java/JACE/netsvcs/Time/TSServerAcceptor.java deleted file mode 100644 index 7e8b9476c19..00000000000 --- a/java/JACE/netsvcs/Time/TSServerAcceptor.java +++ /dev/null @@ -1,116 +0,0 @@ -package JACE.netsvcs.Time; - -import java.io.*; -import java.net.*; -import java.util.*; -import JACE.OS.*; -import JACE.Misc.*; -import JACE.Connection.*; -import JACE.Reactor.*; -import JACE.ASX.TimeValue; -import JACE.Concurrency.ThreadManager; -import JACE.netsvcs.Server; - -/** - * Server for the time service. Creates TSServerHandlers as necessary - * to handle the requests. - * <P> - * <B>Valid command line arguments:</B> - * <PRE> - * -p (port) Port to listen on for clients"); - * -d Enable debugging messages"); - * -a (class name) Specify ActivateStrategy"); - * (Default is multi-threaded"); - * </PRE> - * - */ -public class TSServerAcceptor extends Server -{ - public TSServerAcceptor () - { - // Set the name in case we're not using the service configurator - name ("Time Service"); - } - - /** - * Simple main program for running the logging service without the - * service configurator. - * - *@param args command line arguments - */ - public static void main (String [] args) - { - // Simple main program to get things rolling - TSServerAcceptor ta = new TSServerAcceptor(); - - ta.init (args); - } - - /** - * Creates a new TSServerHandler instance. - */ - protected SvcHandler makeSvcHandler () - { - return new TSServerHandler (); - } - - /** - * Prints out the valid command line arguments. See the class - * description for more information. Called by Server.init when - * parseArgs returns -1. - */ - protected void printUsage () - { - ACE.ERROR ("Valid options:\n"); - ACE.ERROR ("-p <port> Port to listen on for clients"); - ACE.ERROR ("-d Enable debugging messages"); - ACE.ERROR ("-a <class name> Specify ActivateStrategy"); - ACE.ERROR (" (Default is multi-threaded"); - } - - /** - * Parses the command line arguments. See the class description - * for more information. - * - *@param args command line arguments - *@return -1 on failure, 0 on success - */ - protected int parseArgs (String [] args) - { - int c = 0; - GetOpt opt = new GetOpt(args, "p:da:", true); - - try { - - while ((c = opt.next ()) != -1) { - switch (c) - { - case 'd': - ACE.enableDebugging (); - ACE.DEBUG ("Debugging is enabled"); - break; - case 'p': - if (!port (opt.optarg ())) - return -1; - break; - case 'a': - Object strategy = newStrategyInstance (opt.optarg (), - "ActivateStrategy"); - if (strategy == null) - return -1; - - activateStrategy ((ActivateStrategy) strategy); - break; - default: - ACE.ERROR("Unknown argument: " + (char)c); - return -1; - } - } - } catch (ArrayIndexOutOfBoundsException e) { - ACE.ERROR ("Option -" + (char)c + " requires an argument"); - return -1; - } - - return 0; - } -} diff --git a/java/JACE/netsvcs/Time/TSServerHandler.java b/java/JACE/netsvcs/Time/TSServerHandler.java deleted file mode 100644 index 69bf4239280..00000000000 --- a/java/JACE/netsvcs/Time/TSServerHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -package JACE.netsvcs.Time; - -import java.io.*; -import java.util.*; -import java.net.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.Reactor.*; -import JACE.SOCK_SAP.*; -import JACE.netsvcs.Handler; - -/** - * Created by TSServerAcceptor to handle time update requests. Currently, - * this simply sends back the current time (in seconds). - * - * @see JACE.netsvcs.Logger.ServerLoggingAcceptor - */ -public class TSServerHandler extends Handler -{ - /** - * Reads in the given TimeRequest request and calls dispatch. - * - *@param request TimeRequest instance to use - */ - public void processRequest (Object requestObject) - throws SocketException, EOFException, IOException - { - TimeRequest request = (TimeRequest)requestObject; - - request.streamInFrom (peer ().dataInputStream ()); - - this.dispatch (request); - } - - /** - * Sets the time value of the request to be the local time (in sec) - * and sends it back to the client. - */ - void dispatch(TimeRequest request) throws IOException - { - request.time ((int)(System.currentTimeMillis () / 1000)); - - request.streamOutTo (peer().outputStream ()); - } - - /** - * Creates a new instance of TimeRequest. - */ - public Object newRequest () - { - return new TimeRequest (); - } -} diff --git a/java/JACE/netsvcs/Time/TimeInfo.java b/java/JACE/netsvcs/Time/TimeInfo.java deleted file mode 100644 index 4ebfc793adb..00000000000 --- a/java/JACE/netsvcs/Time/TimeInfo.java +++ /dev/null @@ -1,90 +0,0 @@ -package JACE.netsvcs.Time; - -/** - * Wrapper for use with the clerk, containing a sequence number and - * time offset pair. - */ -public class TimeInfo -{ - /** - * Default constructor. - */ - public TimeInfo () - { - this (0, 0); - } - - /** - * Constructor. - * - *@param seqNum sequence number - *@param delta time offset in seconds - */ - public TimeInfo (int seqNum, long delta) - { - sequenceNumber_ = seqNum; - delta_ = delta; - } - - /** - * Returns this TimeInfo's sequence number. - */ - public int sequenceNumber () - { - return sequenceNumber_; - } - - /** - * Sets this TimeInfo's sequence number. - */ - public void sequenceNumber (int num) - { - sequenceNumber_ = num; - } - - /** - * Returns the time offset represented by this TimeInfo instance. - * (in sec) - */ - public long delta () - { - return delta_; - } - - /** - * Sets the time offset (in sec). - */ - public void delta (long num) - { - delta_ = num; - } - - /** - * Returns an informative String about the time difference represented - * by this TimeInfo instance. The sequence number is included in - * brackets. - * <P> - * Example: - * <PRE> - * Local time is 3 sec slower [57] - * </PRE> - */ - public String toString () - { - String result = "Local time is "; - if (delta_ > 0) { - result += (delta_ + " sec slower"); - } else - if (delta_ < 0) { - result += (delta_ + " sec faster"); - } else - result += "the same as the average"; - - result += " [" + sequenceNumber_ + "]"; - - return result; - } - - private long delta_; - private int sequenceNumber_; -} diff --git a/java/JACE/netsvcs/Time/TimeRequest.java b/java/JACE/netsvcs/Time/TimeRequest.java deleted file mode 100644 index 1b0e691398a..00000000000 --- a/java/JACE/netsvcs/Time/TimeRequest.java +++ /dev/null @@ -1,121 +0,0 @@ -package JACE.netsvcs.Time; - -import java.io.*; -import java.net.*; - -/** - * Request for a time update (and its reply). This is compatible with - * C++ ACE_Time_Request. Currently, the Java version always specifies to - * block forever for requests. - */ -public class TimeRequest -{ - /** - * Type for requesting updates. - */ - public static int TIME_UPDATE = 01; - - /** - * Default constructor, specifies block forever for an update. - */ - public TimeRequest () - { - messageType_ = TIME_UPDATE; - blockForever_ = 1; - } - - /** - * Constructor specifying the type of request, the current - * time, and to block forever. - */ - public TimeRequest (int messageType, - int timeSec) - { - time_ = timeSec; - messageType_ = messageType; - blockForever_ = 1; - } - - /** - * Dump all class information to a String. - */ - public String toString () - { - return "TimeRequest (" + messageType_ + - ", " + blockForever_ + ", " + secTimeout_ + ", " + - usecTimeout_ + ", " + time_ + ")"; - } - - /** - * Read the TimeRequest in from a given InputStream. - */ - public void streamInFrom (InputStream is) - throws IOException, EOFException - { - BufferedInputStream bis = new BufferedInputStream (is, 25); - DataInputStream dis = new DataInputStream (bis); - - streamInFrom (dis); - } - - /** - * Read the TimeRequest in from a given DataInputStream. - */ - public void streamInFrom (DataInputStream dis) - throws IOException, EOFException - { - messageType_ = dis.readInt (); - blockForever_ = dis.readInt (); - secTimeout_ = dis.readInt (); - usecTimeout_ = dis.readInt (); - time_ = dis.readInt (); - } - - /** - * Write this TimeRequest out to a given OutputStream. - */ - public void streamOutTo (OutputStream os) - throws IOException - { - BufferedOutputStream bos = new BufferedOutputStream (os, 25); - DataOutputStream dos = new DataOutputStream (bos); - - streamOutTo (dos); - } - - /** - * Write this TimeRequest out to a given DataOutputStream. - */ - public void streamOutTo (DataOutputStream dos) throws IOException - { - dos.writeInt (messageType_); - dos.writeInt (blockForever_); - dos.writeInt (secTimeout_); - dos.writeInt (usecTimeout_); - dos.writeInt (time_); - - dos.flush (); - } - - /** - * Return the time value in seconds. - */ - public int time () - { - return time_; - } - - /** - * Set the time value in seconds. - */ - public void time (int value) - { - time_ = value; - } - - private int messageType_; - private int blockForever_; - private int secTimeout_; - private int usecTimeout_; - private int time_; -} diff --git a/java/JACE/netsvcs/Time/c.bat b/java/JACE/netsvcs/Time/c.bat deleted file mode 100644 index 5e9e99f5807..00000000000 --- a/java/JACE/netsvcs/Time/c.bat +++ /dev/null @@ -1 +0,0 @@ -javac -d C:\Everett\JACE\classes *.java diff --git a/java/JACE/netsvcs/Time/package.html b/java/JACE/netsvcs/Time/package.html deleted file mode 100644 index 96fff45b643..00000000000 --- a/java/JACE/netsvcs/Time/package.html +++ /dev/null @@ -1,10 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Time Service for synchronizing clocks of collaborating network computers. -<P> -A simple test client is available under the tests directory in netsvcs\Time. - -@see <a href="http://www.cs.wustl.edu/~schmidt/ACE-netsvcs.html">ACE Network Services</a> -</BODY> -</HTML> diff --git a/java/JACE/netsvcs/Time/r.bat b/java/JACE/netsvcs/Time/r.bat deleted file mode 100644 index 7c89fbddd77..00000000000 --- a/java/JACE/netsvcs/Time/r.bat +++ /dev/null @@ -1 +0,0 @@ -java JACE.netsvcs.Time.%1 %2 %3 %4 %5 %6 %7 %8 %9 diff --git a/java/JACE/netsvcs/Token/LockHandler.java b/java/JACE/netsvcs/Token/LockHandler.java deleted file mode 100644 index 8e3612efb42..00000000000 --- a/java/JACE/netsvcs/Token/LockHandler.java +++ /dev/null @@ -1,38 +0,0 @@ -package JACE.netsvcs.Token; - -/** - * Defines a handler for a certain type of lock. This allows new types - * of synchronization mechanisms to be added to the Token service without - * any modification of existing code. Implementing class instances that - * are registered (via the command line or another way) - * with the token service can be created as requests for that type of - * lock come into the service. - * - *@see LockHandlerAdapter - *@see MutexHandler - *@author Everett Anderson - */ -public interface LockHandler -{ - /** - * Process a given TokenRequest and construct the appropriate - * reply. The request has already been read from the connection, - * and the reply will be sent without the LockHandler having to - * worry about the details. - * - *@param caller TokenRequestHandler which is accessing this LockHandler - *@param request request read from the connection - *@return appropriate TokenReply (success, failure, etc) - */ - TokenReply handleRequest(TokenRequestHandler caller, - TokenRequest request); - - /** - * Release any claim the client represented with the given ID - * has on this handler's lock. This is used when a client - * disconnects. - * - *@param clientID ID of the client whose claims to abandon - */ - void abandonLock (String clientID); -} diff --git a/java/JACE/netsvcs/Token/LockHandlerAdapter.java b/java/JACE/netsvcs/Token/LockHandlerAdapter.java deleted file mode 100644 index e240000161c..00000000000 --- a/java/JACE/netsvcs/Token/LockHandlerAdapter.java +++ /dev/null @@ -1,380 +0,0 @@ -package JACE.netsvcs.Token; - -import java.util.*; -import JACE.ASX.*; -import JACE.OS.*; -import JACE.Concurrency.*; - -/** - * LockHandler implementation for any AbstractLock. - * <P> - * Provides the dispatching to appropriate methods on an AbstractLock - * as requests come in. - */ -public class LockHandlerAdapter implements LockHandler -{ - /** - * Constructor taking an AbstractLock to use as the locking - * mechanism the requests work on. - */ - public LockHandlerAdapter (AbstractLock lock) - { - lock_ = lock; - } - - /** - * Default constructor. - */ - public LockHandlerAdapter () - { - lock_ = null; - } - - /** - * Dispatch the request according to its type, calling the - * appropriate methods on the AbstractLock member. - * - *@param caller TokenRequestHandler which called handleRequest (unused) - *@param request request to process - *@return appropriate reply to send to the client - */ - public TokenReply handleRequest (TokenRequestHandler caller, - TokenRequest request) - { - String client = request.clientID (); - String token = request.tokenName (); - TokenReply result = null; - - // Dispatch according to operation type - switch (request.operationType ()) - { - case LockOperations.ACQUIRE: - ACE.DEBUG (client + " begins ACQUIRE for " + token); - result = acquireDispatcher (request); - break; - case LockOperations.RELEASE: - ACE.DEBUG (client + " begins RELEASE for " + token); - result = release (request); - break; - case LockOperations.RENEW: - ACE.DEBUG (client + " begins RENEW for " + token); - result = renew (request); - break; - case LockOperations.REMOVE: - ACE.DEBUG (client + " begins REMOVE for " + token); - result = remove (request); - break; - case LockOperations.TRY_ACQUIRE: - ACE.DEBUG (client + " begins TRY_ACQUIRE for " + token); - result = tryAcquireDispatcher (request); - break; - default: - ACE.ERROR ("Unknown operation: " + request.operationType ()); - break; - } - - ACE.DEBUG (client + " result: " + result); - - return result; - } - - /** - * Create a TimeValue from the given request's timeout information. Note - * that the time in the request is an absolute time timeout. - * - *@param request request to obtain the timeout info from - *@return null if useTimeout is false, otherwise a TimeValue - * representing the appropriate time period - */ - protected TimeValue getTimeout (TokenRequest request) - { - if (request.useTimeout ()) - return new TimeValue (request.sec (), - request.usec () * 1000); - else - return null; - } - - /** - * Call acquireWrite on the lock, returning its return value. - * - *@see AbstractLock#acquireWrite - *@return value from the lock's operation - */ - protected int acquireWrite (TokenRequest request, TimeValue timeout) - throws LockException, TimeoutException, InterruptedException - { - int result; - - if (timeout != null) - result = lock_.acquireWrite (timeout); - else - result = lock_.acquireWrite (); - - return result; - } - - /** - * Call acquireRead on the lock, returning its return value. - * - *@see AbstractLock#acquireRead - *@return value from the lock's operation - */ - protected int acquireRead (TokenRequest request, TimeValue timeout) - throws LockException, TimeoutException, InterruptedException - { - int result; - - if (timeout != null) - result = lock_.acquireRead (timeout); - else - result = lock_.acquireRead (); - - return result; - } - - /** - * Call acquire on the lock, returning its return value. - * - *@see AbstractLock#acquire - *@return value from the lock's operation - */ - protected int acquire (TokenRequest request, TimeValue timeout) - throws LockException, TimeoutException, InterruptedException - { - int result; - - if (timeout != null) - result = lock_.acquire (timeout); - else - result = lock_.acquire (); - - return result; - } - - /** - * Dispatch to the appropriate acquire method. In C++ ACE, when - * the type is LockTypes.RWLOCK and the proxy type is - * LockTypes.WRITE_LOCK_PROXY, then this calls acquireWrite. - * If it's RWLOCK and the proxy is READ_LOCK_PROXY, it calls - * acquireRead. In the normal case, it just calls acquire. - * - *@return reply to be sent back to the client (values for errno - * include constants in TokenReply such as EFAULT, ETIME, - * EINTR, or NO_ERRORS) - */ - protected TokenReply acquireDispatcher (TokenRequest request) - { - int result; - TimeValue timeout = getTimeout (request); - - try { - - /* - ACE specifies that when requesting a reader lock, the - token type will be RWLOCK and the proxy type is 0. - When it's a writer lock, the proxy type is 1. - */ - if (request.tokenType () == LockTypes.RWLOCK) { - if (request.proxyType () == LockTypes.READ_LOCK_PROXY) - result = acquireRead (request, timeout); - else - result = acquireWrite (request, timeout); - } else - result = acquire (request, timeout); - - } catch (LockException e) { - return new TokenReply (TokenReply.EFAULT, - request.arg ()); - } catch (TimeoutException e) { - return new TokenReply (TokenReply.ETIME, - request.arg ()); - } catch (InterruptedException e) { - return new TokenReply (TokenReply.EINTR, - request.arg ()); - } - - if (result == AbstractLock.FAILURE) { - return new TokenReply (TokenReply.EFAULT, - request.arg ()); - } else { - return new TokenReply (TokenReply.NO_ERRORS, - request.arg ()); - } - } - - /** - * Process a release request and construct a reply. The values - * for errno include TokenReply constants EFAULT, EACCES, or - * NO_ERRORS. - */ - protected TokenReply release (TokenRequest request) - { - int result; - - try { - result = lock_.release (); - } catch (LockException e) { - return new TokenReply (TokenReply.EFAULT, - request.arg ()); - } - - if (result == AbstractLock.FAILURE) { - return new TokenReply (TokenReply.EACCES, - request.arg ()); - } else { - return new TokenReply (TokenReply.NO_ERRORS, - request.arg ()); - } - } - - /** - * Process a renew request and construct a reply. The values for - * errno include TokenReply constants EFAULT, ETIME, EINTR, EACCES, - * or NO_ERRORS. - */ - protected TokenReply renew (TokenRequest request) - { - int result = AbstractLock.FAILURE; - TimeValue timeout = getTimeout (request); - - try { - - if (timeout != null) { - result = lock_.renew (request.requeuePosition (), - timeout); - } else { - result = lock_.renew (request.requeuePosition ()); - } - - } catch (LockException e) { - return new TokenReply (TokenReply.EFAULT, - request.arg ()); - } catch (TimeoutException e) { - return new TokenReply (TokenReply.ETIME, - request.arg ()); - } catch (InterruptedException e) { - return new TokenReply (TokenReply.EINTR, - request.arg ()); - } - - if (result == AbstractLock.FAILURE) { - return new TokenReply (TokenReply.EACCES, - request.arg ()); - } else { - return new TokenReply (TokenReply.NO_ERRORS, - request.arg ()); - } - } - - /** - * Process a remove request and construct a reply. This currently - * is not supported in the normal AbstractLock interface, so the - * default implementation returns a reply with errno set to - * TokenReply.ENOTSUP. - */ - protected TokenReply remove (TokenRequest request) - { - ACE.ERROR ("Remove is unimplemented"); - return new TokenReply (TokenReply.ENOTSUP, - request.arg ()); - } - - /** - * Call tryAcquireWrite on the lock, returning the result. - */ - protected int tryAcquireWrite (TokenRequest request) - throws LockException - { - return lock_.tryAcquireWrite (); - } - - /** - * Call tryAcquireRead on the lock, returning the result. - */ - protected int tryAcquireRead (TokenRequest request) - throws LockException - { - return lock_.tryAcquireRead (); - } - - /** - * Call tryAcquire on the lock, returning the result. - */ - protected int tryAcquire (TokenRequest request) throws LockException - { - return lock_.tryAcquire (); - } - - /** - * Dispatch to the appropriate tryAcquire method. In C++ ACE, when - * the type is LockTypes.RWLOCK and the proxy type is - * LockTypes.WRITE_LOCK_PROXY, then this calls acquireWrite. - * If it's RWLOCK and the proxy is READ_LOCK_PROXY, it calls - * acquireRead. In the normal case, it just calls acquire. - * - *@return reply to be sent back to the client (values for errno - * include constants in TokenReply such as EFAULT, - * EWOULDBLOCK, or NO_ERRORS). - */ - protected TokenReply tryAcquireDispatcher (TokenRequest request) - { - int result; - - try { - - /* - ACE specifies that when requesting a reader lock, the - token type will be RWLOCK and the proxy type is 0. - When it's a writer lock, the proxy type is 1. - */ - if (request.tokenType () == LockTypes.RWLOCK) { - if (request.proxyType () == LockTypes.READ_LOCK_PROXY) - result = tryAcquireRead (request); - else - result = tryAcquireWrite (request); - } else - result = tryAcquire (request); - - } catch (LockException e) { - return new TokenReply (TokenReply.EFAULT, - request.arg ()); - } - - if (result == AbstractLock.FAILURE) { - return new TokenReply (TokenReply.EWOULDBLOCK, - request.arg ()); - } else { - return new TokenReply (TokenReply.NO_ERRORS, - request.arg ()); - } - } - - /** - * Abandon any claim the specified client has on the lock. - * - *@param clientID identification of the client - */ - public void abandonLock (String clientID) - { - ACE.DEBUG (clientID + " abandoning lock"); - try { - int nesting_level = 0; - while (lock_.release () != AbstractLock.FAILURE) - { - nesting_level++; - // Loop until not the owner in case the lock - // supports nested acquires - } - if (nesting_level == 0) - ACE.DEBUG (clientID + " was not the owner"); - else - ACE.DEBUG (clientID + " had " + nesting_level + " locks"); - } catch (LockException e) { - ACE.ERROR ("While abandoning lock: " + e.getMessage ()); - // Don't need to send a reply to the client - } - } - - protected AbstractLock lock_; -} diff --git a/java/JACE/netsvcs/Token/LockOperations.java b/java/JACE/netsvcs/Token/LockOperations.java deleted file mode 100644 index f5dfa5bc486..00000000000 --- a/java/JACE/netsvcs/Token/LockOperations.java +++ /dev/null @@ -1,16 +0,0 @@ -package JACE.netsvcs.Token; - -/** - * Constants defining the operation types available on a lock. - * For information on specifying a read/write style lock, see LockTypes. - * - *@see LockTypes - */ -public interface LockOperations -{ - int ACQUIRE = 0; - int RELEASE = 1; - int RENEW = 2; - int REMOVE = 3; - int TRY_ACQUIRE = 4; -} diff --git a/java/JACE/netsvcs/Token/LockTypes.java b/java/JACE/netsvcs/Token/LockTypes.java deleted file mode 100644 index f377529367a..00000000000 --- a/java/JACE/netsvcs/Token/LockTypes.java +++ /dev/null @@ -1,19 +0,0 @@ -package JACE.netsvcs.Token; - -/** - * Constants related to the default lock and proxy types. New types - * of LockHandlers and lock types can be created and registered with - * the token service on the command line without modifying this. - * <P> - * C++ ACE handles RWLOCK in this way: - * When a request comes through for a RWLOCK, the proxy type is - * 0 for a read lock request and 1 for a write lock request. - */ -public interface LockTypes -{ - int MUTEX = 0; - int RWLOCK = 1; - - int READ_LOCK_PROXY = 0; - int WRITE_LOCK_PROXY = 1; -} diff --git a/java/JACE/netsvcs/Token/MutexHandler.java b/java/JACE/netsvcs/Token/MutexHandler.java deleted file mode 100644 index 82f79fe5a76..00000000000 --- a/java/JACE/netsvcs/Token/MutexHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -package JACE.netsvcs.Token; - -import JACE.Concurrency.*; - -/** - * LockHandler implementation for a mutex lock. - * <P> - * Currently, this uses JACE.Concurrency.Token as the actual lock since - * it supports nested acquires. - * - *@see LockHandler - */ -public class MutexHandler extends LockHandlerAdapter -{ - // Uses token since it supports nested acquires. - static class ExtendedMutex extends Token - { - // This is so that we don't make any assumptions about previous - // implementations of LockAdapter, and enable owner checking with - // the client ID from TokenRequest. The thread name is set in - // handleRequest. - protected Object accessorID () - { - return Thread.currentThread().getName(); - } - } - - /** - * Default constructor. - */ - public MutexHandler () - { - super (new ExtendedMutex ()); - } - - public TokenReply handleRequest (TokenRequestHandler caller, - TokenRequest request) - { - Thread.currentThread().setName (request.clientID ()); - - return super.handleRequest (caller, request); - } - - public void abandonLock (String clientID) - { - Thread.currentThread().setName (clientID); - - super.abandonLock (clientID); - } -} - diff --git a/java/JACE/netsvcs/Token/RWMutexHandler.java b/java/JACE/netsvcs/Token/RWMutexHandler.java deleted file mode 100644 index 89dc679dd8d..00000000000 --- a/java/JACE/netsvcs/Token/RWMutexHandler.java +++ /dev/null @@ -1,54 +0,0 @@ -package JACE.netsvcs.Token; - -import JACE.Concurrency.*; - -/** - * LockHandler implementation for a reader/writer mutex lock. - * <P> - * Since it uses RWMutex as the actual lock, it doesn't support - * nested acquires. - * - *@see LockHandler - */ -public class RWMutexHandler extends LockHandlerAdapter -{ - static class ExtendedRWMutex extends RWMutex - { - // This is so that we don't make any assumptions about previous - // implementations of LockAdapter, and enable owner checking with - // the client ID from TokenRequest. The thread name is set in - // handleRequest. - protected Object accessorID () - { - return Thread.currentThread().getName(); - } - } - - /** - * Default constructor. - */ - public RWMutexHandler () - { - super (new ExtendedRWMutex ()); - } - - public TokenReply handleRequest (TokenRequestHandler caller, - TokenRequest request) - { - // Set the name of this thread to the client ID to perform - // proper owner checking. - Thread.currentThread().setName (request.clientID ()); - - // process the request - return super.handleRequest (caller, request); - } - - public void abandonLock (String clientID) - { - // Set the name of this thread to the client ID to perform - // proper owner checking. - Thread.currentThread().setName (clientID); - - super.abandonLock (clientID); - } -} diff --git a/java/JACE/netsvcs/Token/RemoteLock.java b/java/JACE/netsvcs/Token/RemoteLock.java deleted file mode 100644 index 824e05a31f0..00000000000 --- a/java/JACE/netsvcs/Token/RemoteLock.java +++ /dev/null @@ -1,543 +0,0 @@ -package JACE.netsvcs.Token; - -import java.io.*; -import JACE.Concurrency.*; -import JACE.ASX.*; -import JACE.Connection.*; -import JACE.OS.*; - -/** - * Proxy used by clients to connect to the token service. This - * implements the AbstractLock interface, so can be used like any - * other synchronization mechanism. The user can either use this - * class directly, or use a proxy which already inputs its type. - * <P> - * Currently, a separate instance (and thus a separate socket connection) - * must be used for each thread which accesses the service. The token - * service itself could handle multiple client IDs and token names per - * connection with the following requirement -- since the service blocks - * in its operations, a shadow mutex would have to be used in the proxy. - * <P> - * It would be best if the user called the close () method after finishing - * up with a RemoteLock, but that is not absolutely necessary. The socket - * will be closed when the JVM exits or finalize is called. (That will also - * free the actual token in the token service in case release was never - * called.) - * <P> - * The SLEEPHOOK result is never returned, only SUCCESS or FAILURE. (C++ - * version doesn't seem to indicate the sleep hook result.) - * - *@see MutexHandler - *@see RWMutexHandler - *@see JACE.Concurrency.AbstractLock - * - *@author Everett Anderson - */ -public class RemoteLock extends SvcHandler implements AbstractLock -{ - /** - * Accessor for the token name. - * - *@return name of the token - */ - public String tokenName () - { - return request_.tokenName (); - } - - /** - * Set the name of the token. - */ - public void tokenName (String name) - { - request_.tokenName (name); - } - - /** - * Accessor for the client ID. - */ - public String clientID () - { - return request_.clientID (); - } - - /** - * Set the client ID. - */ - public void clientID (String clientID) - { - request_.clientID (clientID); - } - - /** - * Constructor. - * - *@see LockTypes - *@param tokenType type of token to create in the token service - *@param proxyType type of proxy to define this RemoteLock as - *@param tokenName name of the token to connect to in the token service - *@param clientID clientID to use to refer to this client - *@param host host name of the token service - *@param port port to connect to for the token service - */ - public RemoteLock (int tokenType, - int proxyType, - String tokenName, - String clientID, - String host, - int port) - { - host_ = host; - port_ = port; - - // Only allocates one reply and one request - reply_ = new TokenReply (); - - request_ = new TokenRequest (tokenType, - proxyType, - 0, - tokenName, - clientID); - } - - /** - * Reconnect this proxy to the token service. - * - *@exception LockException problem occured in reconnecting - */ - protected void reconnect () throws LockException - { - Connector c = new Connector (); - c.open (host_, port_); - - try { - c.connect (this); - } catch (InstantiationException e) { - throw new LockException (e.getMessage()); - } catch (IllegalAccessException e) { - throw new LockException (e.getMessage()); - } catch (IOException e) { - throw new LockException (e.getMessage()); - } - } - - /** - * Check to see if this RemoteLock is connected. - */ - public boolean connected () - { - return connected_; - } - - /** - * Initialize this RemoteLock. Called by Connector. - */ - public int open (Object obj) - { - connected_ = true; - return 0; - } - - /** - * Shut down the connection to the server. Current implementation - * calls close (). - */ - public int close (long flags) - { - return close (); - } - - /** - * Shut down the connection to the server and mark this lock - * as disconnected. - */ - public int close () - { - if (connected ()) { - try { - connected_ = false; - peer ().close (); - } catch (IOException e) { - return -1; - } - } - - return 0; - } - - /** - * Send the given request to the token service, throwing a - * LockException on error. - */ - protected void sendRequest (TokenRequest request) throws LockException - { - try { - if (!connected ()) - reconnect (); - - request.streamOutTo (peer ().dataOutputStream ()); - - } catch (IOException e) { - close (); - throw new LockException (e.getMessage ()); - } - } - - /** - * Receive a reply from the token service, throwing a LockException - * on error. - */ - protected void receiveReply (TokenReply reply) throws LockException - { - if (!connected ()) - throw new LockException ("Proxy wasn't connected, any replies lost"); - - try { - - reply.streamInFrom (peer ().dataInputStream ()); - - } catch (IOException e) { - close (); - throw new LockException (e.getMessage ()); - } - } - - /** - * For errors that shouldn't generate exceptions, return the - * appropriate result code as defined in AbstractLock. - * - *@return AbstractLock.SUCCESS or AbstractLock.FAILURE - */ - protected int processErrno (TokenReply reply) - { - switch (reply.errno ()) - { - case TokenReply.NO_ERRORS: - return AbstractLock.SUCCESS; - case TokenReply.EIO: - close (); - return AbstractLock.FAILURE; - default: - return AbstractLock.FAILURE; - } - } - - /** - * Make a request to the token service with the given operation - * type and arguments. - * - *@see LockOperations - *@see LockTypes - *@param operationType type of operation to perform - *@param proxyType type of proxy this is - *@param requeuePosition put this owner at this position in the - * waiting queue (only makes sense if the - * operation is renew) - *@return AbstractLock.SUCCESS or AbstractLock.FAILURE - *@exception LockException remote access error occured - */ - protected int makeRequest (int operationType, - int proxyType, - int requeuePosition) - throws LockException - { - request_.operationType (operationType); - request_.proxyType (proxyType); - request_.requeuePosition (requeuePosition); - request_.useTimeout (false); - - sendRequest (request_); - receiveReply (reply_); - - // make sure that if someone does send a magic cookie arg back, - // to keep it going - request_.arg (reply_.arg ()); - - return processErrno (reply_); - } - - /** - * Make a request to the token service with the given arguments - * that must be performed by the given absolute time timeout. - * Currently, the timeout is managed by the remote service. - * - *@see LockOperations - *@see LockTypes - *@param operationType type of operation to perform - *@param proxyType type of proxy this is - *@param requeuePosition put this owner at this position in the - * waiting queue (only makes sense if the - * operation is renew) - *@param timeout absolute time timeout to accomplish the operation by - *@return AbstractLock.SUCCESS or AbstractLock.FAILURE - *@exception LockException remote access error occured - */ - protected int makeRequest (int operationType, - int proxyType, - int requeuePosition, - TimeValue timeout) - throws LockException, TimeoutException - { - request_.operationType (operationType); - request_.proxyType (proxyType); - request_.requeuePosition (requeuePosition); - request_.useTimeout (timeout); - - sendRequest (request_); - receiveReply (reply_); - - request_.arg (reply_.arg ()); - - if (reply_.errno () == TokenReply.ETIME) - throw new TimeoutException (timeout, "Remote Lock"); - - return processErrno (reply_); - } - - /** - * Acquire ownership of the lock, blocking indefinitely if necessary. - * <P> - *@return AbstractLock.FAILURE or AbstractLock.SUCCESS - *@exception LockException a remote error occured - */ - public int acquire () throws LockException - { - return makeRequest (LockOperations.ACQUIRE, 0, 0); - } - - /** - * Acquire ownership of the lock by the given absolute time time-out. - * A value of null for the timeout parameter results in a blocking - * acquire. - * A value of TimeValue.zero throws a TimeoutException if the - * acquire would block. - * <P> - *@param timeout absolute time by which the lock must be acquired - *@return appropriate Lock return value (AbstractLock.FAILURE, - * AbstractLock.SUCCESS or AbstractLock.SLEEPHOOK) - *@exception LockException a remote error occured - *@exception JACE.ASX.TimeoutException thrown when the lock is not - * obtained by the desired time - *@see #tryAcquire - */ - public int acquire (TimeValue timeout) - throws LockException, TimeoutException - { - return makeRequest (LockOperations.ACQUIRE, 0, 0, timeout); - } - - /** - * Acquire a read lock, blocking indefinitely if necessary. - * - *@return AbstractLock.FAILURE or AbstractLock.SUCCESS - *@exception LockException a remote error occured - */ - public int acquireRead () throws LockException - { - return makeRequest (LockOperations.ACQUIRE, - LockTypes.READ_LOCK_PROXY, - 0); - } - - /** - * Acquire a read lock by the given absolute time time-out. - * - *@param timeout absolute time by which the lock must be acquired - *@return appropriate lock return value (AbstractLock.FAILURE, - * AbstractLock.SUCCESS or AbstractLock.SLEEPHOOK) - *@exception LockException a remote error occured - *@exception JACE.ASX.TimeoutException thrown when the lock is not - * obtained by the desired time - *@see #tryAcquireRead - */ - public int acquireRead (TimeValue timeout) - throws LockException, TimeoutException - { - return makeRequest (LockOperations.ACQUIRE, - LockTypes.READ_LOCK_PROXY, - 0, - timeout); - } - - /** - * Acquire a write lock, blocking indefinitely if necessary. - * - *@return AbstractLock.FAILURE or AbstractLock.SUCCESS - *@exception LockException a remote error occured - */ - public int acquireWrite () - throws LockException - { - return makeRequest (LockOperations.ACQUIRE, - LockTypes.WRITE_LOCK_PROXY, - 0); - } - - /** - * Acquire a write lock by the given absolute time time-out. - * - *@param timeout absolute time by which the lock must be acquired - *@return appropriate lock return value (AbstractLock.FAILURE, - * AbstractLock.SUCCESS or AbstractLock.SLEEPHOOK) - *@exception LockException a remote error occured - *@exception JACE.ASX.TimeoutException thrown when the lock is not - * obtained by the desired time - *@see #tryAcquireWrite - */ - public int acquireWrite (TimeValue timeout) - throws LockException, TimeoutException - { - return makeRequest (LockOperations.ACQUIRE, - LockTypes.WRITE_LOCK_PROXY, - 0, - timeout); - } - - - /** - * Give up the lock to some number of waiting threads (if any), then - * reacquire, blocking indefinitely if necessary. - * <P> - * An optimized method that efficiently reacquires the token if no - * other threads are waiting. This is useful for situations where - * you don't want to degrade the quality of service if there are - * other threads waiting to get the token. - * <P> - *@param requeuePosition position in the waiters queue to insert - * this thread. If this value is -1 and there are other - * threads waiting to obtain the token, this thread is queued - * at the end. If this value is greater than -1, then it - * indicates how many entries to skip over before inserting - * our thread into the queue. (For example, if it is 0, - * this thread is put at the front of the queue.) If this - * value is greater than the number of waiters, this thread is - * simply put at the end of the current waiters queue. - *@return AbstractLock.FAILURE or AbstractLock.SUCCESS - *@exception LockException a remote error occured - */ - public int renew (int requeuePosition) - throws LockException - { - return makeRequest (LockOperations.RENEW, - 0, - requeuePosition); - } - - /** - * Give up the lock to some waiting threads (if any), then reacquire - * by the given absolute time time-out. - * <P> - * An optimized method that efficiently reacquires the token if no - * other threads are waiting. This is useful for situations where - * you don't want to degrade the quality of service if there are - * other threads waiting to get the token. - * <P> - * A value of null for the timeout indicates a blocking renew. - * <P> - *@param requeuePosition position in the waiters queue to insert - * this thread. If this value is -1 and there are other - * threads waiting to obtain the token, this thread is queued - * at the end. If this value is greater than -1, then it - * indicates how many entries to skip over before inserting - * our thread into the queue. (For example, if it is 0, - * this thread is put at the front of the queue.) If this - * value is greater than the number of waiters, this thread is - * simply put at the end of the current waiters queue. - * - *@param timeout absolute time by which the lock must be reacquired - * - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - *@exception LockException a remote error occured - *@exception JACE.ASX.TimeoutException thrown when the lock is not - * obtained by the desired time - */ - public int renew (int requeuePosition, TimeValue timeout) - throws LockException, TimeoutException - { - return makeRequest (LockOperations.RENEW, - 0, - requeuePosition, - timeout); - } - - /** - * Try to acquire the lock without blocking. - * <P> - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - *@exception LockException a remote error occured - */ - public int tryAcquire () throws LockException - { - return makeRequest (LockOperations.TRY_ACQUIRE, 0, 0); - } - - /** - * Try to acquire a read lock without blocking. - * <P> - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - *@exception LockException a remote error occured - */ - public int tryAcquireRead () throws LockException - { - return makeRequest (LockOperations.TRY_ACQUIRE, - LockTypes.READ_LOCK_PROXY, - 0); - } - - /** - * Try to acquire a write lock without blocking. - * - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - *@exception LockException a remote error occured - */ - public int tryAcquireWrite () throws LockException - { - return makeRequest (LockOperations.TRY_ACQUIRE, - LockTypes.WRITE_LOCK_PROXY, - 0); - } - - /** - * Release ownership of this lock. - * - *@return appropriate AbstractLock return value - * (AbstractLock.FAILURE or AbstractLock.SUCCESS) - *@exception LockException a remote error occured - */ - public int release () throws LockException - { - return makeRequest (LockOperations.RELEASE, 0, 0); - } - - /** - * Closes the connection to the server (if it is still open). - */ - protected void finalize () throws Throwable - { - close (); - } - - /** - * No-op implementation for the sleep hook (unused). - */ - public void sleepHook () {} - - /** Status of whether this RemoteLock is connected to the server or not */ - protected boolean connected_ = false; - - /** Request object for transmissions to the server */ - protected TokenRequest request_; - - /** Reply object for receiving transmissions from the server */ - protected TokenReply reply_; - - /** Host name of the token service */ - protected String host_; - - /** Port number of the token service */ - protected int port_; -} diff --git a/java/JACE/netsvcs/Token/RemoteMutex.java b/java/JACE/netsvcs/Token/RemoteMutex.java deleted file mode 100644 index 7f2a4311116..00000000000 --- a/java/JACE/netsvcs/Token/RemoteMutex.java +++ /dev/null @@ -1,28 +0,0 @@ -package JACE.netsvcs.Token; - -/** - * Proxy used by clients for accessing a mutex at the token service. - */ -public class RemoteMutex extends RemoteLock -{ - /** - * Constructor. - * - *@param tokenName name of the mutex to access - *@param clientID identification of this client - *@param host host of the token service - *@param port port number of the token service - */ - public RemoteMutex (String tokenName, - String clientID, - String host, - int port) - { - super (LockTypes.MUTEX, - 0, - tokenName, - clientID, - host, - port); - } -} diff --git a/java/JACE/netsvcs/Token/RemoteRWMutex.java b/java/JACE/netsvcs/Token/RemoteRWMutex.java deleted file mode 100644 index cc666bfd70f..00000000000 --- a/java/JACE/netsvcs/Token/RemoteRWMutex.java +++ /dev/null @@ -1,29 +0,0 @@ -package JACE.netsvcs.Token; - -/** - * Proxy used by clients for accessing a reader/writer mutex - * at the token service. - */ -public class RemoteRWMutex extends RemoteLock -{ - /** - * Constructor. - * - *@param tokenName name of the reader/writer lock to access - *@param clientID identification of this client - *@param host host of the token service - *@param port port number of the token service - */ - public RemoteRWMutex (String tokenName, - String clientID, - String host, - int port) - { - super (LockTypes.RWLOCK, - 0, - tokenName, - clientID, - host, - port); - } -} diff --git a/java/JACE/netsvcs/Token/TokenAcceptor.java b/java/JACE/netsvcs/Token/TokenAcceptor.java deleted file mode 100644 index 53adf08753b..00000000000 --- a/java/JACE/netsvcs/Token/TokenAcceptor.java +++ /dev/null @@ -1,353 +0,0 @@ -package JACE.netsvcs.Token; - -import java.io.*; -import java.net.*; -import java.util.*; -import JACE.OS.*; -import JACE.Misc.*; -import JACE.Connection.*; -import JACE.netsvcs.Server; - -/** - * Server for the token service. Launches TokenRequestHandlers as - * connections are made. Currently, the activation strategy must be - * thread per connection since the operations are allowed to block - * during acquires, etc. - * <P> - * Two types of locks are supported by default -- Mutex and RWMutex. - * New lock types can be added from the command line without changing - * any code in the service. To do this, just create a class which - * implements the LockHandler interface. - * <P> - * When a request for a new lock comes in, a LockHandler of the corresponding - * type is created and a mapping is created between the lock name and the - * handler. Later requests reuse that mapping. - * <P> - * <B>Valid command line arguments:</B> - * <PRE> - * -f (class name):(type) Specify a LockHandler for a type of lock"); - * -p (port number) Port to listen on for clients"); - * -d Enable debugging messages"); - * </PRE> - * - *@see JACE.netsvcs.Server - *@see TokenRequestHandler - *@see LockHandler - *@see LockTypes - */ -public class TokenAcceptor extends Server -{ - protected void addDefaultFactories() throws ClassNotFoundException { - addHandlerFactory(LockTypes.MUTEX, - Class.forName("JACE.netsvcs.Token.MutexHandler")); - addHandlerFactory(LockTypes.RWLOCK, - Class.forName("JACE.netsvcs.Token.RWMutexHandler")); - } - - /** - * Default constructor. - */ - public TokenAcceptor() { - - // Set the name in case we aren't using the service configurator. - name ("Token Service"); - - lockHandlerMap_ = new Hashtable(); - handlerFactoryMap_ = new Hashtable(); - clientHandlerMap_ = new Hashtable (); - } - - /** - * Add a map between a type of lock and the factory which - * creates LockHandler instances that handle it. - * - *@see LockTypes - *@param type number representing the type of lock - *@param factory Class object for a LockHandler class - */ - public void addHandlerFactory(Integer type, Class factory) { - handlerFactoryMap_.put(type, factory); - } - - /** - * Add a map between a type of lock and the factory which - * creates LockHandler instances that handle it. - * - *@see LockTypes - *@param type number representing the type of lock - *@param factory Class object for a LockHandler class - */ - public void addHandlerFactory(int type, Class factory) { - addHandlerFactory(new Integer(type), factory); - } - - /** - * Remove the LockHandler factory which handles locks - * of the specified type. - * - *@param type type of LockHandler to cease supporting - *@return the LockHandler instance (or null if not found) - */ - public Object removeHandlerFactory(Integer type) { - return handlerFactoryMap_.remove(type); - } - - /** - * Remove the LockHandler factory which handles locks - * of the specified type. - * - *@param type type of LockHandler to cease supporting - *@return the LockHandler instance (or null if not found) - */ - public Object removeHandlerFactory(int type) { - return handlerFactoryMap_.remove(new Integer(type)); - } - - /** - * Retrieve the LockHandler corresponding to the given name - * or create a new one if it doesn't exist. This is called by - * TokenRequestHandlers. - * - *@param lockName name of the lock to retrieve or create a LockHandler for - *@param lockType type of the lock - *@return LockHandler which handles the lock with that name - */ - public LockHandler getLockHandler (String lockName, - int lockType) { - synchronized (lockHandlerMap_) { - - Object obj = lockHandlerMap_.get(lockName); - - if (obj != null) - return (LockHandler)obj; - else { - LockHandler handler = newHandler (lockType); - lockHandlerMap_.put (lockName, handler); - return handler; - } - } - } - - /** - * Create a new LockHandler of the specified type. - * - *@param type type of LockHandler to create - *@return a new LockHandler instance - */ - protected LockHandler newHandler (int type) { - ACE.DEBUG ("Creating new handler of type " + type); - Object factoryObj = handlerFactoryMap_.get(new Integer(type)); - if (factoryObj == null) - return null; - - Class factory = (Class)factoryObj; - LockHandler handler = null; - - try { - handler = (LockHandler)factory.newInstance(); - } catch (InstantiationException e) { - ACE.ERROR("Can't create a handler of type " + type); - } catch (IllegalAccessException e) { - ACE.ERROR("Handler of type " + type + - " must have a default constructor"); - } - return handler; - } - - /** - * Simple main program. See the class description for more - * information about command line arguments. - */ - public static void main(String args[]) { - TokenAcceptor ta = new TokenAcceptor(); - - ta.init(args); - } - - /** - * Create a new TokenRequestHandler instance. - */ - protected SvcHandler makeSvcHandler() - { - return new TokenRequestHandler(); - } - - /** - * Sets up the default factories so the user can override them on - * the command line, then delegates back to Server.init (String[]). - * - *@see JACE.netsvcs.Server#init - *@param args command line arguments - *@return -1 on failure, 0 on success - */ - public int init(String [] args) { - try { - addDefaultFactories (); - } catch (ClassNotFoundException e) { - ACE.ERROR ("Can't find default factory " + e.getMessage ()); - return -1; - } - - return super.init (args); - } - - /** - * Prints out the valid command line arguments. See the class - * description for more information. Called by Server.init when - * parseArgs returns -1. - */ - protected void printUsage () - { - ACE.ERROR ("Valid options:\n"); - ACE.ERROR ("-f <class name>:<type> Specify a handler for a type of lock"); - ACE.ERROR ("-p <port number> Port to listen on for clients"); - ACE.ERROR ("-d Enable debugging messages"); - } - - /** - * Parses the command line arguments. See the class description - * for more information. - * - *@param args command line arguments - *@return -1 on failure, 0 on success - */ - protected int parseArgs(String [] args) - { - int c = 0; - GetOpt opt = new GetOpt(args, "p:f:d", true); - - try { - - while ((c = opt.next ()) != -1) { - switch (c) - { - case 'd': - ACE.enableDebugging (); - ACE.DEBUG ("Debugging is enabled"); - break; - case 'p': - if (!port (opt.optarg ())) - return -1; - break; - case 'f': - if (newHandlerFactory (opt.optarg ()) < 0) - return -1; - break; - default: - ACE.ERROR("Unknown argument: " + (char)c); - return -1; - } - } - } catch (ArrayIndexOutOfBoundsException e) { - ACE.ERROR ("Option -" + (char)c + " requires an argument"); - return -1; - } - - return 0; - } - - /** - * Load the Class for the specified LockHandler and create a mapping - * from its type to the Class instance. Used to parse the command - * line pair of (class name):(type). - * - *@param nameAndType (class name):(type) pair from the command line - *@return -1 on failure, 0 on success - */ - protected int newHandlerFactory (String nameAndType) - { - int colon = nameAndType.lastIndexOf (':'); - - if (colon < 1) { - ACE.ERROR ("Invalid -f <class name>:<type num> for handler: " + - nameAndType); - return -1; - } - - int type = 0; - try { - type = Integer.parseInt (nameAndType.substring (colon + 1)); - } catch (NumberFormatException e) { - ACE.ERROR ("Invalid token type: " + e.getMessage ()); - return -1; - } - - String name = nameAndType.substring (0, colon); - - Class factory; - try { - factory = Class.forName (name); - } catch (ClassNotFoundException e) { - ACE.ERROR (e.getMessage ()); - return -1; - } - - addHandlerFactory (type, factory); - ACE.DEBUG ("New handler " + name + " with type " + type); - - return 0; - } - - /** - * Create a mapping between a client ID and a LockHandler. This is - * only used by TokenRequestHandlers in order to keep track of which - * locks a client touches. That way, if/when a client disconnects, - * all its locks can be abandoned successfully. - * - *@param clientID client identification (key in the mapping) - *@param handler LockHandler to map to (value in the mapping) - * - */ - void addClientLockHandler (String clientID, - LockHandler handler) - { - Object obj = clientHandlerMap_.get (clientID); - if (obj == null) { - // Probably won't have more than 10 locks per client ID, and the Vector - // should resize automatically even if someone does. - Vector handlerList = new Vector (10); - handlerList.addElement (handler); - clientHandlerMap_.put (clientID, handlerList); - } else { - Vector handlerList = (Vector)obj; - int alreadyThereIndex = handlerList.indexOf (handler); - if (alreadyThereIndex == -1) - handlerList.addElement (handler); - } - } - - /** - * Called by TokenRequestHandlers to remove a specified client ID - * from the client ID to LockHandler mapping. - */ - void removeClient (String clientID) - { - clientHandlerMap_.remove (clientID); - } - - /** - * Called by TokenRequestHandlers to obtain a list of all LockHandlers - * accessed by a particular client. Useful for abandoning the locks. - */ - Enumeration getClientLockHandlers (String clientID) - { - Object obj = clientHandlerMap_.get (clientID); - if (obj == null) - return null; - else - return ((Vector)obj).elements (); - } - - // These should be replaced by weak hash maps when available - - // Map consisting of (token name) to (LockHandler instance) pairs - private Hashtable lockHandlerMap_; - - // Map consisting of (Integer token type) to (Class instance for - // corresponding LockHandler class) - private Hashtable handlerFactoryMap_; - - // Map consisting of (client ID) to (Vector of LockHandler) pairs - private Hashtable clientHandlerMap_; -} - diff --git a/java/JACE/netsvcs/Token/TokenReply.java b/java/JACE/netsvcs/Token/TokenReply.java deleted file mode 100644 index 35f50901610..00000000000 --- a/java/JACE/netsvcs/Token/TokenReply.java +++ /dev/null @@ -1,171 +0,0 @@ -package JACE.netsvcs.Token; - -import java.io.*; -import JACE.ASX.*; -import JACE.OS.*; - -/** - * Reply from a lock operation, and constants involved in it. - * This is compatible with the C++ ACE version. The user probably - * never deals directly with the constant errno values in Java ACE since - * the proxy (RemoteLock) should hide those details. - */ -public class TokenReply -{ - - /** indicates success */ - public static final int NO_ERRORS = 0; - - /** indicates a timeout */ - public static final int ETIME = 62; - - /** indicates the operation was interrupted */ - public static final int EINTR = 4; - - /** deadlock indication errno (JACE currently doesn't implement a - * deadlock detection system, but C++ ACE does and JACE proxies - * act appropriately). - */ - public static final int EDEADLK = 45; - - /** indicates the operation would block, used in tryAcquire */ - public static final int EWOULDBLOCK = 11; - - /** indicates a token name or client ID was too long */ - public static final int ENAMETOOLONG = 78; - - /** indicates an operation type was not supported */ - public static final int ENOTSUP = 48; - - /** indicates that this client was not the owner of the lock, - * so couldn't perform the desired operation */ - public static final int EACCES = 13; - - /** indicates an IO error occured during transmission of the request */ - public static final int EIO = 5; - - /** indicates a generic failure to complete the request */ - public static final int EFAULT = 14; - - /** indicates an operation was requested on an unknown type of token */ - public static final int EINVAL = 22; - - /** constant length of a valid token reply */ - private final static int LENGTH = 12; - - /** error code */ - private int errno_; - - /** argument (unused in JACE) */ - private int arg_; - - /** Dump the state of this TokenReply to a String */ - public String toString () - { - return "TokenReply(" + this.length() + ", " + this.errno_ - + ", " + this.arg_ + ")"; - } - - /** Default constructor (NO_ERRORS) */ - public TokenReply () - { - errno_ = NO_ERRORS; - arg_ = 0; - } - - /** Constructor which takes the error code and argument */ - public TokenReply (int errno, int arg) - { - errno_ = errno; - arg_ = arg; - } - - /** - * Accessor for the length of this TokenReply. - */ - public int length () - { - return LENGTH; - } - - /** Accessor for the error code of this TokenReply. */ - public int errno () - { - return errno_; - } - - /** - * Set the error code of this TokenReply. - */ - public void errno (int value) - { - errno_ = value; - } - - /** - * Accessor of the argument of this TokenReply. (Unused in JACE) - */ - public int arg () - { - return arg_; - } - - /** - * Set the argument of this TokenReply. (Unused in JACE) - */ - public void arg (int value) - { - arg_ = value; - } - - /** - * Read this TokenReply in from the given InputStream. - */ - public void streamInFrom (InputStream is) - throws IOException, EOFException - { - BufferedInputStream bis = new BufferedInputStream (is, LENGTH); - DataInputStream dis = new DataInputStream (bis); - - streamInFrom (dis); - } - - /** - * Read this TokenReply in from the given DataInputStream. - */ - public void streamInFrom (DataInputStream dis) - throws IOException, EOFException - { - int length = dis.readInt (); - if (length != LENGTH) - throw new IOException ("Invalid TokenReply length " + length); - - this.errno_ = dis.readInt (); - this.arg_ = dis.readInt (); - } - - /** - * Write this TokenReply out to the given OutputStream. - */ - public void streamOutTo (OutputStream os) - throws IOException - { - BufferedOutputStream bos = new BufferedOutputStream (os, LENGTH); - DataOutputStream dos = new DataOutputStream (bos); - - streamOutTo (dos); - } - - /** - * Write this TokenReply out to the given DataOutputStream. - */ - public void streamOutTo (DataOutputStream dos) - throws IOException - { - dos.writeInt (LENGTH); - dos.writeInt (this.errno_); - dos.writeInt (this.arg_); - - dos.flush (); - } -} diff --git a/java/JACE/netsvcs/Token/TokenRequest.java b/java/JACE/netsvcs/Token/TokenRequest.java deleted file mode 100644 index eb1113428c5..00000000000 --- a/java/JACE/netsvcs/Token/TokenRequest.java +++ /dev/null @@ -1,426 +0,0 @@ -package JACE.netsvcs.Token; - -import java.io.*; -import JACE.ASX.*; -import JACE.OS.*; - -/** - * Request for an operation on a lock. This is compatible with the - * C++ ACE version. The US-ASCII character encoding is used for - * String to byte conversions (and vice versa). If - * that encoding isn't supported, it attempts to use the default - * encoding (but prints a message). Users probably never need to - * deal with this class directly. The notify field isn't used - * in JACE (or in C++ ACE as far as I can tell). - * - *@author Everett Anderson - */ -public class TokenRequest -{ - /** Maximum length for a token name */ - public final static int MAX_TOKEN_NAME_LEN = 40; - - /** Maximum length for a client ID */ - public final static int MAX_CLIENT_ID_LEN = 276; - - /** Length of the fixed size header */ - protected final static int HEADER_LEN = 40; - - /** Maximum length of any TokenRequest (total) */ - protected final static int MAX_LEN = 359; - - /** - * Dump this TokenRequest's state out to a String. - */ - public String toString() - { - return "TokenRequest(" + this.length() + ", " + - this.tokenType_ + ", " + - this.proxyType_ + ", " + - this.operationType_ + ", " + - this.requeuePosition_ + ", " + - this.notify_ + ", " + - this.useTimeout_ + ", " + - this.sec_ + ", " + - this.usec_ + ", " + - this.arg_ + ", " + - this.tokenName_ + ", " + - this.clientID_ + ")"; - } - - /** Default constructor. */ - public TokenRequest() - { - // Remember that the length is transmitted first - tokenType_ = 0; - proxyType_ = 0; - operationType_ = 0; - requeuePosition_ = 0; - notify_ = 0; - useTimeout_ = 0; - sec_ = 0; - usec_ = 0; - arg_ = 0; - tokenName_ = ""; - clientID_ = ""; - // Transmission is "<10 ints><token name>(null):<clientID>(null)" - - charEncoding_ = "US-ASCII"; - - buffer_ = new byte[MAX_LEN]; - } - - /** - * Create a request which doesn't use timeouts. - * - *@param tokenType type of token (usually a constant in LockTypes) - *@param proxyType type of proxy (usually a constant in LockTypes) - *@param operationType type of operation (usually a constant in - * LockOperations) - *@param tokenName name of the token to operate on - *@param clientID name of the client requesting an operation - * - *@see LockTypes - *@see LockOperations - */ - public TokenRequest(int tokenType, - int proxyType, - int operationType, - String tokenName, - String clientID) - { - this(); - - this.tokenType_ = tokenType; - this.proxyType_ = proxyType; - this.operationType_ = operationType; - this.tokenName_ = tokenName; - this.clientID_ = clientID; - } - - /** - * Create a request which uses the given absolute time timeout. - * - *@param tokenType type of token (usually a constant in LockTypes) - *@param proxyType type of proxy (usually a constant in LockTypes) - *@param operationType type of operation (usually a constant in - * LockOperations) - *@param tokenName name of the token to operate on - *@param clientID name of the client requesting an operation - *@param tv absolute time timeout to process the request by - * - *@see LockTypes - *@see LockOperations - */ - public TokenRequest(int tokenType, - int proxyType, - int operationType, - String tokenName, - String clientID, - TimeValue tv) - { - this(tokenType, - proxyType, - operationType, - tokenName, - clientID); - - this.useTimeout_ = 1; - this.sec_ = (int)tv.sec(); - this.usec_ = tv.nanos() / 1000; - } - - /** - * Return the length of this TokenRequest. - * <P> - * Details: - * <PRE> - * Fixed size header of length HEADER_LEN - * token name - * null - * : - * client ID - * null - * </PRE> - */ - public int length() - { - return (HEADER_LEN + - this.tokenName_.length() + - this.clientID_.length() + 3); - } - - /** Accessor for the token type. */ - public int tokenType() - { - return this.tokenType_; - } - /** Set the token type. */ - public void tokenType(int type) - { - this.tokenType_ = type; - } - /** Accessor for the proxy type. */ - public int proxyType() - { - return this.proxyType_; - } - /** Set the proxy type. */ - public void proxyType(int type) - { - this.proxyType_ = type; - } - /** Accessor for the operation type. */ - public int operationType() - { - return this.operationType_; - } - /** Set the operation type. */ - public void operationType(int type) - { - this.operationType_ = type; - } - /** Accessor for the requeue position. This only makes - * sense for a renew operation. */ - public int requeuePosition() - { - return this.requeuePosition_; - } - /** Set the requeue position. This only makes sense for - * a renew operation. */ - public void requeuePosition(int position) - { - this.requeuePosition_ = position; - } - /** Accessor for the flag to determine if a timeout should be used. */ - public boolean useTimeout() - { - return (this.useTimeout_ == 1 ? true : false); - } - /** Set the flag to enable or disable use of timeouts. - */ - public void useTimeout(boolean useIt) - { - this.useTimeout_ = (useIt == true ? 1 : 0); - } - - /** - * Set the absolute time timeout to the given TimeValue's value, and - * enable the useTimeout flag. - */ - public void useTimeout (TimeValue timeout) - { - this.useTimeout_ = 1; - this.sec_ = (int)timeout.sec (); - this.usec_ = timeout.nanos () / 1000; - } - - /** - * Accessor for the seconds component of the absolute time timeout. - */ - public int sec() - { - return this.sec_; - } - /** Set the seconds component of the timeout. */ - public void sec(int sec) - { - this.sec_ = sec; - } - /** Accessor for the usec component of the timeout. */ - public int usec() - { - return this.usec_; - } - /** Set the usec component of the timeout. */ - public void usec(int usec) - { - this.usec_ = usec; - } - /** Accessor for the arg value. (unused in JACE) */ - public int arg() - { - return this.arg_; - } - /** Set the arg value. (unused in JACE) */ - public void arg(int arg) - { - this.arg_ = arg; - } - - /** Accessor for the name of the token. */ - public String tokenName() - { - return this.tokenName_; - } - - /** Set the name of the token. */ - public void tokenName(String name) - { - this.tokenName_ = name; - } - - /** Accessor for the client identification string. */ - public String clientID() - { - return this.clientID_; - } - - /** Set the client identification string. */ - public void clientID(String ID) - { - this.clientID_ = ID; - } - - /** - * Construct a String from a specific subset of the byte array. - * The string begins at the start index and ends at either the - * end of the buffer or the first byte with value 0 (null). - * Tries to use the specified encoding, but uses the default - * platform encoding if it isn't available. - * - *@param start beginning index in the buffer - *@param bufferLength total length of the buffer - */ - protected String stringFromBuffer(int start, int bufferLength) - { - int end = start; - String result = null; - - while (end < bufferLength && this.buffer_[end] != 0) - end++; - - try { - result = new String(this.buffer_, - start, - end - start, - this.charEncoding_); - } catch (UnsupportedEncodingException e) { - ACE.ERROR(this.charEncoding_ + " is not supported!"); - result = new String (this.buffer_, start, end - start); - } - - return result; - } - - /** - * Read the request in from the given InputStream. - */ - public void streamInFrom(InputStream is) - throws IOException, EOFException - { - BufferedInputStream bis = new BufferedInputStream(is, - MAX_LEN); - DataInputStream dis = new DataInputStream(bis); - - streamInFrom (dis); - } - - /** - * Read the request in from the given DataInputStream. - */ - public void streamInFrom (DataInputStream dis) - throws IOException, EOFException - { - int length = dis.readInt(); - if (length > MAX_LEN || length < HEADER_LEN + 5) - throw new IOException ("Invalid TokenRequest length: " + length); - - this.tokenType_ = dis.readInt(); - this.proxyType_ = dis.readInt(); - this.operationType_ = dis.readInt(); - this.requeuePosition_ = dis.readInt(); - this.notify_ = dis.readInt(); - this.useTimeout_ = dis.readInt(); - this.sec_ = dis.readInt(); - this.usec_ = dis.readInt(); - this.arg_ = dis.readInt(); - - int total = dis.read(this.buffer_, 0, length - HEADER_LEN); - - this.tokenName_ = this.stringFromBuffer(0, total); - - this.clientID_ = this.stringFromBuffer(this.tokenName_.length() + 2, - total); - - if (this.tokenName_.length() > MAX_TOKEN_NAME_LEN || - this.clientID_.length() > MAX_CLIENT_ID_LEN) - throw new IOException("Exceeds maximum token name or client ID"); - } - - /** - * Write the request out to the given OutputStream. - */ - public void streamOutTo (OutputStream os) - throws IOException - { - BufferedOutputStream bos = new BufferedOutputStream(os); - DataOutputStream dos = new DataOutputStream(bos); - - streamOutTo (dos); - } - - /** - * Write the request out to the given DataOutputStream. Tries to use - * the specified encoding to the convert the token name and client ID - * to bytes, but uses the platform default encoding if necessary. - */ - public void streamOutTo (DataOutputStream dos) - throws IOException - { - dos.writeInt(this.length()); - dos.writeInt(this.tokenType_); - dos.writeInt(this.proxyType_); - dos.writeInt(this.operationType_); - dos.writeInt(this.requeuePosition_); - - dos.writeInt(this.notify_); - dos.writeInt(this.useTimeout_); - dos.writeInt(this.sec_); - dos.writeInt(this.usec_); - dos.writeInt(this.arg_); - - StringBuffer data = new StringBuffer(this.tokenName_.length() + - this.clientID_.length() + - 3); - - data.append(this.tokenName_); - data.append('\0'); - data.append(':'); - data.append(this.clientID_); - data.append('\0'); - - byte buf [] = null; - String dataString = data.toString (); - try { - buf = dataString.getBytes (this.charEncoding_); - } catch (UnsupportedEncodingException e) { - ACE.ERROR (charEncoding_ + " is unsupported, trying to use default"); - buf = dataString.getBytes (); - } - - dos.write(buf, 0, buf.length); - dos.flush(); - } - - private int tokenType_; - private int proxyType_; - private int operationType_; - private int requeuePosition_; - private int notify_; - private int useTimeout_; - private int sec_; - private int usec_; - private int arg_; - - private String tokenName_; - private String clientID_; - - private byte buffer_[]; - - /** - * Character encoding to use for converting the token name and - * client ID to/from bytes. - */ - protected String charEncoding_; -} diff --git a/java/JACE/netsvcs/Token/TokenRequestHandler.java b/java/JACE/netsvcs/Token/TokenRequestHandler.java deleted file mode 100644 index cb6d729f3bd..00000000000 --- a/java/JACE/netsvcs/Token/TokenRequestHandler.java +++ /dev/null @@ -1,180 +0,0 @@ -package JACE.netsvcs.Token; - -import java.io.*; -import java.net.SocketException; -import java.util.*; -import JACE.Connection.*; -import JACE.OS.*; -import JACE.netsvcs.Handler; - -/** - * Created by TokenAcceptor to handle token requests. Delegates to - * the appropriate LockHandler. This is fairly robust, and can handle - * multiple clients and locks (meaning requests can come in to this - * handle with varying client IDs and token names and still be processed - * and released appropriately.) Compatible with the C++ ACE token service. - * - *@author Everett Anderson - */ -class TokenRequestHandler extends Handler -{ - /** - * Default constructor. - */ - public TokenRequestHandler() { - this.clients_ = new Vector (10); - } - - /** - * Creates a new TokenRequest instance. - */ - public Object newRequest () - { - return new TokenRequest (); - } - - /** - * Sends an error message to a client with the TokenReply.EIO - * errno before abandoning the connection. This is used when an IO - * error occured while receiving the request. - * - *@param lastRequest request object to get the arg from - */ - protected void sendAbortMessage (TokenRequest lastRequest) - { - TokenReply reply = new TokenReply (TokenReply.EIO, - lastRequest.arg ()); - try { - reply.streamOutTo (this.peer ().dataOutputStream ()); - } catch (Exception e) { - // Doesn't matter if there is an error here, we've abandoned - // the connection. - } - } - - /** - * Safely shuts down this handler, making sure to release any locks - * that were touched by clients from this TokenRequestHandler. - * - *@return -1 on failure, 0 on success - */ - public synchronized int close () - { - // For every client X that has used this handler - // for every LockHandler that X has used - // release the lock until it fails because X isn't the owner - // remove the client entries - // Call Handler.close () - if (!done ()) { - - TokenAcceptor parent = (TokenAcceptor) parent (); - Enumeration clientEnum = clients_.elements (); - - while (clientEnum.hasMoreElements ()) { - String clientID = (String)clientEnum.nextElement (); - - Enumeration handlers = parent.getClientLockHandlers (clientID); - if (handlers == null) - continue; - - int num = 0; - - while (handlers.hasMoreElements ()) { - LockHandler handler = (LockHandler)handlers.nextElement (); - - handler.abandonLock (clientID); - - num++; - } - - parent.removeClient (clientID); - } - - return super.close (); - } - - return 0; - } - - /** - * Read in the given TokenRequest and delegates to the appropriate - * LockHandler. - * - *@see JACE.netsvcs.Handler - *@param requestObject TokenRequest object to use - */ - public void processRequest (Object requestObject) - throws SocketException, EOFException, IOException - { - TokenRequest request = (TokenRequest)requestObject; - TokenAcceptor parent = (TokenAcceptor) parent (); - - try { - request.streamInFrom (this.peer ().dataInputStream ()); - - if (!request.tokenName ().equals (lastTokenName_)) { - // Switched tokens: - // - // Either find a handler that's already been made (which would - // mean this token has been accessed before), or create a new - // one with a new token - handler_ = parent.getLockHandler(request.tokenName(), - request.tokenType()); - - if (handler_ == null) { - // The client asked for an operation on a type of token - // that we don't know about. - ACE.ERROR ("Unknown lock type: " + request.tokenType ()); - TokenReply error = new TokenReply (TokenReply.EINVAL, - request.arg ()); - error.streamOutTo(this.peer ().dataOutputStream ()); - return; - } - - // Add this LockHandler to the list of those accessed by - // this clientID - parent.addClientLockHandler (request.clientID (), - handler_); - } - - if (!request.clientID ().equals (lastClientID_)) { - // Switched clients - - if (!clients_.contains (request.clientID ())) - clients_.addElement (request.clientID ()); - - parent.addClientLockHandler (request.clientID (), - handler_); - } - - lastClientID_ = request.clientID (); - lastTokenName_ = request.tokenName (); - - TokenReply reply = handler_.handleRequest(this, request); - - reply.streamOutTo(this.peer ().dataOutputStream ()); - - } catch (NullPointerException e) { - sendAbortMessage (request); - throw e; - } catch (IOException e) { - sendAbortMessage (request); - throw e; - } - } - - // List of clientIDs that have been processed by this instance - // of TokenRequestHandler. This is useful when abandoning the - // locks of any clients that have been using this socket. - private Vector clients_; - - // Name of the last token accessed - private String lastTokenName_ = null; - - // Last client ID which accessed a token from this handler - private String lastClientID_ = null; - - // Current LockHandler - private LockHandler handler_ = null; -} - diff --git a/java/JACE/netsvcs/Token/package.html b/java/JACE/netsvcs/Token/package.html deleted file mode 100644 index 80777aecc0a..00000000000 --- a/java/JACE/netsvcs/Token/package.html +++ /dev/null @@ -1,16 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Token Service for remote mutexes and reader/writer locks. -<P> -New types of lock can be easily added on the command line to the service -without changing existing code by implementing a LockHandler for the new -type. -<P> -A simple test client is available in the tests directory under -netsvcs\Token. - -@see JACE.netsvcs.Token.LockHandler -@see <a href="http://www.cs.wustl.edu/~schmidt/ACE-netsvcs.html">ACE Network Services</a> -</BODY> -</HTML> diff --git a/java/JACE/netsvcs/package.html b/java/JACE/netsvcs/package.html deleted file mode 100644 index a806080aece..00000000000 --- a/java/JACE/netsvcs/package.html +++ /dev/null @@ -1,11 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Bases classes for the network services and two activation strategies. -<P> -Services can be loaded and managed via the Service Configurator. - -@see JACE.ServiceConfigurator -@see <a href="http://www.cs.wustl.edu/~schmidt/ACE-netsvcs.html">ACE Network Services</a> -</BODY> -</HTML> diff --git a/java/JACE/overview.html b/java/JACE/overview.html deleted file mode 100644 index a0c2fdabd73..00000000000 --- a/java/JACE/overview.html +++ /dev/null @@ -1,84 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> -Java ACE is a collection of Java packages containing classes that have been -converted from the C++ version of the -<A HREF="http://www.cs.wustl.edu/~schmidt/ACE.html">ADAPTIVE Communication -Environment</A> (ACE). -<P> -The C++ version of ACE is a large object-oriented network programming toolkit -which contains over 125,000 lines of C++ code and uses advanced C++ features -like templates. -</P> -<P>The goal of converting ACE from C++ to Java is to provide a portable -programming toolkit with a similar interface and functionality to the original - version of ACE. This allows new and current users of C++ ACE an easy transition -to Java and also adds significant value to programming concurrent Java -networking applications. Note that applications written using Java ACE can -communicate seamlessly over sockets with applications written using C++ ACE. -</P> -<P> -The following diagram illustrates the architecture of the Java version of ACE: -</P> - -<P ALIGN="CENTER"> -<IMG SRC="images/java-ace.gif" WIDTH="735" HEIGHT="339" ALIGN="BOTTOM" BORDER="0"> -</P> - -<P> -The Java ACE architecture has fewer components than the diagram illustrating -the architecture for the -<A HREF="http://www.cs.wustl.edu/~schmidt/ACE-overview.html">C++ version -of ACE </A>. This reduction in size occurs for two reasons. First, the Java -Virtual Machine (JVM) handles many of the portability issues provided by C++ -ACE. Therefore, the OS adaptation layer is unnecessary. Second, -Java doesn't support certain OS features provided by Win32, UNIX, and other -OS platforms that C++ ACE is ported to. For example, Java doesn't support -shared memory and memory-mapped files and therefore the memory management -wrappers (such as <CODE>Mem_Map</CODE> and <CODE>Shared_Malloc</CODE>) are -omitted from Java ACE. -</P> - -<P> -The process of converting ACE from C++ to Java provided us with an excellent -source of insights on the strengths and weaknesses of using Java for -industrial-strength software system frameworks. We've written a paper -documenting our -<A HREF="http://www.cs.wustl.edu/~schmidt/C++2java.html">experiences</A> -converting the C++ version of ACE to Java. -</P> - -<H3>Copyright Information for Java ACE</H3> - -<P> -Java ACE is copyrighted by -<A HREF="http://www.cs.wustl.edu/~schmidt">Douglas C. Schmidt</A> and his -research group at -<A HREF="http://www.wustl.edu">Washington University</A>. -You are free to do anything you like with the Java ACE source code such -as including it in commercial software, as long as you include this copyright -statement along with code built using Java ACE. -</P> -<P> -You are under no obligation to freely redistribute any of your source -code that is built using Java ACE. Please note, however, that you may -not do anything to the Java ACE code that will prevent it from being -distributed freely (such as copyrighting it yourself). Naturally, I am not -responsible for any problems caused by using Java ACE. -</P> -<P> -My goal is to see Java ACE continue to evolve and become a more -comprehensive, robust, and well-documented Java toolkit that is freely -available to researchers and developers. If you have any -improvements, suggestions, and or comments, I'd like to hear about it. -</P> -<P> -Thanks, -</P> -<P> -Douglas C. Schmidt -<BR> -<A HREF="mailto@schmidt@cs.wustl.edu">schmidt@cs.wustl.edu</A> -</P> -</BODY> -</HTML> diff --git a/java/JACE/package.html b/java/JACE/package.html deleted file mode 100644 index 72d43449ea7..00000000000 --- a/java/JACE/package.html +++ /dev/null @@ -1,32 +0,0 @@ -<!-- $Id$ --> -<HTML> -<BODY> - -<H3>Overview of Java ACE</H3> -<P>Java ACE is a collection of Java packages containing classes that have been converted from the C++ version of -the <A HREF="http://www.cs.wustl.edu/~schmidt/ACE.html">ADAPTIVE Communication Environment</A> (ACE). The C++ version -of ACE is a large object-oriented network programming toolkit which contains over 125,000 lines of C++ code and -uses advanced C++ features like templates.</P> -<P>The goal of converting ACE from C++ to Java is to provide a portable programming toolkit with a similar interface -and functionality to the original version of ACE. This allows new and current users of C++ ACE an easy transition -to Java and also adds significant value to programming concurrent Java networking applications. Note that applications -written using Java ACE can communicate seamlessly over sockets with applications written using C++ ACE.</P> -<P>The following diagram illustrates the architecture of the Java version of ACE:</P> -<CENTER> -<IMG SRC="java-ace.gif" ALIGN="BOTTOM" BORDER="0"></CENTER> -<P> -The Java ACE architecture has fewer components than the diagram illustrating the architecture for the <A HREF="http://www.cs.wustl.edu/~schmidt/ACE-overview.html">C++ -version of ACE </A>. This reduction in size occurs for two reasons. First, the Java Virtual Machine (JVM) handles -many of the portability issues provided by C++ ACE. Therefore, the OS adaptation layer is unnecessary. Second, -Java doesn't support certain OS features provided by Win32, UNIX, and other OS platforms that C++ ACE is ported -to. For example, Java doesn't support shared memory and memory-mapped files and therefore the memory management -wrappers (such as <CODE>Mem_Map</CODE> and <CODE>Shared_Malloc</CODE>) are omitted from Java ACE.</P> - -<P>The process of converting ACE from C++ to Java provided us with an excellent source of insights on the strengths -and weaknesses of using Java for industrial-strength software system frameworks. We've written a paper documenting -our <A HREF="http://www.cs.wustl.edu/~schmidt/C++2java.html">experiences</A> converting the C++ version of ACE -to Java. - -</BODY> -</HTML> - diff --git a/java/JACE/tests/ASX/BufferStreamTest.java b/java/JACE/tests/ASX/BufferStreamTest.java deleted file mode 100644 index a9600da19dc..00000000000 --- a/java/JACE/tests/ASX/BufferStreamTest.java +++ /dev/null @@ -1,189 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.ASX -// -// = FILENAME -// BufferStreamTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.ASX; - -import java.io.*; -import JACE.OS.*; -import JACE.ASX.*; - -/** - * This short program copies stdin to stdout via the use of an ASX - * STREAM. It illustrates an implementation of the classic "bounded - * buffer" program using an ASX STREAM containing two Modules. Each - * Module contains two Tasks. - */ -public class BufferStreamTest -{ - - static class CommonTask extends Task - { - // ACE_Task hooks - public int open (Object obj) - { - if (this.activate (0, 1, false) == -1) - ACE.ERROR ("spawn"); - return 0; - } - - public int close (long exitStatus) - { - ACE.DEBUG (Thread.currentThread () + " thread is exiting with status " + - exitStatus + " in module " + this.name () + "\n"); - return 0; - } - - public int put (MessageBlock mb, TimeValue tv) - { - return 0; - } - - public int handleTimeout (TimeValue tv, Object obj) - { - return 0; - } - } - - // Define the Producer interface. - - static class Producer extends CommonTask - { - // Read data from stdin and pass to consumer. - // The Consumer reads data from the stdin stream, creates a message, - // and then queues the message in the message list, where it is - // removed by the consumer thread. A 0-sized message is enqueued when - // there is no more data to read. The consumer uses this as a flag to - // know when to exit. - - public int svc () - { - // Keep reading stdin, until we reach EOF. - - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - - String msg = null; - try - { - while (true) - { - System.out.print ("Enter input: "); - System.out.flush (); - msg = in.readLine (); - if (msg == null) - { - // Send a shutdown message to the other thread and exit. - if (this.putNext (new MessageBlock (0), null) == -1) - ACE.ERROR ("putNext"); - break; - } - else - { - // Send the message to the other thread. - if (this.putNext (new MessageBlock (msg), null) == -1) - ACE.ERROR ("putNext"); - } - } - } - catch (IOException e) - { - } - return 0; - } - } - - static class Consumer extends CommonTask - // = TITLE - // Define the Consumer interface. - { - // Enqueue the message on the MessageQueue for subsequent - // handling in the svc() method. - public int put (MessageBlock mb, TimeValue tv) - { - try - { - return this.putq (mb, tv); - } - catch (InterruptedException e) - { - } - return 0; - } - - // The consumer dequeues a message from the ACE_Message_Queue, writes - // the message to the stderr stream, and deletes the message. The - // Consumer sends a 0-sized message to inform the consumer to stop - // reading and exit. - - public int svc () - { - MessageBlock mb = null; - - // Keep looping, reading a message out of the queue, until we - // timeout or get a message with a length == 0, which signals us to - // quit. - try - { - while (true) - { - // Wait for upto 4 seconds - mb = this.getq (TimeValue.relativeTimeOfDay (4, 0)); - - if (mb == null) - break; - - int length = mb.length (); - - if (length > 0) - System.out.println ("\n" + mb.base ()); - - if (length == 0) - break; - } - } - catch (InterruptedException e) - { - } - if (mb == null) - { - ACE.ERROR ("timed out waiting for message"); - System.exit (1); - } - return 0; - } - } - - // Spawn off a new thread. - - public static void main (String args[]) - { - ACE.enableDebugging (); - - // Control hierachically-related active objects - Stream stream = new Stream (); - Module pm = new Module ("Consumer", new Consumer (), null, null); - Module cm = new Module ("Producer", new Producer (), null, null); - - // Create Producer and Consumer Modules and push them onto the - // STREAM. All processing is performed in the STREAM. - - if (stream.push (pm) == -1) - { - ACE.ERROR ("push"); - return; - } - else if (stream.push (cm) == -1) - { - ACE.ERROR ("push"); - return; - } - } -} diff --git a/java/JACE/tests/ASX/MessageQueueTest.java b/java/JACE/tests/ASX/MessageQueueTest.java deleted file mode 100644 index 38f098c1bb7..00000000000 --- a/java/JACE/tests/ASX/MessageQueueTest.java +++ /dev/null @@ -1,54 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.ASX -// -// = FILENAME -// MessageQueueTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.ASX; - -import java.io.*; -import JACE.OS.*; -import JACE.ASX.*; - -public class MessageQueueTest -{ - public static void main (String args[]) - { - ACE.enableDebugging (); - - try - { - MessageBlock conMb; - MessageQueue msgQueue = new MessageQueue (); - MessageBlock mb1 = new MessageBlock ("hello"); - MessageBlock mb2 = new MessageBlock ("world"); - mb1.msgPriority (5); - mb2.msgPriority (7); - - // Enqueue in priority order. - if (msgQueue.enqueue (mb1) == -1) - ACE.ERROR ("put_next"); - - if (msgQueue.enqueue (mb2) == -1) - ACE.ERROR ("put_next"); - - // Now try to dequeue - if ((conMb = msgQueue.dequeueHead ()) == null) - ACE.ERROR ("dequeueHead"); - else - ACE.DEBUG ("Consumer: removed item " + conMb.base () - + " of priority " + conMb.msgPriority ()); - } - catch (InterruptedException e) - { - ACE.ERROR (e); - } - } -} - diff --git a/java/JACE/tests/ASX/PriorityBufferTest.java b/java/JACE/tests/ASX/PriorityBufferTest.java deleted file mode 100644 index 37f0370522d..00000000000 --- a/java/JACE/tests/ASX/PriorityBufferTest.java +++ /dev/null @@ -1,118 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.ASX -// -// = FILENAME -// PriorityBufferTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.ASX; - -import java.io.*; -import JACE.OS.*; -import JACE.ASX.*; - -class consumer extends Thread -{ - public void run () - { - MessageBlock mb = null; - long curPriority = 0; - int length = 0; - - try - { - // Keep looping, reading a message out of the queue, until we - // get a message with a length == 0, which signals us to quit. - for (;;) - { - if ((mb = PriorityBufferTest.msgQueue.dequeueHead ()) == null) - break; - - length = mb.length (); - curPriority = mb.msgPriority (); - - if (length > 0) - ACE.DEBUG ("Consumer: removed item \"" + mb.base () + "\" of priority: " + curPriority); - - if (length == 0) - break; - } - } - catch (InterruptedException e) - { - } - } -} - -class producer extends Thread -{ - producer (int delay) - { - this.delay_ = delay; - } - - public void run () - { - try - { - long count = 0; - for (char c = 'a'; c <= 'z'; c++) - { - count++; - // Allocate a new message - MessageBlock mb = new MessageBlock (new Character (c).toString ()); - // Set the priority - mb.msgPriority (count); - - // Enqueue in priority order. - if (PriorityBufferTest.msgQueue.enqueue (mb) == -1) - ACE.ERROR ("put_next"); - else - { - ACE.DEBUG ("Producer: inserted item \"" + mb.base () + "\" of priority: " + count); - if (this.delay_ > 0) - this.sleep (this.delay_); - } - } - - // Now send a 0-sized shutdown message to the other thread - if (PriorityBufferTest.msgQueue.enqueueTail (new MessageBlock (0)) == -1) - ACE.ERROR ("put_next"); - } - catch (InterruptedException e) - { - } - } - - private int delay_; -} - -public class PriorityBufferTest -{ - public static MessageQueue msgQueue = new MessageQueue (); - - public static void main (String args[]) - { - ACE.enableDebugging (); - - int delay = 0; - if (args.length == 1) - { - try - { - delay = Integer.parseInt (args[0]); - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - } - new producer (delay).start (); - new consumer ().start (); - } -} diff --git a/java/JACE/tests/ASX/TaskTest.java b/java/JACE/tests/ASX/TaskTest.java deleted file mode 100644 index 09ebfe22a1f..00000000000 --- a/java/JACE/tests/ASX/TaskTest.java +++ /dev/null @@ -1,95 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.ASX -// -// = FILENAME -// TaskTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.ASX; - -import java.io.*; -import JACE.OS.*; -import JACE.ASX.*; -import JACE.Reactor.*; - -public class TaskTest extends Task -{ - int nThreads_; - int nIterations_; - - public TaskTest (int nThreads, int nIterations) - { - this.nIterations_ = nIterations; - this.nThreads_ = nThreads; - } - - public void beginTest () - { - if (this.activate (0, this.nThreads_, true) == -1) - ACE.ERROR ("activate failed"); - } - - public int open (Object obj) - { - return 0; - } - - public int close (long flags) - { - return 0; - } - - public int put (MessageBlock mb, TimeValue tv) - { - return 0; - } - - public int handleTimeout (TimeValue tv, Object obj) - { - return 0; - } - - public int svc () - { - for (int i = 1; i <= this.nIterations_; i++) - { - ACE.DEBUG (Thread.currentThread ().toString () + - " in iteration " + i); - // Allow other threads to run - Thread.yield (); - } - return 0; - } - - public static void main (String args[]) - { - int nThreads = 1; - int nIterations = 1; - - ACE.enableDebugging (); - - try - { - if (args.length == 2) - { - nThreads = Integer.parseInt (args[0]); - nIterations = Integer.parseInt (args[1]); - } - else if (args.length == 1) - { - nThreads = Integer.parseInt (args[0]); - } - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - TaskTest tt = new TaskTest (nThreads, nIterations); - tt.beginTest (); - } -} diff --git a/java/JACE/tests/ASX/ThreadPoolTest.java b/java/JACE/tests/ASX/ThreadPoolTest.java deleted file mode 100644 index c48b0caf3c2..00000000000 --- a/java/JACE/tests/ASX/ThreadPoolTest.java +++ /dev/null @@ -1,187 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.ASX -// -// = FILENAME -// ThreadPoolTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.ASX; - -import java.io.*; -import JACE.OS.*; -import JACE.ASX.*; -import JACE.Reactor.*; - -public class ThreadPoolTest extends Task -{ - int nThreads_; - int nIterations_; - - public static int MAX_MB_SIZE = 1024; - - public ThreadPoolTest (int nThreads, int nIterations) - { - this.nIterations_ = nIterations; - this.nThreads_ = nThreads; - if (this.activate (0, nThreads, true) == -1) - ACE.ERROR ("activate failed"); - } - - public int handleTimeout (TimeValue tv, Object obj) - { - return 0; - } - - public int open (Object obj) - { - return 0; - } - - public int close (long flags) - { - return 0; - } - - public int put (MessageBlock mb, TimeValue tv) - { - try - { - return this.putq (mb, tv); - } - catch (InterruptedException e) - { - } - return 0; - } - - public int svc () - { - int count = 1; - - // Keep looping, reading a message out of the queue, until we get a - // message with a length == 0, which signals us to quit. - try - { - for (;; count++) - { - MessageBlock mb = this.getq (null); - if (mb == null) - { - ACE.ERROR (Thread.currentThread ().toString () + " in iteration " + count + ", got result -1, exiting"); - break; - } - int length = mb.length (); - - if (length > 0) - ACE.DEBUG (Thread.currentThread ().toString () + - " in iteration " + count + ", length = " + - length + ", text = \"" + mb.base () + "\""); - - if (length == 0) - { - ACE.DEBUG (Thread.currentThread ().toString () + - " in iteration " + count + - ", got NULL message, exiting"); - break; - } - Thread.yield (); - } - } - catch (InterruptedException e) - { - } - return 0; - } - - public static void produce (ThreadPoolTest threadPool, int nIterations) - { - int count = 0; - for (int n = 0;;) - { - // Allocate a new message. - MessageBlock mb = new MessageBlock (new Integer (count).toString ()); - - if (count == nIterations) - n = 1; // Indicate that we need to shut down. - else - count++; - - if (count == 0 || (count % 20 == 0)) - { - try - { - Thread.sleep (1); - } - catch (InterruptedException e) - { - } - } - if (n != 1) - { - ACE.DEBUG ("Producing..."); - // Pass the message to the Thread_Pool. - if (threadPool.put (mb, null) == -1) - ACE.ERROR ("put"); - } - else - { - // Send a shutdown message to the waiting threads and exit. - ACE.DEBUG ("start loop, dump of task"); - - for (int i = threadPool.thrCount (); i > 0; i--) - { - ACE.DEBUG (Thread.currentThread ().toString () + - "EOF, enqueueing NULL block for thread " + i); - - // Enqueue a NULL message to flag each consumer to - // shutdown. - if (threadPool.put (new MessageBlock (0), null) == -1) - ACE.ERROR ("put"); - } - - break; - } - } - } - - public static void main (String args[]) - { - int nThreads = 1; - int nIterations = 100; - - ACE.enableDebugging (); - - try - { - if (args.length == 2) - { - nThreads = Integer.parseInt (args[0]); - nIterations = Integer.parseInt (args[1]); - } - else if (args.length == 1) - { - nThreads = Integer.parseInt (args[0]); - } - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - ACE.DEBUG ("Threads = " + nThreads + " Iterations = " + nIterations); - - // Create the worker tasks. - ThreadPoolTest threadPool = new ThreadPoolTest (nThreads, - nIterations); - - // Create work for the worker tasks to process in their own threads. - produce (threadPool, nIterations); - ACE.DEBUG ("exiting..."); - } -} - - diff --git a/java/JACE/tests/Concurrency/Condition/Consumer.java b/java/JACE/tests/Concurrency/Condition/Consumer.java deleted file mode 100644 index e43a28f00e0..00000000000 --- a/java/JACE/tests/Concurrency/Condition/Consumer.java +++ /dev/null @@ -1,75 +0,0 @@ -//File: Consumer.java -//Seth Widoff 8/8/96 -//This class attempts at random intervals to dequeue random elements -//from a queue. If the queue is empty the thread waits until an element -//has been enqueued and another thread has invoked the notify() method. -package JACE.tests.Concurrency.Condition; - -import java.lang.Math; -import JACE.ASX.TimeValue; -import java.util.Random; - -public class Consumer implements Runnable -{ - //Maximum pause between dequeues (in milliseconds) - private static final int MAX_PAUSE = 1000; - - private SimpleMessageQueue queue_; - private boolean stop_requested_ = false; - private String name_; - private int iterations_; - private TimeValue timeout_; - - public Consumer(String name, - SimpleMessageQueue queue, - int iterations, - TimeValue timeout) - { - name_ = "Consumer " + name; - queue_ = queue; - iterations_ = iterations; - timeout_ = timeout; - } - - public void run() - { - //Set the random number generator seed to the current time in - //milliseconds. - - Random random = new Random(System.currentTimeMillis()); - Integer element; - - for (int i = 0; i < iterations_; ) - { - try - { - TimeValue absTv = TimeValue.relativeTimeOfDay (timeout_); - element = (Integer)queue_.dequeue(absTv); - if (element != null) - { - - System.out.println("Consumer::run() " + name_ + " dequeued " - + element.toString() + - " Queue size: " + queue_.size()); - - Thread.sleep(Math.abs (random.nextLong()) % MAX_PAUSE); - } - else - { - System.out.println ("Null"); - } - i++; - } - catch(Exception excp) - { - System.out.print ("Consumer::run() Exception: "); - System.out.println(excp); - } - } - } - - public void requestStop() - { - stop_requested_ = true; - } -} diff --git a/java/JACE/tests/Concurrency/Condition/JoinableThreadGroup.java b/java/JACE/tests/Concurrency/Condition/JoinableThreadGroup.java deleted file mode 100644 index 908da33f9f9..00000000000 --- a/java/JACE/tests/Concurrency/Condition/JoinableThreadGroup.java +++ /dev/null @@ -1,24 +0,0 @@ -package JACE.tests.Concurrency.Condition; - -public class JoinableThreadGroup extends ThreadGroup -{ - public JoinableThreadGroup(String name) - { - super(name); - } - - public JoinableThreadGroup(ThreadGroup parent, String name) - { - super(parent, name); - } - - public void join() throws InterruptedException - { - Thread list[] = new Thread[activeCount()]; - - enumerate(list, true); - - for (int i = 0; i < list.length; i++) - list[i].join(); - } -} diff --git a/java/JACE/tests/Concurrency/Condition/Producer.java b/java/JACE/tests/Concurrency/Condition/Producer.java deleted file mode 100644 index cda5063ceed..00000000000 --- a/java/JACE/tests/Concurrency/Condition/Producer.java +++ /dev/null @@ -1,70 +0,0 @@ -//File: Producer.java -//Seth Widoff 8/8/96 -//This class attempts at random intervals to enqueue random elements -//into a queue. If the queue is full the thread waits until an element -//has been dequeued and another thread has invoked the notify() method. - -package JACE.tests.Concurrency.Condition; - -import JACE.ASX.TimeValue; -import java.lang.Math; -import java.util.Random; - -public class Producer implements Runnable -{ - //Maximum pause between enqueues (in milliseconds) - private static final int MAX_PAUSE = 1000; - - private SimpleMessageQueue queue_; - private boolean stop_requested_ = false; - private String name_; - private int iterations_; - private TimeValue timeout_; - - public Producer(String name, - SimpleMessageQueue queue, - int iterations, - TimeValue timeout) - { - name_ = "Producer " + name; - queue_ = queue; - iterations_ = iterations; - timeout_ = timeout; - } - - public void run() - { - //Set the random number generator seed to the current time in milliseconds. - Random random = new Random(System.currentTimeMillis()); - int element = 1; - - for (int i = 0; i < iterations_; ) - { - try - { - // element = random.nextInt(); - TimeValue absTv = TimeValue.relativeTimeOfDay (timeout_); - queue_.enqueue((Object)new Integer(element), absTv); - - System.out.println("Producer::run() " + name_ - + " enqueued " + element + - " Queue size: " + queue_.size()); - - Thread.sleep(Math.abs (random.nextLong()) % MAX_PAUSE); - i++; - element++; - } - catch(Exception excp) - { - System.out.print("Producer::run() Exception: "); - System.out.println(excp); - } - } - } - - public void requestStop() - { - stop_requested_ = true; - } -} - diff --git a/java/JACE/tests/Concurrency/Condition/QueueTest.java b/java/JACE/tests/Concurrency/Condition/QueueTest.java deleted file mode 100644 index 7d6560b11a7..00000000000 --- a/java/JACE/tests/Concurrency/Condition/QueueTest.java +++ /dev/null @@ -1,68 +0,0 @@ -//File: QueueTest.java -//Seth Widoff, 8/8/96 -//This class is a test method for the Producer and Consumer classes. -//The main method takes as arguments the number of producers, the -//number of consumers and the number of elements in the queue. It then -//spawn the specified threads and starts them. - -package JACE.tests.Concurrency.Condition; - -import JACE.ASX.TimeValue; - -public class QueueTest -{ - public static void main(String[] args) - { - if (args.length < 5) - { - System.out.println("Usage: java QueueTest <# producers> <# consumers> " + - "<# elements> <#iterations> <#timeout secs> <#timeout nano secs>"); - System.exit(1); - } - - int num_producers = Integer.parseInt(args[0]), - num_consumers = Integer.parseInt(args[1]), - num_elements = Integer.parseInt(args[2]), - num_iterations = Integer.parseInt(args[3]), - num_timeout_secs = Integer.parseInt(args[4]), - num_timeout_nano_secs = Integer.parseInt(args[5]); - - if (num_elements < 1 - || num_consumers < 1 - || num_producers < 1) - { - System.out.println("All the parameters must be larger than zero."); - System.exit(1); - } - - SimpleMessageQueue queue = new SimpleMessageQueue(num_elements); - Consumer[] consumers = new Consumer[num_consumers]; - Producer[] producers = new Producer[num_producers]; - JoinableThreadGroup thread_group = new JoinableThreadGroup("Producer Consumer"); - - for (int i = 0; i < num_producers; i++) - { - producers[i] = new Producer("Number " + (i + 1), - queue, - num_iterations, - new TimeValue (num_timeout_secs, num_timeout_nano_secs)); - new Thread(thread_group, producers[i]).start(); - } - - for (int i = 0; i < num_consumers; i++) - { - consumers[i] = new Consumer("Number " + (i + 1), queue, num_iterations, new TimeValue (num_timeout_secs, num_timeout_nano_secs)); - new Thread(thread_group, consumers[i]).start(); - } - - try - { - thread_group.join(); - } - catch(InterruptedException excp) - { - System.out.println("QueueTest::main"); - System.out.println(excp); - } - } -} diff --git a/java/JACE/tests/Concurrency/Condition/SimpleMessageQueue.java b/java/JACE/tests/Concurrency/Condition/SimpleMessageQueue.java deleted file mode 100644 index f2a465a9025..00000000000 --- a/java/JACE/tests/Concurrency/Condition/SimpleMessageQueue.java +++ /dev/null @@ -1,86 +0,0 @@ -package JACE.tests.Concurrency.Condition; - -import JACE.ASX.TimeoutException; -import JACE.ASX.TimeValue; -import JACE.Concurrency.*; - -public class SimpleMessageQueue -{ - private int num_items_ = 0; - private int head_ = 0, tail_ = 0; - private Object[] queue_; - - private Mutex lock_ = new Mutex (); - private Condition notFull_ = new Condition (lock_); - private Condition notEmpty_ = new Condition (lock_); - - public SimpleMessageQueue(int size) - { - queue_ = new Object[size]; - } - - public void enqueue(Object element, TimeValue timeout) - throws TimeoutException, InterruptedException - { - try - { - lock_.acquire (); - while (this.isFull ()) - notFull_.Wait (timeout); - - if (tail_ == queue_.length) - tail_ = 0; - queue_[tail_] = element; - tail_++; - - num_items_++; - notEmpty_.signal (); - } - finally - { - lock_.release (); - } - } - - public Object dequeue (TimeValue timeout) - throws TimeoutException, InterruptedException - { - Object return_value = null; - - try - { - lock_.acquire (); - while (this.isEmpty ()) - notEmpty_.Wait (timeout); - - return_value = queue_[head_]; - head_++; - if (head_ == queue_.length) - head_ = 0; - - num_items_--; - notFull_.signal (); - } - finally - { - lock_.release (); - } - return return_value; - } - - public boolean isEmpty() - { - return num_items_ == 0; - } - - public boolean isFull() - { - return num_items_ == queue_.length; - } - - public int size() - { - return num_items_; - } -} - diff --git a/java/JACE/tests/Concurrency/IterationTest.java b/java/JACE/tests/Concurrency/IterationTest.java deleted file mode 100644 index 79e083e7f7a..00000000000 --- a/java/JACE/tests/Concurrency/IterationTest.java +++ /dev/null @@ -1,235 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.tests.Concurrency - * - * = FILENAME - * IterationTest.java - * - *@author Prashant Jain - *@author Everett Anderson - * - *************************************************/ -package JACE.tests.Concurrency; - -import java.io.*; -import JACE.OS.*; -import JACE.Concurrency.*; - -/** - * Test which uses an AbstractLock to prevent threads from mangling - * shared data. This currently tests the four local concurrency - * mechanisms -- Token, Mutex, RWMutex, and Semaphore. - */ -public class IterationTest -{ - static class LockReader extends Thread - { - LockReader (int nIterations, AbstractLock lock) - { - this.nIterations_ = nIterations; - this.lock_ = lock; - } - - public void run () - { - for (int i = 1; i <= this.nIterations_; i++) - { - // Acquire the lock (will block until it gets it) - try - { - this.lock_.acquire (); - } - catch (InterruptedException e) - { - ACE.ERROR (e); - } - catch (LockException e) - { - ACE.ERROR (e); - } - - IterationTest.count++; - ACE.DEBUG (Thread.currentThread ().toString () + - " reader acquired lock in iteration " + i + - ", count = " + IterationTest.count); - - try - { - Thread.sleep (1); - } - catch (InterruptedException e) - { - } - // Release the lock - try - { - this.lock_.release (); - } - catch (LockException e) - { - ACE.ERROR (e); - } - try - { - Thread.sleep (1); - } - catch (InterruptedException e) - { - } - - } - } - - int nIterations_; - AbstractLock lock_; - } - - static class LockWriter extends Thread - { - LockWriter (int nIterations, AbstractLock lock) - { - this.nIterations_ = nIterations; - this.lock_ = lock; - } - - public void run () - { - for (int i = 1; i <= this.nIterations_; i++) - { - // Acquire the lock (will block until it gets it) - try - { - this.lock_.acquire (); - } - catch (InterruptedException e) - { - ACE.ERROR (e); - } - catch (LockException e) - { - ACE.ERROR (e); - } - - - IterationTest.count++; - ACE.DEBUG (Thread.currentThread ().toString () + - " writer acquired lock in iteration " + i + - ", count = " + IterationTest.count); - - try - { - Thread.sleep (1); - } - catch (InterruptedException e) - { - } - - // Release the lock - try - { - this.lock_.release (); - } - catch (LockException e) - { - ACE.ERROR (e); - } - - try - { - Thread.sleep (1); - } - catch (InterruptedException e) - { - } - - } - } - - int nIterations_; - AbstractLock lock_; - } - - final static int TOKEN = 0; - final static int MUTEX = 1; - final static int RWMUTEX = 2; - final static int SEMAPHORE = 3; - - /** - * Command line arguments: - * - * (number of readers) (number of writers) (number of iterations) - */ - public static void main (String args[]) throws InterruptedException - { - int nReaders = 1; - int nWriters = 1; - int nIterations = 100; - int i; - - ACE.enableDebugging (); - - try - { - if (args.length == 3) - { - nReaders = Integer.parseInt (args[0]); - nWriters = Integer.parseInt (args[1]); - nIterations = Integer.parseInt (args[2]); - } - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - - AbstractLock lock = null; - Thread threads[] = new Thread [nReaders + nWriters]; - - for (int state = TOKEN; state <= SEMAPHORE; state++) { - - count = 0; - - switch (state) - { - case TOKEN: - ACE.DEBUG ("--------\nTesting Token:"); - lock = new Token (); - break; - case MUTEX: - ACE.DEBUG ("--------\nTesting Mutex:"); - lock = new Mutex (); - break; - case RWMUTEX: - ACE.DEBUG ("--------\nTesting RWMutex:"); - lock = new RWMutex (); - break; - case SEMAPHORE: - ACE.DEBUG ("--------\nTesting Semaphore:"); - lock = new Semaphore (); - break; - } - - int numThreads = 0; - - // Spawn off the readers and writers - for (i = 0; i < nReaders; i++) { - threads[numThreads] = new LockReader (nIterations, lock); - threads[numThreads].start (); - numThreads++; - } - - for (i = 0; i < nWriters; i++) { - threads[numThreads] = new LockWriter (nIterations, lock); - threads[numThreads].start (); - numThreads++; - } - - for (i = 0; i < numThreads; i++) - threads[i].join (); - - } - } - - public static int count; -} diff --git a/java/JACE/tests/Concurrency/RWMutexTest.java b/java/JACE/tests/Concurrency/RWMutexTest.java deleted file mode 100644 index ff2bbc1f396..00000000000 --- a/java/JACE/tests/Concurrency/RWMutexTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.tests.Concurrency - * - * = FILENAME - * RWMutexTest.java - * - *@author Ross Dargahi (rossd@krinfo.com) - * - *************************************************/ -package JACE.tests.Concurrency; - -import JACE.OS.*; -import JACE.Concurrency.*; - -public class RWMutexTest -{ - static class TestThread extends Thread - { - TestThread(String name, - boolean writer, - AbstractLock lock) - { - super (name); - mWriter = writer; - mLock = lock; - } - - public void output (String msg) - { - synchronized (iosynch) { - ACE.DEBUG (msg); - } - } - - public void run() - { - for (int i = 0; i < 10; i++) - { - try - { - if (!mWriter) - { - mLock.acquireRead(); - output (getName() + ": Acquired Read Lock"); - - int sleepTime = 10; - sleep (sleepTime); - - mLock.release (); - output (getName () + ": Released Read Lock"); - } - else - { - mLock.acquireWrite (); - output (getName () + ": Acquired Write Lock"); - - int sleepTime = 10; - sleep (sleepTime); - - mLock.release (); - output (getName () + ": Released Write Lock"); - } - } - catch (InterruptedException ex) - { - ACE.ERROR ("InterruptedException"); - } - catch (LockException ex) - { - ACE.ERROR ("LockException: " + ex.getMessage ()); - } - } - } - - AbstractLock mLock; - boolean mWriter; - - static Object iosynch = new Object (); - } - - /** - * Command line arguments: - * - * Optional class name to use for the tests (must implement the - * AbstractLock interface). Followed by an optional number of - * iterations. - */ - public static void main(String [] args) - throws ClassNotFoundException, - IllegalAccessException, - InstantiationException, - InterruptedException, - NumberFormatException - { - AbstractLock lock; - int iterations = 1; - - ACE.enableDebugging (); - - if (args.length > 0) { - ACE.DEBUG("Using class " + args[0] + " as the Lock"); - - lock = (AbstractLock)(Class.forName (args[0]).newInstance ()); - - if (args.length > 1) - iterations = Integer.parseInt (args[1]); - - } else - lock = new RWMutex (); - - for (int i = 0; i < iterations; i++) { - - ACE.DEBUG("Iteration " + (i + 1)); - - TestThread t1 = new TestThread ("1", false, lock); - TestThread t2 = new TestThread ("2", false, lock); - TestThread t3 = new TestThread ("3", false, lock); - TestThread t4 = new TestThread ("4", true, lock); - TestThread t5 = new TestThread ("5", false, lock); - TestThread t6 = new TestThread ("6", false, lock); - TestThread t7 = new TestThread ("7", false, lock); - TestThread t8 = new TestThread ("8", true, lock); - - t1.start (); - t2.start (); - t3.start (); - t4.start (); - t5.start (); - t6.start (); - t7.start (); - t8.start (); - } - } -} - diff --git a/java/JACE/tests/Concurrency/TimingTest.java b/java/JACE/tests/Concurrency/TimingTest.java deleted file mode 100644 index 783d2e003a2..00000000000 --- a/java/JACE/tests/Concurrency/TimingTest.java +++ /dev/null @@ -1,290 +0,0 @@ -package JACE.tests.Concurrency; - -import JACE.OS.*; -import JACE.ASX.*; -import JACE.Concurrency.*; - -/** - * Performs a test with 5 threads. This should test what happens during - * renews, also testing what happens when timeout exceptions are generated - * during operations. - * - * Sample output: - * - * Thread 1 calling acquire - * Thread 1 got lock - * Thread 1 doing work - * Thread 2 calling acquire - * Thread 1 finished doing work - * Thread 1 calling renew -1 1 - * Thread 2 got lock - * Thread 2 doing work - * Thread 3 calling acquire - * Thread 4 calling acquire - * Thread 5 calling acquire with 1 sec timeout - * Thread 1 timed out in renew - * Thread 1 failed renewing - * Thread 1 calling release - * Thread 1 failed release - * Thread 5 timed out in acquire - * Thread 5 failed acquire - * Thread 5 calling release - * Thread 5 failed release - * Thread 2 finished doing work - * Thread 2 calling renew 1 - * Thread 3 got lock - * Thread 3 doing work - * Thread 3 finished doing work - * Thread 3 calling release - * Thread 3 released - * Thread 2 got the lock back - * Thread 2 calling release - * Thread 2 released - * Thread 4 got lock - * Thread 4 doing work - * Thread 4 finished doing work - * Thread 4 calling release - * Thread 4 released - */ -public class TimingTest -{ - static class Worker extends Thread - { - AbstractLock lock; - String name; - int order; - - public Worker (String name, int order, AbstractLock lock) - { - this.name = name; - this.order = order; - this.lock = lock; - } - - public void run() - { - switch (this.order) - { - case 1: - methodA(); - break; - case 2: - methodB(); - break; - case 3: - methodC(); - break; - case 4: - methodD(); - break; - } - } - - public void methodA() - { - // acquires - // launches a class 2 worker - // works - // renew -1 with a 1 sec timeout (intended to fail) - // release - - try { - if (acquire() == AbstractLock.FAILURE) - return; - - new Worker("Thread 2", 2, lock).start(); - - work(3000); - - renew(-1, 1); - } finally { - release(); - } - } - - public void methodB() - { - // acquire - // launch two new class 3 workers and one class 4 worker - // work - // renew, yielding to one waiter - // release - try { - if (acquire() == AbstractLock.FAILURE) - return; - - new Worker ("Thread 3", 3, lock).start (); - new Worker ("Thread 4", 3, lock).start (); - new Worker ("Thread 5", 4, lock).start (); - - work(3000); - - renew(1); - } finally { - release(); - } - } - - public void methodC() - { - // acquire - // work - // release - - try { - if (acquire() == AbstractLock.FAILURE) - return; - - work(1000); - } finally { - release(); - } - - } - - public void methodD() - { - // acquire with a short timeout - // (shouldn't get past the timeout) - try { - if (acquire (1) == AbstractLock.FAILURE) - return; - - ACE.DEBUG (name + " probably should have timed out in acquire"); - work (1000); - } finally { - release (); - } - } - - public int acquire (int relativeTimeout) - { - int result = AbstractLock.FAILURE; - ACE.DEBUG(name + " calling acquire with " + relativeTimeout + - " sec timeout"); - - try { - result = lock.acquire (TimeValue.relativeTimeOfDay (relativeTimeout, 0)); - } catch (JACE.ASX.TimeoutException e) { - ACE.DEBUG(name + " timed out in acquire"); - } catch (Exception e) { - ACE.DEBUG (name + " got exception: " + e); - } - - if (result != AbstractLock.FAILURE) - ACE.DEBUG(name + " got lock"); - else - ACE.DEBUG(name + " failed acquire"); - - return result; - } - - public int acquire() - { - int result = AbstractLock.FAILURE; - - ACE.DEBUG(name + " calling acquire"); - try { - result = lock.acquire(); - } catch (Exception e) { - ACE.DEBUG(name + " got exception: " + e); - } - if (result != AbstractLock.FAILURE) - ACE.DEBUG(name + " got lock"); - else - ACE.DEBUG(name + " failed acquire"); - - return result; - } - - public void release() - { - ACE.DEBUG(name + " calling release"); - int result = AbstractLock.FAILURE; - try { - result = lock.release(); - } catch (Exception e) { - ACE.DEBUG (name + " got exception: " + e); - } - - if (result != AbstractLock.FAILURE) - ACE.DEBUG(name + " released"); - else - ACE.DEBUG(name + " failed release"); - } - - public void renew(int pos) - { - int result = AbstractLock.FAILURE; - ACE.DEBUG(name + " calling renew " + pos); - try { - result = lock.renew(pos); - } catch (Exception e) { - ACE.DEBUG (name + " got exception: " + e); - } - - if (result != AbstractLock.FAILURE) - ACE.DEBUG(name + " got the lock back"); - else - ACE.DEBUG(name + " failed renewing"); - } - - public void renew(int pos, int relativeTimeout) - { - int result = AbstractLock.FAILURE; - ACE.DEBUG(name + " calling renew " + pos + " " + - relativeTimeout); - try { - result = lock.renew(pos, - TimeValue.relativeTimeOfDay(relativeTimeout, - 0)); - } catch (JACE.ASX.TimeoutException e) { - ACE.DEBUG(name + " timed out in renew"); - } catch (Exception e) { - ACE.DEBUG (name + " got exception: " + e); - } - - if (result != AbstractLock.FAILURE) - ACE.DEBUG(name + " got the lock back"); - else - ACE.DEBUG(name + " failed renewing"); - } - - public void work(int ms) - { - ACE.DEBUG(name + " doing work"); - try { - Thread.sleep(ms); - } catch (InterruptedException e) { - ACE.DEBUG(name + " was interrupted"); - } - ACE.DEBUG(name + " finished doing work"); - } - } - - /** - * Command line: - * - * Optional class name (which implements AbstractLock) to test - */ - public static void main(String args[]) { - AbstractLock lock; - - ACE.enableDebugging (); - - try { - - if (args.length > 0) { - ACE.DEBUG("Using class " + args[0] + " as the Lock"); - - lock = (AbstractLock)(Class.forName (args[0]).newInstance ()); - } else - lock = new Token (); - - new Worker("Thread 1", 1, lock).start(); - - } catch (Exception e) { - ACE.ERROR("Error: " + e); - } - } -} diff --git a/java/JACE/tests/Concurrency/TokenTest.java b/java/JACE/tests/Concurrency/TokenTest.java deleted file mode 100644 index 162170f1996..00000000000 --- a/java/JACE/tests/Concurrency/TokenTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/************************************************* - * - * = PACKAGE - * tests.Concurrency - * - * = FILENAME - * TokenTest.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.tests.Concurrency; - -import java.io.*; -import JACE.OS.*; -import JACE.Concurrency.ThreadManager; -import JACE.Concurrency.*; -import JACE.ASX.TimeValue; - -public class TokenTest implements Runnable -{ - static class MyToken extends Token - { - public void sleepHook () - { - ACE.DEBUG (Thread.currentThread ().getName () + - " blocking, sleepHook called"); - } - } - - public void run () - { - String name = Thread.currentThread().getName(); - try - { - if (this.token_.acquire () != AbstractLock.FAILURE) - ACE.DEBUG (name + " got token"); - else - ACE.DEBUG (name + " couldn't get token"); - - ACE.DEBUG (name + " calling acquire again (test nesting)"); - if (this.token_.acquire() != AbstractLock.FAILURE) - ACE.DEBUG (name + " got token again"); - else - ACE.DEBUG (name + " couldn't get token"); - - Thread.sleep (1000); - - ACE.DEBUG (name + " gives it up for max 2 sec to first waiter"); - this.token_.renew (1, TimeValue.relativeTimeOfDay(2, 0)); - - ACE.DEBUG (name + " releases the token once"); - this.token_.release (); - ACE.DEBUG (name + " calls release again (nesting level was 2)"); - this.token_.release (); - } - catch (InterruptedException e) - { - this.token_.release (); - } - catch (JACE.ASX.TimeoutException e) - { - ACE.DEBUG (name + " timed out"); - } - } - - /** - * Command line: optional number of threads to create (defaults to 2) - */ - public static void main (String args []) - { - ThreadManager tm = new ThreadManager (); - int n = 2; - - ACE.enableDebugging (); - - try - { - if (args.length == 1) - { - n = Integer.parseInt (args[0]); - } - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - - tm.spawnN (n, - new TokenTest (), - false); - } - - private static MyToken token_ = new MyToken (); -} diff --git a/java/JACE/tests/Connection/AcceptorTest.java b/java/JACE/tests/Connection/AcceptorTest.java deleted file mode 100644 index 0e313ba1f43..00000000000 --- a/java/JACE/tests/Connection/AcceptorTest.java +++ /dev/null @@ -1,83 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.Connection -// -// = FILENAME -// AcceptorTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.Connection.*; - -public class AcceptorTest -{ - void print_usage_and_die () - { - System.out.println ("Usage: test_server [<port>]"); - System.exit (0); - } - - public void init (int port) - { - try - { - Acceptor acceptor = - new Acceptor - (Class.forName ("JACE.tests.Connection.ServerHandler")); - acceptor.open (port); - while (true) - { - acceptor.accept (); - } - } - catch (ClassNotFoundException e) - { - ACE.ERROR (e); - } - catch (SocketException e) - { - ACE.ERROR ("Socket Exception: " + e); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR ("Dang!" + e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - } - - public static void main (String [] args) - { - int port = ACE.DEFAULT_SERVER_PORT; - AcceptorTest acceptorTest = new AcceptorTest (); - - ACE.enableDebugging (); - - if (args.length == 1) - { - try - { - port = Integer.parseInt (args[0]); - } - catch (NumberFormatException e) - { - acceptorTest.print_usage_and_die (); - } - } - acceptorTest.init (port); - } -} diff --git a/java/JACE/tests/Connection/ClientHandler.java b/java/JACE/tests/Connection/ClientHandler.java deleted file mode 100644 index d5885a892e9..00000000000 --- a/java/JACE/tests/Connection/ClientHandler.java +++ /dev/null @@ -1,77 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.Connection -// -// = FILENAME -// ClientHandler.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.Connection.*; - -public class ClientHandler extends SvcHandler -{ - public ClientHandler () - { - } - - public int open (Object obj) - { - new Thread (this).start (); - return 0; - } - - public void run () - { - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - - String msg; - StringBuffer ack = new StringBuffer (); - int ack_len; - try - { - while (true) - { - System.out.print ("Enter input: "); - System.out.flush (); - msg = in.readLine (); - if (msg == null) - break; - this.peer ().send (new StringBuffer (msg)); - System.out.println ("Waiting for ack..."); - ack_len = this.peer ().recv (ack); - if (ack_len == 0) - break; - else - System.out.println (ack); - } - } - catch (NullPointerException e) - { - ACE.ERROR ("connection reset by peer"); - } - catch (IOException e) - { - ACE.ERROR (e); - } - finally - { - try - { - this.peer ().close (); - } - catch (IOException e) - { - } - } - - } -} diff --git a/java/JACE/tests/Connection/ConnectorTest.java b/java/JACE/tests/Connection/ConnectorTest.java deleted file mode 100644 index 285e492dcaf..00000000000 --- a/java/JACE/tests/Connection/ConnectorTest.java +++ /dev/null @@ -1,78 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.Connection -// -// = FILENAME -// ConnectorTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.Connection.*; - -public class ConnectorTest -{ - void print_usage_and_die () - { - System.out.println ("Usage: test_Connector <hostname> [<port>]"); - System.exit (0); - } - - public void init (String hostname, int port) - { - try - { - Connector connector = new Connector (); - connector.open (hostname, port); - connector.connect (new ClientHandler ()); - } - catch (UnknownHostException e) - { - ACE.ERROR (e); - } - catch (SocketException e) - { - ACE.ERROR ("Connection refused"); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - } - - public static void main (String [] args) - { - int port = ACE.DEFAULT_SERVER_PORT; - ConnectorTest connectorTest = new ConnectorTest (); - - ACE.enableDebugging (); - - if (args.length == 2) - { - try - { - port = Integer.parseInt (args[1]); - } - catch (NumberFormatException e) - { - connectorTest.print_usage_and_die (); - } - } - connectorTest.init (args[0], port); - } -} diff --git a/java/JACE/tests/Connection/HTTPHelperTest.java b/java/JACE/tests/Connection/HTTPHelperTest.java deleted file mode 100644 index 28967acb8d3..00000000000 --- a/java/JACE/tests/Connection/HTTPHelperTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package JACE.tests.Connection; - -import java.io.*; -import JACE.Connection.*; -import JACE.OS.*; - -public class HTTPHelperTest -{ - public static void main(String args[]) - { - ACE.enableDebugging (); - // This is just a quick test to confirm that the Base 64 - // encoding and decoding work - // (tests the example given in the HTTP 1.1 RFC) - - String secret = "Aladdin:open sesame"; - - String encoded = HTTPHelper.EncodeBase64(secret); - - System.err.println("Encoding string: \"" + secret + '\"'); - - System.err.println("Result: \"" + encoded + '\"'); - - System.err.println("Is this right? " + - (encoded.equals("QWxhZGRpbjpvcGVuIHNlc2FtZQ==") ? - "Yes" : "No")); - - String decoded = HTTPHelper.DecodeBase64 (encoded); - System.err.println("Decoded: \"" + decoded + '\"'); - - System.err.println("Is this right? " + - (decoded.equals (secret) ? "Yes" : "No")); - } -} diff --git a/java/JACE/tests/Connection/ServerHandler.java b/java/JACE/tests/Connection/ServerHandler.java deleted file mode 100644 index 4dec8186427..00000000000 --- a/java/JACE/tests/Connection/ServerHandler.java +++ /dev/null @@ -1,68 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.Connection -// -// = FILENAME -// ServerHandler.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.Connection.*; - -public class ServerHandler extends SvcHandler -{ - public ServerHandler () - { - } - - public int open (Object obj) - { - new Thread (this).start (); - return 0; - } - - public void run () - { - int msg_len; - System.out.println ("Waiting for messages..."); - try - { - while (true) - { - StringBuffer msg = new StringBuffer (); - msg_len = this.peer ().recv (msg); - if (msg_len == 0) - break; - System.out.println ("Received: " + msg); - this.peer ().send (new StringBuffer ("Got it!")); - } - } - catch (NullPointerException e) - { - ACE.ERROR ("connection reset by peer"); - } - catch (IOException e) - { - ACE.ERROR (e); - } - finally - { - try - { - this.peer ().close (); - } - catch (IOException e) - { - } - } - - } -} diff --git a/java/JACE/tests/Makefile b/java/JACE/tests/Makefile deleted file mode 100644 index f6336bd7ebb..00000000000 --- a/java/JACE/tests/Makefile +++ /dev/null @@ -1,115 +0,0 @@ -# Makefile for JACE tests -# $Id$ - -.SUFFIXES: .java .class - -JACE_WRAPPER = ../.. -CLASSDIR = $(JACE_WRAPPER)/classes - -JC = javac -JCOPTS = -d $(CLASSDIR) - -COMPILE.java = $(JC) $(JCOPTS) $(filter %.java,$?) - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: asx concurrency condition connection misc reactor socksap svcconfig netsvcs - -pkg_all = $(pkg_asx) $(pkg_concurrency) $(pkg_condition) $(pkg_connection) \ - $(pkg_misc) $(pkg_reactor) $(pkg_socksap) $(pkg_svcconfig) $(pkg_netsvcs) - -clean: - find ${JACE_WRAPPER}/classes/JACE/tests -name '*.class' -print | xargs ${RM} - -pkg_asx = \ - BufferStreamTest \ - MessageQueueTest \ - PriorityBufferTest \ - TaskTest \ - ThreadPoolTest - -asx: $(addprefix ASX/,$(addsuffix .java,$(pkg_asx))) - $(COMPILE.java) - -pkg_concurrency = \ - IterationTest \ - RWMutexTest \ - TimingTest \ - TokenTest - -concurrency: $(addprefix Concurrency/,$(addsuffix .java,$(pkg_concurrency))) - $(COMPILE.java) - -pkg_condition = \ - Consumer \ - JoinableThreadGroup \ - Producer \ - QueueTest \ - SimpleMessageQueue - -condition: $(addprefix Concurrency/Condition/,$(addsuffix .java,$(pkg_condition))) - $(COMPILE.java) - -pkg_connection = \ - AcceptorTest \ - ClientHandler \ - ConnectorTest \ - HTTPHelperTest \ - ServerHandler - -connection: $(addprefix Connection/,$(addsuffix .java,$(pkg_connection))) - $(COMPILE.java) - -pkg_misc = \ - ParseArgsTest - -misc: $(addprefix Misc/,$(addsuffix .java,$(pkg_misc))) - $(COMPILE.java) - -pkg_reactor = \ - TimeValueTest \ - TimerQueueTest - -reactor: $(addprefix Reactor/,$(addsuffix .java,$(pkg_reactor))) - $(COMPILE.java) - -pkg_socksap = \ - SOCKAcceptorTest \ - SOCKConnectorTest - -socksap: $(addprefix SOCK_SAP/,$(addsuffix .java,$(pkg_socksap))) - $(COMPILE.java) - -pkg_svcconfig = \ - Main - -svcconfig: $(addprefix ServiceConfigurator/,$(addsuffix .java,$(pkg_svcconfig))) - $(COMPILE.java) - -netsvcs: logger_tests naming_tests time_tests token_tests - -pkg_logger_tests = \ - LoggerTest - -logger_tests: $(addprefix netsvcs/Logger/,$(addsuffix .java,$(pkg_logger_tests))) - $(COMPILE.java) - -pkg_naming_tests = \ - ClientTest - -naming_tests: $(addprefix netsvcs/Naming/,$(addsuffix .java,$(pkg_naming_tests))) - $(COMPILE.java) - -pkg_time_tests = \ - TSClient - -time_tests: $(addprefix netsvcs/Time/,$(addsuffix .java,$(pkg_time_tests))) - $(COMPILE.java) - -pkg_token_tests = \ - ProxyClientTest - -token_tests: $(addprefix netsvcs/Token/,$(addsuffix .java,$(pkg_token_tests))) - $(COMPILE.java) - - diff --git a/java/JACE/tests/Misc/ParseArgsTest.java b/java/JACE/tests/Misc/ParseArgsTest.java deleted file mode 100644 index cc27b28d75b..00000000000 --- a/java/JACE/tests/Misc/ParseArgsTest.java +++ /dev/null @@ -1,48 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.Misc -// -// = FILENAME -// ParseArgsTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.Misc; - -import JACE.OS.*; -import JACE.Misc.*; - -public class ParseArgsTest -{ - public static void main (String args[]) - { - ACE.enableDebugging (); - - String s; - GetOpt opt = new GetOpt (args, "p:rs:", true); - for (int c; (c = opt.next ()) != -1; ) - { - System.out.println ("c is " + (char)c); - switch (c) - { - case 'p': - s = opt.optarg (); - ACE.DEBUG ("Option <p> selected with argument " + s); - break; - case 'r': - ACE.DEBUG ("Option <r> selected"); - break; - case 's': - s = opt.optarg (); - ACE.DEBUG ("Option <s> selected with argument " + s); - break; - default: - ACE.DEBUG ("Usage: java tests.Misc.ParseArgsTest [-p arg1] [-r] [-s arg2]"); - break; - } - } - } -} diff --git a/java/JACE/tests/Reactor/TimeValueTest.java b/java/JACE/tests/Reactor/TimeValueTest.java deleted file mode 100644 index 559f6d15176..00000000000 --- a/java/JACE/tests/Reactor/TimeValueTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/************************************************* - * - * = PACKAGE - * ACE.Reactor - * - * = FILENAME - * TimeValueTest.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.tests.Reactor; - -import JACE.OS.*; -import JACE.ASX.*; - -public class TimeValueTest -{ - public void ASSERT (boolean expression, int i) - { - if (!expression) - ACE.ERROR ("ASSERT failed for " + i); - } - - public void runTest () - { - TimeValue tv1 = new TimeValue (); - TimeValue tv2 = new TimeValue (2); - TimeValue tv3 = new TimeValue (100); - TimeValue tv4 = new TimeValue (1, 1000000000); - TimeValue tv5 = new TimeValue (2); - TimeValue tv6 = new TimeValue (1, -1000000000); - - this.ASSERT (tv1.equals (new TimeValue (0)), 1); - this.ASSERT (tv2.lessThan (tv3), 2); - this.ASSERT (tv2.lessThanEqual (tv2), 3); - this.ASSERT (tv2.greaterThanEqual (tv4), 4); - this.ASSERT (tv5.greaterThanEqual (tv6), 5); - this.ASSERT (tv2.equals (new TimeValue (1, 1000000000)), 6); - this.ASSERT (tv5.equals (tv4), 7); - this.ASSERT (tv2.equals (tv4), 8); - this.ASSERT (tv1.notEquals (tv2), 9); - this.ASSERT (tv6.equals (tv1), 10); - } - - public static void main (String [] args) - { - ACE.enableDebugging (); - - new TimeValueTest ().runTest (); - } -} diff --git a/java/JACE/tests/Reactor/TimerQueueTest.java b/java/JACE/tests/Reactor/TimerQueueTest.java deleted file mode 100644 index 93845ccb6ec..00000000000 --- a/java/JACE/tests/Reactor/TimerQueueTest.java +++ /dev/null @@ -1,84 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.Reactor -// -// = FILENAME -// TimerQueueTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.Reactor; - -import JACE.OS.*; -import JACE.ASX.*; -import JACE.Reactor.*; - -public class TimerQueueTest implements EventHandler -{ - public int handleTimeout (TimeValue tv, Object obj) - { - ACE.DEBUG ("handleTimeout: " + tv.toString () + " " + (String) obj); - return 0; - } - - public static void main (String args []) - { - ACE.enableDebugging (); - - TimerQueue tq = new TimerQueue (true); - TimerQueueTest th1 = new TimerQueueTest (); - int n = 5; - - ACE.enableDebugging (); - - try - { - if (args.length == 1) - { - n = Integer.parseInt (args[0]); - } - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - - // Set a periodic timer - int id = tq.scheduleTimer (th1, - "periodic", - new TimeValue (2), - new TimeValue (3)); - - int i; - // Set a bunch of single timers - for (i=1; i <= n; i++) - { - tq.scheduleTimer (th1, - "A-timer-" + new Integer (i), - new TimeValue (i*2)); - } - - TimerQueueTest th2 = new TimerQueueTest (); - for (i=1; i <= n; i++) - { - tq.scheduleTimer (th2, - "B-timer-" + new Integer (i), - new TimeValue (i*3)); - } - // Cancel all timers associated with this handler - tq.cancelTimer (th2); - - try - { - Thread.sleep (30000); - } - catch (InterruptedException e) - { - } - tq.cancelTimer (id); - System.exit (0); - } -} diff --git a/java/JACE/tests/SOCK_SAP/SOCKAcceptorTest.java b/java/JACE/tests/SOCK_SAP/SOCKAcceptorTest.java deleted file mode 100644 index 3251030fe1c..00000000000 --- a/java/JACE/tests/SOCK_SAP/SOCKAcceptorTest.java +++ /dev/null @@ -1,110 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.SOCK_SAP -// -// = FILENAME -// SOCKAcceptorTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.SOCK_SAP; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.SOCK_SAP.*; - -class TestHandler extends Thread -{ - public TestHandler (SOCKStream stream) - { - this.stream_ = stream; - } - - public void run () - { - int msgLen; - System.out.println ("Waiting for messages..."); - try - { - while (true) - { - StringBuffer msg = new StringBuffer (); - msgLen = this.stream_.recv (msg); - if (msgLen == 0) - break; - ACE.DEBUG ("Received: " + msg); - this.stream_.send ("Got it!"); - } - } - catch (NullPointerException e) - { - ACE.ERROR ("connection reset by peer"); - } - catch (IOException e) - { - ACE.ERROR (e); - } - finally - { - try - { - this.stream_.close (); - } - catch (IOException e) - { - } - } - } - SOCKStream stream_; -} - -public class SOCKAcceptorTest -{ - void print_usage_and_die () - { - ACE.DEBUG ("Usage: SOCKAcceptorTest [<port>]"); - System.exit (0); - } - - public void init (int port) - { - try - { - SOCKAcceptor acceptor = new SOCKAcceptor (port); - while (true) - { - SOCKStream stream = new SOCKStream (); - acceptor.accept (stream); - TestHandler handler = new TestHandler (stream); - handler.start (); - } - } - catch (IOException e) - { - } - } - - public static void main (String [] args) - { - ACE.enableDebugging (); - - int port = ACE.DEFAULT_SERVER_PORT; - SOCKAcceptorTest server = new SOCKAcceptorTest (); - if (args.length == 1) - { - try - { - port = Integer.parseInt (args[0]); - } - catch (NumberFormatException e) - { - server.print_usage_and_die (); - } - } - server.init (port); - } -} diff --git a/java/JACE/tests/SOCK_SAP/SOCKConnectorTest.java b/java/JACE/tests/SOCK_SAP/SOCKConnectorTest.java deleted file mode 100644 index e14b63936f5..00000000000 --- a/java/JACE/tests/SOCK_SAP/SOCKConnectorTest.java +++ /dev/null @@ -1,97 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.SOCK_SAP -// -// = FILENAME -// SOCKConnectorTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package JACE.tests.SOCK_SAP; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.SOCK_SAP.*; - -public class SOCKConnectorTest -{ - static void print_usage_and_die () - { - System.out.println ("Usage: SOCKConnectorTest <hostname> [<port>]"); - System.exit (0); - } - - void processRequests (SOCKStream stream) throws IOException - { - // 1.0 JDK DataInputStream in = new DataInputStream (System.in); - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - String msg; - int ack_len; - - while (true) - { - StringBuffer ack = new StringBuffer (); - ACE.DEBUG ("Enter input: "); - ACE.FLUSH (); - msg = in.readLine (); - if (msg == null) - break; - stream.send (msg); - ACE.DEBUG ("Waiting for ack..."); - ack_len = stream.recv (ack); - if (ack_len == 0) - break; - else - ACE.DEBUG (ack.toString ()); - } - } - - public void init (String host, int port) - { - SOCKStream stream = new SOCKStream (); - SOCKConnector connector = new SOCKConnector (); - try - { - connector.connect (stream, - host, - port); - processRequests (stream); - } - catch (IOException e) - { - ACE.ERROR (e); - } - } - - public static void main (String [] args) - { - ACE.enableDebugging (); - - int port = ACE.DEFAULT_SERVER_PORT; - SOCKConnectorTest client = new SOCKConnectorTest (); - - // check arg count - if (args.length == 0 || args.length > 2) - print_usage_and_die(); - - if (args.length == 2) - { - try - { - port = Integer.parseInt (args[1]); - } - catch (NumberFormatException e) - { - client.print_usage_and_die (); - } - } - client.init (args[0], port); - - - } -} - diff --git a/java/JACE/tests/ServiceConfigurator/Main.java b/java/JACE/tests/ServiceConfigurator/Main.java deleted file mode 100644 index 2b57d5ad429..00000000000 --- a/java/JACE/tests/ServiceConfigurator/Main.java +++ /dev/null @@ -1,113 +0,0 @@ -package JACE.tests.ServiceConfigurator; - -import java.io.*; -import java.util.*; -import JACE.OS.*; -import JACE.ServiceConfigurator.*; - -/** - * Runs the service configurator, allowing the user to interact with it. - */ -public class Main -{ - public static void main (String args[]) - throws FileNotFoundException, IOException, ClassNotFoundException, - IllegalAccessException, InstantiationException - { - ACE.enableDebugging (); - - if (ServiceConfig.open (args) < 0) { - System.err.println ("Error opening ServiceConfig"); - return; - } - - processCommands (args); - - // close everything down - ServiceConfig.close (); - } - - public static void report(String s) { - System.out.println(s); - } - - static InputStreamReader stdin = new InputStreamReader (System.in); - - public static void showMenu () - { - report ("\n[C]lose all"); - report ("[S]uspend all"); - report ("[R]esume all"); - report ("[Re[l]oad all"); - report ("List [n]ames"); - - report ("\n[Q]uit"); - System.out.print ("\nOption (CSRLNQ): "); - } - - public static void processCommands (String [] args) - throws FileNotFoundException, IOException, ClassNotFoundException, - IllegalAccessException, InstantiationException - { - int ch = 0; - Enumeration svcs; - - showMenu (); - - do { - - ch = stdin.read (); - - switch (ch) - { - case 'c': - case 'C': - ServiceConfig.close (); - break; - case 's': - case 'S': - svcs = ServiceConfig.serviceNames (); - while (svcs.hasMoreElements ()) - ServiceConfig.suspend ((String)svcs.nextElement ()); - break; - case 'r': - case 'R': - svcs = ServiceConfig.serviceNames (); - while (svcs.hasMoreElements ()) - ServiceConfig.resume ((String)svcs.nextElement ()); - break; - case 'l': - case 'L': - ServiceConfig.close (); - svcs = ServiceConfig.serviceNames (); - while (svcs.hasMoreElements ()) - ServiceConfig.remove ((String)svcs.nextElement ()); - ServiceConfig.open (args); - break; - case 'n': - case 'N': - report ("\nService names:\n"); - svcs = ServiceConfig.services (); - while (svcs.hasMoreElements ()) { - Service sv = (Service)svcs.nextElement (); - report (sv.name () + " : " + sv.info ()); - } - break; - case 'q': - case 'Q': - report ("\nExiting..."); - return; - case -1: - case 10: - case 13: - continue; - default: - break; - } - - showMenu (); - - } while (true); - } - -} diff --git a/java/JACE/tests/ServiceConfigurator/svc.conf b/java/JACE/tests/ServiceConfigurator/svc.conf deleted file mode 100644 index 5c0c331ed94..00000000000 --- a/java/JACE/tests/ServiceConfigurator/svc.conf +++ /dev/null @@ -1,4 +0,0 @@ -load TimeService JACE.netsvcs.Time.TSServerAcceptor ServiceObject "-d -p 30000" -load LogService JACE.netsvcs.Logger.ServerLoggingAcceptor ServiceObject "-d -p 30001" -load NameService JACE.netsvcs.Naming.NameAcceptor ServiceObject "-d -p 30002" -load TokenService JACE.netsvcs.Token.TokenAcceptor ServiceObject "-d -p 30003" diff --git a/java/JACE/tests/netsvcs/Logger/LoggerTest.java b/java/JACE/tests/netsvcs/Logger/LoggerTest.java deleted file mode 100644 index ae835b07753..00000000000 --- a/java/JACE/tests/netsvcs/Logger/LoggerTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/************************************************* - * - * = FILENAME - * LoggerTest.java - * - *@author Everett Anderson - * - *************************************************/ -package JACE.tests.netsvcs.Logger; - -import JACE.SOCK_SAP.*; -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.netsvcs.Logger.*; - -/** - * - * This is a simple test log client very similar to the direct_logging - * client of C++ ACE. The logging service should correctly receive - * messages from both the C++ and Java version. - * - * @see JACE.netsvcs.Logger.ServerLoggingAcceptor - */ -public class LoggerTest { - - /** Command line: <hostname> [<port>] - * - * Creates a "hello world" log message and sends it to the server logging - * service. - */ - public static void main(String args[]) - { - if (args.length != 2) { - System.err.println("Use: LoggerTest <host name> [<port>]"); - System.exit(0); - } - - ACE.enableDebugging (); - - // Set the port - int port = args.length > 1 ? - (new Integer(args[1])).intValue() : ACE.DEFAULT_SERVER_PORT; - - SOCKStream cli_stream = new SOCKStream(); - INETAddr remote_addr; - String host; - - // Try to find the host - try { - - host = args[0]; - - remote_addr = new INETAddr(port, host); - - } catch (UnknownHostException uhe) { - ACE.ERROR("UnknownHostException " + uhe); - return; - } - - System.out.println("Connecting to " + host + " on port " + port); - - SOCKConnector con = new SOCKConnector(); - - try { - - // Connect to the service - con.connect(cli_stream, remote_addr); - - } catch (SocketException se) { - - ACE.ERROR("Socket Exception " + se); - return; - - } catch (IOException ie) { - - ACE.ERROR("IOException " + ie); - return; - } - - - // Send a message with priority 4, the current time, - // and 0 for the process ID. - LogRecord record = new LogRecord(4, - System.currentTimeMillis(), - 0); - - // Set the text of the message - record.msgData("hello world"); - - try { - - // Send it - record.streamOutTo(cli_stream.socket().getOutputStream ()); - - // Close the socket - cli_stream.close(); - - } catch (IOException ie) { - - ACE.ERROR("" + ie); - return; - } - } -}; - - - - - - - - - - diff --git a/java/JACE/tests/netsvcs/Naming/ClientTest.java b/java/JACE/tests/netsvcs/Naming/ClientTest.java deleted file mode 100644 index f6af6f906ea..00000000000 --- a/java/JACE/tests/netsvcs/Naming/ClientTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package JACE.tests.netsvcs.Naming; - -import java.io.*; -import java.net.*; -import java.util.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.SOCK_SAP.*; -import JACE.netsvcs.Naming.*; - -/** - * Simple test program for NameProxy and the naming service. - * - * Command line: (hostname) (port) - */ -public class ClientTest -{ - public static void print_usage_and_die () - { - System.out.println ("Usage: ClientTest <hostname> [<port>]"); - System.exit (0); - } - public static void main (String [] args) - throws UnknownHostException, - SocketException, - InstantiationException, - IllegalAccessException, - IOException - { - ACE.enableDebugging (); - - int port = ACE.DEFAULT_SERVER_PORT; - - if (args.length == 0 || args.length > 2) - print_usage_and_die (); - - if (args.length == 2) { - try - { - port = Integer.parseInt (args[1]); - } - catch (NumberFormatException e) - { - print_usage_and_die (); - } - } - - System.out.println("Trying to open port " + port + " on " + args[0]); - - NameProxy proxy = new NameProxy (); - - Connector c = new Connector (); - c.open (args[0], port); - c.connect (proxy); - - System.out.println("---- Beginning tests ----"); - - try { - - System.out.println("Binding (five, six, seven): " - + proxy.bind("five", "six", "seven")); - System.out.println("Binding (filth, rat, eats): " - + proxy.bind("filth", "rat", "eats")); - - Vector res = proxy.resolve("five"); - - System.out.println("Resolve (five) : " - + (String)res.elementAt(1) + " " - + (String)res.elementAt(2)); - - System.out.println("Binding (fish, words, him): " - + proxy.bind("fish", "words", "him")); - - System.out.println("Unbind (five, six, seven): " - + proxy.unbind("five")); - - res = proxy.resolve("five"); - - System.out.println("Resolve (five) : " - + (String)res.elementAt(1) + " " - + (String)res.elementAt(2)); - - System.out.println("Binding (fiction, us, you): " - + proxy.bind("fiction", "us", "you")); - - System.out.println("\nGetting all records whose names begin with fi:\n"); - Vector res2 = proxy.listNameEntries("fi"); - - Enumeration iter = res2.elements(); - - while (iter.hasMoreElements()) { - Vector res3 = (Vector)(iter.nextElement()); - - System.out.println((String)res3.elementAt(0) - + "\t" + (String)res3.elementAt(1) - + "\t" + (String)res3.elementAt(2)); - } - - } catch (Exception e) { - System.err.println ("" + e); - e.printStackTrace (); - } finally { - proxy.close (); - } - } -} - diff --git a/java/JACE/tests/netsvcs/Time/TSClient.java b/java/JACE/tests/netsvcs/Time/TSClient.java deleted file mode 100644 index 7a8adf93f42..00000000000 --- a/java/JACE/tests/netsvcs/Time/TSClient.java +++ /dev/null @@ -1,37 +0,0 @@ -package JACE.tests.netsvcs.Time; - -import JACE.netsvcs.Time.*; -import JACE.OS.*; -import JACE.Reactor.*; - -public class TSClient -{ - - // Will run until killed since the default is to run the timer - // queue in its own thread. - public static void main (String args[]) - { - ACE.enableDebugging (); - - TSClerkProcessor cp = new TSClerkProcessor (); - - if (cp.init (args) != 0) - return; - - ACE.DEBUG ("***************************"); - ACE.DEBUG ("Press enter to end the test"); - ACE.DEBUG ("***************************"); - - try { - System.in.read(); - - cp.close (); - - } catch (Exception e) { - ACE.ERROR (e); - } - } -} - - - diff --git a/java/JACE/tests/netsvcs/Token/ProxyClientTest.java b/java/JACE/tests/netsvcs/Token/ProxyClientTest.java deleted file mode 100644 index 1b2118b7f9e..00000000000 --- a/java/JACE/tests/netsvcs/Token/ProxyClientTest.java +++ /dev/null @@ -1,200 +0,0 @@ -package JACE.tests.netsvcs.Token; - -import java.net.*; -import java.io.*; -import JACE.ASX.*; -import JACE.OS.*; -import JACE.Misc.*; -import JACE.Concurrency.*; -import JACE.netsvcs.Token.*; - -public class ProxyClientTest -{ - public static void report(String s) { - System.out.println(s); - } - - static InputStreamReader stdin = new InputStreamReader (System.in); - static RemoteLock lock; - static int requeuePosition = -1, timeout = -1; - - public static void showMenu () - { - report ("\n[A]cquire"); - report ("Acquire [w]rite"); - report ("Acquire rea[d]"); - report ("[T]ry Acquire"); - report ("Try acquire wr[i]te"); - report ("Try acquire r[e]ad"); - report ("Re[n]ew"); - report ("[R]elease"); - - report ("\n[Q]uit"); - System.out.print ("\nOption (AWDTIENRQ): "); - } - - public static void processCommands () throws IOException - { - int ch = 0, result = -1; - - showMenu (); - do { - - ch = stdin.read(); - - try { - - switch (ch) - { - case 'a': - case 'A': - if (timeout >= 0) { - TimeValue tv = TimeValue.relativeTimeOfDay (timeout, 0); - result = lock.acquire (tv); - } else - result = lock.acquire (); - break; - case 'w': - case 'W': - if (timeout >= 0) { - TimeValue tv = TimeValue.relativeTimeOfDay (timeout, 0); - result = lock.acquireWrite (tv); - } else - result = lock.acquire (); - break; - case 'd': - case 'D': - if (timeout >= 0) { - TimeValue tv = TimeValue.relativeTimeOfDay (timeout, 0); - result = lock.acquireRead (tv); - } else - result = lock.acquire (); - break; - case 't': - case 'T': - result = lock.tryAcquire (); - break; - case 'i': - case 'I': - result = lock.tryAcquireWrite (); - break; - case 'e': - case 'E': - result = lock.tryAcquireRead (); - break; - case 'r': - case 'R': - result = lock.release (); - break; - case 'n': - case 'N': - if (timeout >= 0) { - TimeValue tv = TimeValue.relativeTimeOfDay (timeout, 0); - result = lock.renew (requeuePosition, tv); - } else - result = lock.renew (requeuePosition); - break; - case 'q': - case 'Q': - continue; - case -1: - case 10: - case 13: - // Ignore line feeds and carriage returns - continue; - default: - report ("Unknown command: " + (char)ch + " (" + ch + ")\n"); - showMenu (); - continue; - } - - report ("\nResult: " + (result == lock.SUCCESS ? "Success" : - "Failure")); - - } catch (TimeoutException e) { - report ("\nRequest timed out"); - /* - } catch (InterruptedException e) { - report ("\nInterrupted while attemping operation"); - */ - } catch (LockException e) { - report ("\nLock failure: " + e.getMessage ()); - } - - showMenu (); - - } while (ch != 'Q' && ch != 'q'); - } - - public static void printUsage () - { - report ("Valid options:\n"); - report ("-h <host name> Specify token server host"); - report ("-p <port number> Port to connect to"); - report ("-t <time in sec> Relative timeout to use"); - report ("-l <lock type> 0 Mutex, 1 RWMutex"); - report ("-c <client ID> Specify ID (default is this machine name)"); - report ("-n <token name> Specify token name"); - report ("-q <requeue pos> Use this requeue position in renew"); - report ("-d Enable debugging"); - } - - public static void main (String args[]) throws IOException - { - GetOpt opt = new GetOpt (args, "h:p:t:l:c:n:q:d", true); - - String host = "localhost", tokenName = "token1"; - int port = ACE.DEFAULT_SERVER_PORT; - int type = LockTypes.MUTEX, c; - String clientID = InetAddress.getLocalHost().getHostName (); - - try { - while ((c = opt.next ()) != -1) { - switch (c) - { - case 'h': - host = opt.optarg (); - break; - case 'p': - port = Integer.parseInt (opt.optarg ()); - break; - case 't': - timeout = Integer.parseInt (opt.optarg ()); - break; - case 'l': - type = Integer.parseInt (opt.optarg ()); - break; - case 'c': - clientID = opt.optarg (); - break; - case 'n': - tokenName = opt.optarg (); - break; - case 'q': - requeuePosition = Integer.parseInt (opt.optarg ()); - break; - case 'd': - ACE.enableDebugging (); - ACE.DEBUG ("Debugging is enabled"); - break; - default: - printUsage (); - return; - } - } - } catch (ArrayIndexOutOfBoundsException e) { - printUsage (); - return; - } - - report ("Using : " + host + " on port " + port); - report ("Token : " + tokenName); - report ("Client ID: " + clientID); - - lock = new RemoteLock (type, 0, tokenName, clientID, host, port); - - processCommands (); - - lock.close (); - } -} diff --git a/java/MSVJProjects.zip b/java/MSVJProjects.zip Binary files differdeleted file mode 100644 index d5d7c95ebe5..00000000000 --- a/java/MSVJProjects.zip +++ /dev/null diff --git a/java/README b/java/README deleted file mode 100644 index 961a0d94c66..00000000000 --- a/java/README +++ /dev/null @@ -1,40 +0,0 @@ -Java ACE Version 1.5 - -JACE is compatible with Java 1.1 and higher. - -Directory information: - -JACE/ All main, network service, and test source files - -classes/ Output directory for all the .class files. This may - need to be added to your classpath. - -doc/ If you generate the javadoc documentation, it will be - placed here. Requires javadoc 1.2 or later. I think - 1.2.2 is the first version that correctly "inherits" - comments. - -Notes on building Java ACE: - -UNIX: - -Use GNU make on the Makefile in the JACE subdirectory. That will -build the main and network service sources. To build the tests, -use the Makefile in the JACE/tests subdirectory. - -Generate the javadoc documentation with the command "make doc" with -the Makefile in the JACE subdirectory. - -Windows: - -Visual J++ 6.0 solution and project files are provided. The main -JACE solution file compiles all the source files (main, network -service, and test). The solutions and projects are in -MSVJProjects.zip. - -If you don't have VJ++ and are using the JDK from the command line, -you can compile JACE with the batch files in makebat.zip in the JACE -subdirectory. - -Generate the javadoc documentation with the makedoc.bat file (also -in makebat.zip). diff --git a/java/VERSION b/java/VERSION deleted file mode 100644 index 8c004c2231b..00000000000 --- a/java/VERSION +++ /dev/null @@ -1,5 +0,0 @@ -This is Java ACE version 1.5. - -If you have any problems, please send email to Douglas C. Schmidt -at (schmidt@cs.wustl.edu) - diff --git a/java/apps/NexusII/README b/java/apps/NexusII/README deleted file mode 100644 index 60a630cef5a..00000000000 --- a/java/apps/NexusII/README +++ /dev/null @@ -1,58 +0,0 @@ -Nexus II - A chat application in Java with image support --------------------------------------------------------- - - Rajeev Bector (rajeev@cs.wustl.edu) - Aravind Gopalan (aravind@cs.wustl.edu) - Sumedh Mungee (sumedh@cs.wustl.edu) - -This is the README file. This distribution contains the NexusII -server, which is a java application that can be started by a command -similar to the one contained in the sample "start" shell-script. - -It also contains a "start.html" file, which serves as an example on how -a client applet can be included within a .html file. - -A sample use of this, alongwith a simple users manual, can be found at -http://cumbia.cs.wustl.edu/NexusII/ - -Compiling (optional, all the class files are already present) -------------------------------------------------------------- - -All the source .java files, alongwith the makefile should be placed in -the same directory, and can then be compiled using make. - -The client/server use the following packages: - - awtCommand: This package provides a GUI toolkit for the applet - ACE: This is used both by the client/server for - networking. ACE documentation can be found at: - http://www.cs.wustl.edu/~schmidt/ACE.html - -Running -------- - -See the "start" and "start.html" files for examples on how to run the -server and client applet, respectively. The "mywebaddress" variable is -the "temporary" URL of the server, and the "mywebdir" variable is the -temporary directory in which images are cached by the server. Make -sure that both these exist and are world-readable. The "mywebdir" -should be writable to by the server. The "mywebdir" and "mywebaddress" -variables should thus point to the same location, of which mywebdir -contains the path, and mywebaddress contains the URL. - -See "start" for an example on how to do this. - -If you only want to use an existing running server, all you need to -know is the server host-name and port number, and you can directly run -the start.html file via appletviewer. - -Notes ------ - -1. You can compile the client and server using the same makefile. -2. The client applet MUST reside on the same host as the server is running on. -4. run the server using start script. Change the paramters in the start script, - suitable to your configurations. The start script contains further - information on this. - - diff --git a/java/apps/NexusII/classes/ClientHandler.class b/java/apps/NexusII/classes/ClientHandler.class Binary files differdeleted file mode 100644 index c6bf722c54f..00000000000 --- a/java/apps/NexusII/classes/ClientHandler.class +++ /dev/null diff --git a/java/apps/NexusII/classes/FrameHandler.class b/java/apps/NexusII/classes/FrameHandler.class Binary files differdeleted file mode 100644 index 72d0c67ce70..00000000000 --- a/java/apps/NexusII/classes/FrameHandler.class +++ /dev/null diff --git a/java/apps/NexusII/classes/ImageCanvas.class b/java/apps/NexusII/classes/ImageCanvas.class Binary files differdeleted file mode 100644 index eefcfe0f323..00000000000 --- a/java/apps/NexusII/classes/ImageCanvas.class +++ /dev/null diff --git a/java/apps/NexusII/classes/NexusClientApplet.class b/java/apps/NexusII/classes/NexusClientApplet.class Binary files differdeleted file mode 100644 index 8157ac32759..00000000000 --- a/java/apps/NexusII/classes/NexusClientApplet.class +++ /dev/null diff --git a/java/apps/NexusII/classes/NexusIIserver.class b/java/apps/NexusII/classes/NexusIIserver.class Binary files differdeleted file mode 100644 index f8e566ce282..00000000000 --- a/java/apps/NexusII/classes/NexusIIserver.class +++ /dev/null diff --git a/java/apps/NexusII/classes/Room.class b/java/apps/NexusII/classes/Room.class Binary files differdeleted file mode 100644 index a9d0d4f97bb..00000000000 --- a/java/apps/NexusII/classes/Room.class +++ /dev/null diff --git a/java/apps/NexusII/classes/RoomFactory.class b/java/apps/NexusII/classes/RoomFactory.class Binary files differdeleted file mode 100644 index c1f92d83728..00000000000 --- a/java/apps/NexusII/classes/RoomFactory.class +++ /dev/null diff --git a/java/apps/NexusII/classes/RoomFrame.class b/java/apps/NexusII/classes/RoomFrame.class Binary files differdeleted file mode 100644 index 4b648e1a8cc..00000000000 --- a/java/apps/NexusII/classes/RoomFrame.class +++ /dev/null diff --git a/java/apps/NexusII/classes/RoomThread.class b/java/apps/NexusII/classes/RoomThread.class Binary files differdeleted file mode 100644 index 829fa4175cb..00000000000 --- a/java/apps/NexusII/classes/RoomThread.class +++ /dev/null diff --git a/java/apps/NexusII/classes/awtCommand/CApplet.class b/java/apps/NexusII/classes/awtCommand/CApplet.class Binary files differdeleted file mode 100644 index 3af0361de76..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CApplet.class +++ /dev/null diff --git a/java/apps/NexusII/classes/awtCommand/CApplet.java b/java/apps/NexusII/classes/awtCommand/CApplet.java deleted file mode 100644 index a8680d9abf3..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CApplet.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 1996 Jan Newmarch, University of Canberra. - * Permission to use, copy, modify, and distribute this - * software and its documentation for any purpose and without - * fee is hereby granted, provided that the above copyright - * notice appear in all copies. The author - * makes no representations about the suitability of this - * software for any purpose. It is provided "as is" without - * express or implied warranty. - */ - -package awtCommand; - -import java.awt.*; -import java.applet.*; - -public class CApplet extends Applet { - - protected Command gotFocusCommand = null, - lostFocusCommand = null; - protected Command mouseDownCommand = null, - mouseDragCommand = null, - mouseEnterCommand = null, - mouseExitCommand = null, - mouseMoveCommand = null, - mouseUpCommand = null; - protected Command keyUpCommand = null, - keyDownCommand = null; - - /** - * Constructs a new CApplet. - */ - public CApplet() { - super(); - } - - /* - * event handling methods - */ - - /** - * Called if the window gains focus. This results in a call to - * the gotFocusCommand object with <code>what</code> set to null. - */ - public boolean gotFocus(Event evt, Object what) { - if (gotFocusCommand != null) - gotFocusCommand.execute(this, evt, what); - return false; - } - - /** - * Called if the window loses focus. This results in a call to - * the lostFocusCommand object with <code>what</code> set to null. - */ - public boolean lostFocus(Event evt, Object what) { - if (lostFocusCommand != null) - lostFocusCommand.execute(this, evt, what); - return false; - } - - /** - * Called if the mouse is down. - * This results in a call to the mouseDownCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseDown(Event evt, int x, int y) { - if (mouseDownCommand != null) - mouseDownCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse is dragged. - * This results in a call to the mouseDragCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseDrag(Event evt, int x, int y) { - if (mouseDragCommand != null) - mouseDragCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse enters the window. - * This results in a call to the mouseEnterCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseEnter(Event evt, int x, int y) { - if (mouseEnterCommand != null) - mouseEnterCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse moves inside the window. - * This results in a call to the mouseMoveCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseMove(Event evt, int x, int y) { - if (mouseExitCommand != null) - mouseExitCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse is up. - * This results in a call to the mouseUpCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseUp(Event evt, int x, int y) { - if (mouseUpCommand != null) - mouseUpCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if a character is pressed. - * This results in a call to the keyDownCommand object with - * <code>what</code> set to Integer(key). - */ - public boolean keyDown(Event evt, int key) { - if (keyDownCommand != null) - keyDownCommand.execute(this, evt, new Integer(key)); - return false; - } - - /** - * Called if a character is released. - * This results in a call to the keyUpCommand object with - * <code>what</code> set to Integer(key). - */ - public boolean keyUp(Event evt, int key) { - if (keyUpCommand != null) - keyUpCommand.execute(this, evt, new Integer(key)); - return false; - } - - - /* - * set...Command methods - */ - - - /** - * Sets the mouseDownCommand object. - */ - public void setMouseDownCommand(Command c) { - mouseDownCommand = c; - } - - /** - * Sets the moueDragCommand object. - */ - public void setMouseDragCommand(Command c) { - mouseDragCommand = c; - } - - /** - * Sets the mouseEnterCommand object. - */ - public void setMouseEnterCommand(Command c) { - mouseEnterCommand = c; - } - - /** - * Sets the mouseExitCommand object. - */ - public void setMouseExitCommand(Command c) { - mouseExitCommand = c; - } - - /** - * Sets the mouseMoveCommand object. - */ - public void setMouseMoveCommand(Command c) { - mouseMoveCommand = c; - } - - /** - * Sets the mouseUpCommand object. - */ - public void setMouseUpCommand(Command c) { - mouseUpCommand = c; - } - - /** - * Sets the keyDownCommand object. - */ - public void setKeyDownCommand(Command c) { - keyDownCommand = c; - } - - /** - * Sets the keyUpCommand object. - */ - public void setKeyUpCommand(Command c) { - keyUpCommand = c; - } -} diff --git a/java/apps/NexusII/classes/awtCommand/CButton.class b/java/apps/NexusII/classes/awtCommand/CButton.class Binary files differdeleted file mode 100644 index b64fecd5bbf..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CButton.class +++ /dev/null diff --git a/java/apps/NexusII/classes/awtCommand/CButton.java b/java/apps/NexusII/classes/awtCommand/CButton.java deleted file mode 100644 index ff0f3385bad..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CButton.java +++ /dev/null @@ -1,41 +0,0 @@ - -package awtCommand; - -import java.lang.*; -import java.awt.*; - -public class CButton extends java.awt.Button { - protected Command actionCommand = null; - - /** - * Constructs a CButton. - */ - public CButton() { - super(); - } - - /** - * Constructs a CButton with the given name. - */ - public CButton(String name) { - super(name); - } - - /** - * Sets the actionCommand object. - */ - public void setActionCommand(Command action) { - actionCommand = action; - } - - /** - * Called when the button is selected.. - * This results in a call to the actionCommand object - * with <code>what</code> set to the button's label. - */ - public boolean action(Event evt, Object what) { - if (actionCommand != null) - actionCommand.execute(this, evt, what); - return false; - } -} diff --git a/java/apps/NexusII/classes/awtCommand/CCanvas.class b/java/apps/NexusII/classes/awtCommand/CCanvas.class Binary files differdeleted file mode 100644 index 5d697017b5b..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CCanvas.class +++ /dev/null diff --git a/java/apps/NexusII/classes/awtCommand/CCanvas.java b/java/apps/NexusII/classes/awtCommand/CCanvas.java deleted file mode 100644 index 837b6f56f7a..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CCanvas.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Copyright 1996 Jan Newmarch, University of Canberra. - * Permission to use, copy, modify, and distribute this - * software and its documentation for any purpose and without - * fee is hereby granted, provided that the above copyright - * notice appear in all copies. The author - * makes no representations about the suitability of this - * software for any purpose. It is provided "as is" without - * express or implied warranty. - */ - -package awtCommand; - -import java.awt.*; - -public class CCanvas extends Canvas { - - protected Command gotFocusCommand = null, - lostFocusCommand = null; - protected Command mouseDownCommand = null, - mouseDragCommand = null, - mouseEnterCommand = null, - mouseExitCommand = null, - mouseMoveCommand = null, - mouseUpCommand = null; - protected Command keyUpCommand = null, - keyDownCommand = null; - protected Command actionCommand = null; - protected Command scrollAbsoluteCommand = null, - lineDownCommand = null, - lineUpCommand = null, - pageDownCommand = null, - pageUpCommand = null; - protected Command selectCommand = null, - deselectCommand = null; - - - /** - * Constructs a new CCanvas. - */ - public CCanvas() { - super(); - } - - /** - * Handles the event. - * Calls methods for variousL events and passes - * others to its superclass method. - */ - public boolean handleEvent(Event evt) { - switch (evt.id) { - case Event.SCROLL_ABSOLUTE: - return scrollAbsolute(evt, evt.arg); - case Event.SCROLL_LINE_DOWN: - return lineDown(evt, evt.arg); - case Event.SCROLL_LINE_UP: - return lineUp(evt, evt.arg); - case Event.SCROLL_PAGE_DOWN: - return pageDown(evt, evt.arg); - case Event.SCROLL_PAGE_UP: - return pageUp(evt, evt.arg); - case Event.LIST_SELECT: - return select(evt, evt.arg); - case Event.LIST_DESELECT: - return deselect(evt, evt.arg); - default: - return super.handleEvent(evt); - } - } - - - /* - * event handling methods - */ - - /** - * Called if the window gains focus. This results in a call to - * the gotFocusCommand object with <code>what</code> set to null. - */ - public boolean gotFocus(Event evt, Object what) { - if (gotFocusCommand != null) - gotFocusCommand.execute(this, evt, what); - return false; - } - - /** - * Called if the window loses focus. This results in a call to - * the lostFocusCommand object with <code>what</code> set to null. - */ - public boolean lostFocus(Event evt, Object what) { - if (lostFocusCommand != null) - lostFocusCommand.execute(this, evt, what); - return false; - } - - /** - * Called if the mouse is down. - * This results in a call to the mouseDownCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseDown(Event evt, int x, int y) { - if (mouseDownCommand != null) - mouseDownCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse is dragged. - * This results in a call to the mouseDragCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseDrag(Event evt, int x, int y) { - if (mouseDragCommand != null) - mouseDragCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse enters the window. - * This results in a call to the mouseEnterCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseEnter(Event evt, int x, int y) { - if (mouseEnterCommand != null) - mouseEnterCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse moves inside the window. - * This results in a call to the mouseMoveCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseMove(Event evt, int x, int y) { - if (mouseExitCommand != null) - mouseExitCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse is up. - * This results in a call to the mouseUpCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseUp(Event evt, int x, int y) { - if (mouseUpCommand != null) - mouseUpCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if a character is pressed. - * This results in a call to the keyDownCommand object with - * <code>what</code> set to Integer(key). - */ - public boolean keyDown(Event evt, int key) { - if (keyDownCommand != null) - keyDownCommand.execute(this, evt, new Integer(key)); - return false; - } - - /** - * Called if a character is released. - * This results in a call to the keyUpCommand object with - * <code>what</code> set to Integer(key). - */ - public boolean keyUp(Event evt, int key) { - if (keyUpCommand != null) - keyUpCommand.execute(this, evt, new Integer(key)); - return false; - } - - /** - * Called when an ACTION_EVENT is generated. - * This results in a call to the actionCommand object - * with <code>what</code> set to the event's arg. - */ - public boolean action(Event evt, Object what) { - if (actionCommand != null) - actionCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar is dragged. - * This results in a call to the scrollAbsoluteCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean scrollAbsolute(Event evt, Object what) { - if (scrollAbsoluteCommand != null) - scrollAbsoluteCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar is incremented down. - * This results in a call to the lineDownCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean lineDown(Event evt, Object what) { - if (lineDownCommand != null) - lineDownCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar is incremented up. - * This results in a call to the lineUpCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean lineUp(Event evt, Object what) { - if (lineUpCommand != null) - lineUpCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar pages up. - * This results in a call to the pageUpCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean pageUp(Event evt, Object what) { - if (pageUpCommand != null) - pageUpCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar pages down. - * This results in a call to the pageDownCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean pageDown(Event evt, Object what) { - if (pageDownCommand != null) - pageDownCommand.execute(this, evt, what); - return false; - } - - /** - * Called if the mouse selects an item in a List. - * This results in a call to the selectCommand object - * with <code>what</code> set to the selected index. - */ - public boolean select(Event evt, Object what) { - if (selectCommand != null) - selectCommand.execute(this, evt, what); - return false; - } - - - /** - * Called if the mouse deselects an item in a List. - * This results in a call to the deselectCommand object - * with <code>what</code> set to the deselected index. - */ - public boolean deselect(Event evt, Object what) { - if (deselectCommand != null) - deselectCommand.execute(this, evt, what); - return false; - } - - - /* - * set...Command methods - */ - - - - /** - * Sets the mouseDownCommand object. - */ - public void setMouseDownCommand(Command c) { - mouseDownCommand = c; - } - - /** - * Sets the moueDragCommand object. - */ - public void setMouseDragCommand(Command c) { - mouseDragCommand = c; - } - - /** - * Sets the mouseEnterCommand object. - */ - public void setMouseEnterCommand(Command c) { - mouseEnterCommand = c; - } - - /** - * Sets the mouseExitCommand object. - */ - public void setMouseExitCommand(Command c) { - mouseExitCommand = c; - } - - /** - * Sets the mouseMoveCommand object. - */ - public void setMouseMoveCommand(Command c) { - mouseMoveCommand = c; - } - - /** - * Sets the mouseUpCommand object. - */ - public void setMouseUpCommand(Command c) { - mouseUpCommand = c; - } - - /** - * Sets the keyDownCommand object. - */ - public void setKeyDownCommand(Command c) { - keyDownCommand = c; - } - - /** - * Sets the keyUpCommand object. - */ - public void setKeyUpCommand(Command c) { - keyUpCommand = c; - } - - /** - * Sets the actionCommand object. - */ - public void setActionCommand(Command action) { - actionCommand = action; - } - - /** - * Sets the scrollAbsoluteCommand. - */ - public void setScrollAbsoluteCommand(Command c) { - scrollAbsoluteCommand = c; - } - - /** - * Sets the lineUpCommand. - */ - public void setLineUpCommand(Command c) { - lineUpCommand = c; - } - - /** - * Sets the lineDownCommand. - */ - public void setLineDownCommand(Command c) { - lineDownCommand = c; - } - - /** - * Sets the pageUpCommand. - */ - public void setPageUpCommand(Command c) { - pageUpCommand = c; - } - - /** - * Sets the pageDownCommand. - */ - public void setPageDownCommand(Command c) { - pageDownCommand = c; - } - - /** - * Sets the selectCommand. - */ - public void setSelectCommand(Command select) { - selectCommand = select; - } - - /** - * Sets the deselectCommand. - */ - public void setDeselectCommand(Command deselect) { - deselectCommand = deselect; - } - -} diff --git a/java/apps/NexusII/classes/awtCommand/CFrame.class b/java/apps/NexusII/classes/awtCommand/CFrame.class Binary files differdeleted file mode 100644 index 66f25773c76..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CFrame.class +++ /dev/null diff --git a/java/apps/NexusII/classes/awtCommand/CFrame.java b/java/apps/NexusII/classes/awtCommand/CFrame.java deleted file mode 100644 index f63d3ce8b9a..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CFrame.java +++ /dev/null @@ -1,486 +0,0 @@ -/* - * Copyright 1996 Jan Newmarch, University of Canberra. - * Permission to use, copy, modify, and distribute this - * software and its documentation for any purpose and without - * fee is hereby granted, provided that the above copyright - * notice appear in all copies. The author - * makes no representations about the suitability of this - * software for any purpose. It is provided "as is" without - * express or implied warranty. - */ - -package awtCommand; - -import java.awt.*; - -public class CFrame extends Frame { - - protected Command destroyCommand = null, - deiconifyCommand = null, - iconifyCommand = null, - movedCommand = null; - protected Command gotFocusCommand = null, - lostFocusCommand = null; - protected Command mouseDownCommand = null, - mouseDragCommand = null, - mouseEnterCommand = null, - mouseExitCommand = null, - mouseMoveCommand = null, - mouseUpCommand = null; - protected Command keyUpCommand = null, - keyDownCommand = null; - protected Command actionCommand = null; - protected Command scrollAbsoluteCommand = null, - lineDownCommand = null, - lineUpCommand = null, - pageDownCommand = null, - pageUpCommand = null; - protected Command selectCommand = null, - deselectCommand = null; - - /** - * Constructs a new, initially invisible CFrame. - */ - public CFrame() { - super(); - } - - /** - * Constructs a new, initially invisible CFrame with the - * specified title. - */ - public CFrame(String title) { - super(title); - } - - /** - * Handles the event - */ - public boolean handleEvent(Event evt) { - switch (evt.id) { - case Event.WINDOW_DESTROY: - return windowDestroy(evt); - case Event.WINDOW_DEICONIFY: - return windowDeiconify(evt); - case Event.WINDOW_ICONIFY: - return windowIconify(evt); - case Event.WINDOW_MOVED: - return windowMoved(evt); - case Event.SCROLL_ABSOLUTE: - return scrollAbsolute(evt, evt.arg); - case Event.SCROLL_LINE_DOWN: - return lineDown(evt, evt.arg); - case Event.SCROLL_LINE_UP: - return lineUp(evt, evt.arg); - case Event.SCROLL_PAGE_DOWN: - return pageDown(evt, evt.arg); - case Event.SCROLL_PAGE_UP: - return pageUp(evt, evt.arg); - case Event.LIST_SELECT: - return select(evt, evt.arg); - case Event.LIST_DESELECT: - return deselect(evt, evt.arg); - default: - return super.handleEvent(evt); - } - } - - /* - * event handling methods - */ - - /** - * Called if the dialog's window is destroyed. This results in a call to - * the destroyCommand object with <code>what</code> set to null - */ - public boolean windowDestroy(Event evt) { - if (destroyCommand != null) - destroyCommand.execute(this, evt, null); - return false; - } - - /** - * Called if the dialog's window is deiconified. This results in a call to - * the deiconifyCommand object with <code>what</code> set to null - */ - public boolean windowDeiconify(Event evt) { - if (deiconifyCommand != null) - deiconifyCommand.execute(this, evt, null); - return false; - } - - /** - * Called if the dialog is iconified. This results in a call to - * the iconifyCommand object with <code>what</code> set to null - */ - public boolean windowIconify(Event evt) { - if (iconifyCommand != null) - iconifyCommand.execute(this, evt, null); - return false; - } - - /** - * Called if the dialog's window is moved. This results in a call to - * the movedCommand object with <code>what</code> set to Point(x, y) - */ - public boolean windowMoved(Event evt) { - if (movedCommand != null) - movedCommand.execute(this, evt, new Point(evt.x, evt.y)); - return false; - } - - /* - * I don't know where what objects this next set should belong - * to. Putting them at the top is ok for now - */ - - /** - * Called if the window gains focus. This results in a call to - * the gotFocusCommand object with <code>what</code> set to null. - */ - public boolean gotFocus(Event evt, Object what) { - if (gotFocusCommand != null) - gotFocusCommand.execute(this, evt, what); - return false; - } - - /** - * Called if the window loses focus. This results in a call to - * the lostFocusCommand object with <code>what</code> set to null. - */ - public boolean lostFocus(Event evt, Object what) { - if (lostFocusCommand != null) - lostFocusCommand.execute(this, evt, what); - return false; - } - - /** - * Called if the mouse is down. - * This results in a call to the mouseDownCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseDown(Event evt, int x, int y) { - if (mouseDownCommand != null) - mouseDownCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse is dragged. - * This results in a call to the mouseDragCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseDrag(Event evt, int x, int y) { - if (mouseDragCommand != null) - mouseDragCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse enters the window. - * This results in a call to the mouseEnterCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseEnter(Event evt, int x, int y) { - if (mouseEnterCommand != null) - mouseEnterCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse moves inside the window. - * This results in a call to the mouseMoveCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseMove(Event evt, int x, int y) { - if (mouseExitCommand != null) - mouseExitCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse is up. - * This results in a call to the mouseUpCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseUp(Event evt, int x, int y) { - if (mouseUpCommand != null) - mouseUpCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if a character is pressed. - * This results in a call to the keyDownCommand object with - * <code>what</code> set to Integer(key). - */ - public boolean keyDown(Event evt, int key) { - if (keyDownCommand != null) - keyDownCommand.execute(this, evt, new Integer(key)); - return false; - } - - /** - * Called if a character is released. - * This results in a call to the keyUpCommand object with - * <code>what</code> set to Integer(key). - */ - public boolean keyUp(Event evt, int key) { - if (keyUpCommand != null) - keyUpCommand.execute(this, evt, new Integer(key)); - return false; - } - - - /** - * Called when an ACTION_EVENT is generated. - * This results in a call to the actionCommand object - * with <code>what</code> set to the event's arg. - */ - public boolean action(Event evt, Object what) { - if (actionCommand != null) - actionCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar is dragged. - * This results in a call to the scrollAbsoluteCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean scrollAbsolute(Event evt, Object what) { - if (scrollAbsoluteCommand != null) - scrollAbsoluteCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar is incremented down. - * This results in a call to the lineDownCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean lineDown(Event evt, Object what) { - if (lineDownCommand != null) - lineDownCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar is incremented up. - * This results in a call to the lineUpCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean lineUp(Event evt, Object what) { - if (lineUpCommand != null) - lineUpCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar pages up. - * This results in a call to the pageUpCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean pageUp(Event evt, Object what) { - if (pageUpCommand != null) - pageUpCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar pages down. - * This results in a call to the pageDownCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean pageDown(Event evt, Object what) { - if (pageDownCommand != null) - pageDownCommand.execute(this, evt, what); - return false; - } - - /** - * Called if the mouse selects an item in a List. - * This results in a call to the selectCommand object - * with <code>what</code> set to the selected index. - */ - public boolean select(Event evt, Object what) { - if (selectCommand != null) - selectCommand.execute(this, evt, what); - return false; - } - - - /** - * Called if the mouse deselects an item in a List. - * This results in a call to the deselectCommand object - * with <code>what</code> set to the deselected index. - */ - public boolean deselect(Event evt, Object what) { - if (deselectCommand != null) - deselectCommand.execute(this, evt, what); - return false; - } - - - /* - * set...Command methods - */ - - - /** - * Sets the destroyCommand object. - */ - public void setDestroyCommand(Command c) { - destroyCommand = c; - } - - /** - * Sets the deiconifyCommand object. - */ - public void setDeiconifyCommand(Command c) { - deiconifyCommand = c; - } - - /** - * Sets the iconifyCommand object. - */ - public void setIconifyCommand(Command c) { - iconifyCommand = c; - } - - /** - * Sets the movedCommand object. - */ - public void setMovedCommand(Command c) { - movedCommand = c; - } - - /** - * Sets the mouseDownCommand object. - */ - public void setMouseDownCommand(Command c) { - mouseDownCommand = c; - } - - /** - * Sets the moueDragCommand object. - */ - public void setMouseDragCommand(Command c) { - mouseDragCommand = c; - } - - /** - * Sets the mouseEnterCommand object. - */ - public void setMouseEnterCommand(Command c) { - mouseEnterCommand = c; - } - - /** - * Sets the mouseExitCommand object. - */ - public void setMouseExitCommand(Command c) { - mouseExitCommand = c; - } - - /** - * Sets the mouseMoveCommand object. - */ - public void setMouseMoveCommand(Command c) { - mouseMoveCommand = c; - } - - /** - * Sets the mouseUpCommand object. - */ - public void setMouseUpCommand(Command c) { - mouseUpCommand = c; - } - - /** - * Sets the keyDownCommand object. - */ - public void setKeyDownCommand(Command c) { - keyDownCommand = c; - } - - /** - * Sets the keyUpCommand object. - */ - public void setKeyUpCommand(Command c) { - keyUpCommand = c; - } - - /** - * Sets the actionCommand object. - */ - public void setActionCommand(Command action) { - actionCommand = action; - } - - /** - * Sets the scrollAbsoluteCommand. - */ - public void setScrollAbsoluteCommand(Command c) { - scrollAbsoluteCommand = c; - } - - /** - * Sets the lineUpCommand. - */ - public void setLineUpCommand(Command c) { - lineUpCommand = c; - } - - /** - * Sets the lineDownCommand. - */ - public void setLineDownCommand(Command c) { - lineDownCommand = c; - } - - /** - * Sets the pageUpCommand. - */ - public void setPageUpCommand(Command c) { - pageUpCommand = c; - } - - /** - * Sets the pageDownCommand. - */ - public void setPageDownCommand(Command c) { - pageDownCommand = c; - } - - /** - * Sets the selectCommand. - */ - public void setSelectCommand(Command select) { - selectCommand = select; - } - - public void setGotFocusCommand(Command c) { - gotFocusCommand = c ; - } - /** - * Sets the deselectCommand. - */ - public void setDeselectCommand(Command deselect) { - deselectCommand = deselect; - } - -} - - - - - - - - - - - - - diff --git a/java/apps/NexusII/classes/awtCommand/CList.class b/java/apps/NexusII/classes/awtCommand/CList.class Binary files differdeleted file mode 100644 index c595ce7786b..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CList.class +++ /dev/null diff --git a/java/apps/NexusII/classes/awtCommand/CList.java b/java/apps/NexusII/classes/awtCommand/CList.java deleted file mode 100644 index 110e6a01db2..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CList.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 1996 Jan Newmarch, University of Canberra. - * Permission to use, copy, modify, and distribute this - * software and its documentation for any purpose and without - * fee is hereby granted, provided that the above copyright - * notice appear in all copies. The author - * makes no representations about the suitability of this - * software for any purpose. It is provided "as is" without - * express or implied warranty. - */ - - -package awtCommand; - -import java.awt.*; - -public class CList extends List { - protected Command selectCommand = null; - protected Command deselectCommand = null; - protected Command actionCommand = null; - - /** - * Handles the event - */ - public boolean handleEvent(Event evt) { - switch (evt.id) { - case Event.LIST_SELECT: - return select(evt, evt.arg); - case Event.LIST_DESELECT: - return deselect(evt, evt.arg); - default: - return super.handleEvent(evt); - } - } - - /* - * event handling methods - */ - - - /** - * Called if the Enter key is pressed. - * This results in a call to the actionCommand object - * with <code>what</code> set to the selected item. - */ - public boolean action(Event evt, Object what) { - if (actionCommand != null) - actionCommand.execute(this, evt, what); - return false; - } - - /** - * Called if the mouse selects an item. - * This results in a call to the selectCommand object - * with <code>what</code> set to the selected index. - */ - public boolean select(Event evt, Object what) { - if (selectCommand != null) - selectCommand.execute(this, evt, what); - return false; - } - - - /** - * Called if the mouse deselects an item. - * This results in a call to the deselectCommand object - * with <code>what</code> set to the deselected index. - */ - public boolean deselect(Event evt, Object what) { - if (deselectCommand != null) - deselectCommand.execute(this, evt, what); - return false; - } - - - /** - * Sets the actionCommand. - */ - public void setActionCommand(Command action) { - actionCommand = action; - } - - /** - * Sets the selectCommand. - */ - public void setSelectCommand(Command select) { - selectCommand = select; - } - - /** - * Sets the deselectCommand. - */ - public void setDeselectCommand(Command deselect) { - deselectCommand = deselect; - } -} diff --git a/java/apps/NexusII/classes/awtCommand/CPanel.class b/java/apps/NexusII/classes/awtCommand/CPanel.class Binary files differdeleted file mode 100644 index d00477a30f5..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CPanel.class +++ /dev/null diff --git a/java/apps/NexusII/classes/awtCommand/CPanel.java b/java/apps/NexusII/classes/awtCommand/CPanel.java deleted file mode 100644 index 1c8d39f8537..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CPanel.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Copyright 1996 Jan Newmarch, University of Canberra. - * Permission to use, copy, modify, and distribute this - * software and its documentation for any purpose and without - * fee is hereby granted, provided that the above copyright - * notice appear in all copies. The author - * makes no representations about the suitability of this - * software for any purpose. It is provided "as is" without - * express or implied warranty. - */ - -package awtCommand; - -import java.awt.*; - -public class CPanel extends Panel { - - protected Command gotFocusCommand = null, - lostFocusCommand = null; - protected Command mouseDownCommand = null, - mouseDragCommand = null, - mouseEnterCommand = null, - mouseExitCommand = null, - mouseMoveCommand = null, - mouseUpCommand = null; - protected Command keyUpCommand = null, - keyDownCommand = null; - protected Command actionCommand = null; - protected Command scrollAbsoluteCommand = null, - lineDownCommand = null, - lineUpCommand = null, - pageDownCommand = null, - pageUpCommand = null; - protected Command selectCommand = null, - deselectCommand = null; - - /** - * Constructs a new CPanel. - */ - public CPanel() { - super(); - } - - - /** - * Handles the event. - * Calls methods for variousL events and passes - * others to its superclass method. - */ - public boolean handleEvent(Event evt) { - switch (evt.id) { - case Event.SCROLL_ABSOLUTE: - return scrollAbsolute(evt, evt.arg); - case Event.SCROLL_LINE_DOWN: - return lineDown(evt, evt.arg); - case Event.SCROLL_LINE_UP: - return lineUp(evt, evt.arg); - case Event.SCROLL_PAGE_DOWN: - return pageDown(evt, evt.arg); - case Event.SCROLL_PAGE_UP: - return pageUp(evt, evt.arg); - case Event.LIST_SELECT: - return select(evt, evt.arg); - case Event.LIST_DESELECT: - return deselect(evt, evt.arg); - default: - return super.handleEvent(evt); - } - } - - /* - * event handling methods - */ - - /** - * Called if the window gains focus. This results in a call to - * the gotFocusCommand object with <code>what</code> set to null. - */ - public boolean gotFocus(Event evt, Object what) { - if (gotFocusCommand != null) - gotFocusCommand.execute(this, evt, what); - return false; - } - - /** - * Called if the window loses focus. This results in a call to - * the lostFocusCommand object with <code>what</code> set to null. - */ - public boolean lostFocus(Event evt, Object what) { - if (lostFocusCommand != null) - lostFocusCommand.execute(this, evt, what); - return false; - } - - /** - * Called if the mouse is down. - * This results in a call to the mouseDownCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseDown(Event evt, int x, int y) { - if (mouseDownCommand != null) - mouseDownCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse is dragged. - * This results in a call to the mouseDragCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseDrag(Event evt, int x, int y) { - if (mouseDragCommand != null) - mouseDragCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse enters the window. - * This results in a call to the mouseEnterCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseEnter(Event evt, int x, int y) { - if (mouseEnterCommand != null) - mouseEnterCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse moves inside the window. - * This results in a call to the mouseMoveCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseMove(Event evt, int x, int y) { - if (mouseExitCommand != null) - mouseExitCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if the mouse is up. - * This results in a call to the mouseUpCommand object with - * <code>what</code> set to Point(x, y) - */ - public boolean mouseUp(Event evt, int x, int y) { - if (mouseUpCommand != null) - mouseUpCommand.execute(this, evt, new Point(x, y)); - return false; - } - - /** - * Called if a character is pressed. - * This results in a call to the keyDownCommand object with - * <code>what</code> set to Integer(key). - */ - public boolean keyDown(Event evt, int key) { - if (keyDownCommand != null) - keyDownCommand.execute(this, evt, new Integer(key)); - return false; - } - - /** - * Called if a character is released. - * This results in a call to the keyUpCommand object with - * <code>what</code> set to Integer(key). - */ - public boolean keyUp(Event evt, int key) { - if (keyUpCommand != null) - keyUpCommand.execute(this, evt, new Integer(key)); - return false; - } - - - /** - * Called when an ACTION_EVENT is generated. - * This results in a call to the actionCommand object - * with <code>what</code> set to the event's arg. - */ - public boolean action(Event evt, Object what) { - if (actionCommand != null) - actionCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar is dragged. - * This results in a call to the scrollAbsoluteCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean scrollAbsolute(Event evt, Object what) { - if (scrollAbsoluteCommand != null) - scrollAbsoluteCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar is incremented down. - * This results in a call to the lineDownCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean lineDown(Event evt, Object what) { - if (lineDownCommand != null) - lineDownCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar is incremented up. - * This results in a call to the lineUpCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean lineUp(Event evt, Object what) { - if (lineUpCommand != null) - lineUpCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar pages up. - * This results in a call to the pageUpCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean pageUp(Event evt, Object what) { - if (pageUpCommand != null) - pageUpCommand.execute(this, evt, what); - return false; - } - - /** - * Called when a scrollbar pages down. - * This results in a call to the pageDownCommand object - * with <code>what</code> set to the slider location value. - */ - public boolean pageDown(Event evt, Object what) { - if (pageDownCommand != null) - pageDownCommand.execute(this, evt, what); - return false; - } - - /** - * Called if the mouse selects an item in a List. - * This results in a call to the selectCommand object - * with <code>what</code> set to the selected index. - */ - public boolean select(Event evt, Object what) { - if (selectCommand != null) - selectCommand.execute(this, evt, what); - return false; - } - - - /** - * Called if the mouse deselects an item in a List. - * This results in a call to the deselectCommand object - * with <code>what</code> set to the deselected index. - */ - public boolean deselect(Event evt, Object what) { - if (deselectCommand != null) - deselectCommand.execute(this, evt, what); - return false; - } - - /* - * set...Command methods - */ - - - - /** - * Sets the mouseDownCommand object. - */ - public void setMouseDownCommand(Command c) { - mouseDownCommand = c; - } - - /** - * Sets the moueDragCommand object. - */ - public void setMouseDragCommand(Command c) { - mouseDragCommand = c; - } - - /** - * Sets the mouseEnterCommand object. - */ - public void setMouseEnterCommand(Command c) { - mouseEnterCommand = c; - } - - /** - * Sets the mouseExitCommand object. - */ - public void setMouseExitCommand(Command c) { - mouseExitCommand = c; - } - - /** - * Sets the mouseMoveCommand object. - */ - public void setMouseMoveCommand(Command c) { - mouseMoveCommand = c; - } - - /** - * Sets the mouseUpCommand object. - */ - public void setMouseUpCommand(Command c) { - mouseUpCommand = c; - } - - /** - * Sets the keyDownCommand object. - */ - public void setKeyDownCommand(Command c) { - keyDownCommand = c; - } - - /** - * Sets the keyUpCommand object. - */ - public void setKeyUpCommand(Command c) { - keyUpCommand = c; - } - - - /** - * Sets the actionCommand object. - */ - public void setActionCommand(Command action) { - actionCommand = action; - } - - /** - * Sets the scrollAbsoluteCommand. - */ - public void setScrollAbsoluteCommand(Command c) { - scrollAbsoluteCommand = c; - } - - /** - * Sets the lineUpCommand. - */ - public void setLineUpCommand(Command c) { - lineUpCommand = c; - } - - /** - * Sets the lineDownCommand. - */ - public void setLineDownCommand(Command c) { - lineDownCommand = c; - } - - /** - * Sets the pageUpCommand. - */ - public void setPageUpCommand(Command c) { - pageUpCommand = c; - } - - /** - * Sets the pageDownCommand. - */ - public void setPageDownCommand(Command c) { - pageDownCommand = c; - } - - /** - * Sets the selectCommand. - */ - public void setSelectCommand(Command select) { - selectCommand = select; - } - - /** - * Sets the deselectCommand. - */ - public void setDeselectCommand(Command deselect) { - deselectCommand = deselect; - } - -} diff --git a/java/apps/NexusII/classes/awtCommand/CTextArea.class b/java/apps/NexusII/classes/awtCommand/CTextArea.class Binary files differdeleted file mode 100644 index 9ec6e238cdf..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CTextArea.class +++ /dev/null diff --git a/java/apps/NexusII/classes/awtCommand/CTextArea.java b/java/apps/NexusII/classes/awtCommand/CTextArea.java deleted file mode 100644 index eacaf526929..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CTextArea.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 1996 Jan Newmarch, University of Canberra. - * Permission to use, copy, modify, and distribute this - * software and its documentation for any purpose and without - * fee is hereby granted, provided that the above copyright - * notice appear in all copies. The author - * makes no representations about the suitability of this - * software for any purpose. It is provided "as is" without - * express or implied warranty. - */ - -package awtCommand; - -import java.awt.*; - -public class CTextArea extends TextArea { - - protected Command gotFocusCommand = null, - lostFocusCommand = null; - - /** - * Constructs a new TextArea. - */ - public CTextArea() { - super(); - } - - /** - * Constructs a new TextArea with the specified number of rows and columns. - * @param rows the number of rows - * @param cols the number of columns - */ - public CTextArea(int rows, int cols) { - super(rows, cols); - } - - /** - * Constructs a new TextArea with the specified text displayed. - * @param text the text to be displayed - */ - public CTextArea(String text) { - super(text); - } - - /** - * Constructs a new TextArea with the specified text and the - * specified number of rows - * and columns. - * @param text the text to be displayed - * @param rows the number of rows - * @param cols the number of cols - */ - public CTextArea(String text, int rows, int cols) { - super(text, rows, cols); - } - - - /** - * Called when the text area gains the focus. - * This results in a call to the gotFocusCommand object - * with <code>what</code> set to null. - */ - public boolean gotFocus(Event evt, Object what) { - if (gotFocusCommand != null) - gotFocusCommand.execute(this, evt, what); - return false; - } - - /** - * Called when the text area loses the focus. - * This results in a call to the lostFocusCommand object - * with <code>what</code> set to null. - */ - public boolean lostFocus(Event evt, Object what) { - if (lostFocusCommand != null) - lostFocusCommand.execute(this, evt, what); - return false; - } - - /** - * Sets the gotFocusCommand object. - */ - public void setGotFocusCommand(Command c) { - gotFocusCommand = c; - } - - /** - * Sets the lostFocusCommand object. - */ - public void setLostFocusCommand(Command c) { - lostFocusCommand = c; - } -} diff --git a/java/apps/NexusII/classes/awtCommand/CTextField.class b/java/apps/NexusII/classes/awtCommand/CTextField.class Binary files differdeleted file mode 100644 index 6f298a43348..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CTextField.class +++ /dev/null diff --git a/java/apps/NexusII/classes/awtCommand/CTextField.java b/java/apps/NexusII/classes/awtCommand/CTextField.java deleted file mode 100644 index 146f13206e5..00000000000 --- a/java/apps/NexusII/classes/awtCommand/CTextField.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 1996 Jan Newmarch, University of Canberra. - * Permission to use, copy, modify, and distribute this - * software and its documentation for any purpose and without - * fee is hereby granted, provided that the above copyright - * notice appear in all copies. The author - * makes no representations about the suitability of this - * software for any purpose. It is provided "as is" without - * express or implied warranty. - */ - -package awtCommand; - -import java.awt.*; - -public class CTextField extends TextField { - - protected Command actionCommand = null, - gotFocusCommand = null, - lostFocusCommand = null; - - /** - * Constructs a new CTextField. - */ - public CTextField() { - super(); - } - - /** - * Constructs a new CTextField initialized with the specified columns. - * @param cols the number of columns - */ - public CTextField(int cols) { - super(cols); - } - - /** - * Constructs a new CTextField initialized with the specified text. - * @param text the text to be displayed - */ - public CTextField(String text) { - super(text); - } - - - /** - * Constructs a new CTextField initialized with the specified text and columns. - * @param text the text to be displayed - * @param cols the number of columns - */ - public CTextField(String text, int cols) { - super(text, cols); - } - - - /** - * Called when Enter is pressed in the text field. - * This results in a call to the actionCommand object - * with <code>what</code> set to the text contents. - */ - public boolean action(Event evt, Object what) { - if (actionCommand != null) - actionCommand.execute(this, evt, what); - return false; - } - - /** - * Called when the text field gains the focus. - * This results in a call to the gotFocusCommand object - * with <code>what</code> set to null. - */ - public boolean gotFocus(Event evt, Object what) { - if (gotFocusCommand != null) - gotFocusCommand.execute(this, evt, what); - return false; - } - - /** - * Called when the text field loses the focus. - * This results in a call to the lostFocusCommand object - * with <code>what</code> set to null. - */ - public boolean lostFocus(Event evt, Object what) { - if (lostFocusCommand != null) - lostFocusCommand.execute(this, evt, what); - return false; - } - - /** - * Sets the actionCommand object. - */ - public void setActionCommand(Command c) { - actionCommand = c; - } - - - /** - * Sets the gotFocusCommand object. - */ - public void setGotFocusCommand(Command c) { - gotFocusCommand = c; - } - - /** - * Sets the lostFocusCommand object. - */ - public void setLostFocusCommand(Command c) { - lostFocusCommand = c; - } -} diff --git a/java/apps/NexusII/classes/awtCommand/Command.class b/java/apps/NexusII/classes/awtCommand/Command.class Binary files differdeleted file mode 100644 index 6b3c12c24f7..00000000000 --- a/java/apps/NexusII/classes/awtCommand/Command.class +++ /dev/null diff --git a/java/apps/NexusII/classes/awtCommand/Command.java b/java/apps/NexusII/classes/awtCommand/Command.java deleted file mode 100644 index 373c7a363cf..00000000000 --- a/java/apps/NexusII/classes/awtCommand/Command.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 1996 Jan Newmarch, University of Canberra. - * Permission to use, copy, modify, and distribute this - * software and its documentation for any purpose and without - * fee is hereby granted, provided that the above copyright - * notice appear in all copies. The author - * makes no representations about the suitability of this - * software for any purpose. It is provided "as is" without - * express or implied warranty. - */ - - - -package awtCommand; - -import java.awt.*; - -public interface Command { - - /** - * Executes application logic. - * Called by events occurring in associated objects - */ - public abstract void execute(Object target, Event evt, Object what); -} diff --git a/java/apps/NexusII/classes/commandHandler.class b/java/apps/NexusII/classes/commandHandler.class Binary files differdeleted file mode 100644 index 53033fb6b6b..00000000000 --- a/java/apps/NexusII/classes/commandHandler.class +++ /dev/null diff --git a/java/apps/NexusII/classes/commandParser.class b/java/apps/NexusII/classes/commandParser.class Binary files differdeleted file mode 100644 index 62da40871e6..00000000000 --- a/java/apps/NexusII/classes/commandParser.class +++ /dev/null diff --git a/java/apps/NexusII/classes/connectionHandler.class b/java/apps/NexusII/classes/connectionHandler.class Binary files differdeleted file mode 100644 index 8708229c0eb..00000000000 --- a/java/apps/NexusII/classes/connectionHandler.class +++ /dev/null diff --git a/java/apps/NexusII/classes/joinHandler.class b/java/apps/NexusII/classes/joinHandler.class Binary files differdeleted file mode 100644 index 7669e7faed7..00000000000 --- a/java/apps/NexusII/classes/joinHandler.class +++ /dev/null diff --git a/java/apps/NexusII/classes/roomHandler.class b/java/apps/NexusII/classes/roomHandler.class Binary files differdeleted file mode 100644 index 9eaa6cc0899..00000000000 --- a/java/apps/NexusII/classes/roomHandler.class +++ /dev/null diff --git a/java/apps/NexusII/classes/textHandler.class b/java/apps/NexusII/classes/textHandler.class Binary files differdeleted file mode 100644 index c52764a236b..00000000000 --- a/java/apps/NexusII/classes/textHandler.class +++ /dev/null diff --git a/java/apps/NexusII/src/Consumer.java b/java/apps/NexusII/src/Consumer.java deleted file mode 100644 index 84df9b3a3ae..00000000000 --- a/java/apps/NexusII/src/Consumer.java +++ /dev/null @@ -1,74 +0,0 @@ - -// This class encapsulates a Consumer. The consumer dq's from the queue -// Supports both a timed and blocking consumer. -// Each instance of this class creates a different thread of control. -// On timeout, the producer returns. -// The producer tries to dq "iteration" number of times, unless it times out - -//package NexusII.util ; - -public class Consumer extends Thread -{ -public static final int DEFAULT_ITERATIONS = 1 ; -public Consumer(MT_Bounded_Queue queue) - { - this.queue_ = queue ; - this.iterations_ = new Integer(DEFAULT_ITERATIONS); - this.time_out_ = -1 ; - } - -public Consumer(MT_Bounded_Queue queue, String name) - { - super(name); - this.queue_ = queue ; - this.iterations_ = new Integer(DEFAULT_ITERATIONS); - this.time_out_ = -1 ; - } - - -public Consumer(MT_Bounded_Queue queue, String name, Integer iterations) - { - super(name); - this.queue_ = queue ; - this.iterations_ = iterations ; - this.time_out_ = -1 ; - } - - -public Consumer(MT_Bounded_Queue queue, String name, Integer iterations, long msec_timeout) - { - super(name); - this.queue_ = queue ; - this.iterations_ = iterations ; - this.time_out_ = msec_timeout ; - } - - - -public void run() - { - for(int i=0;i<iterations_.intValue();i++) - { - if(time_out_ < 0) - System.out.println(getName() + ": dequeued " + queue_.dq()); - else - { - Object err = queue_.dq(time_out_); - if(err == null) - { - System.out.println(getName() + ": Timedout\n"); - return ; - } - - else - System.out.println(getName() + ": dequeued " + err); - } - } - } - - -protected MT_Bounded_Queue queue_ ; -private Integer iterations_ ; -private long time_out_ ; -} - diff --git a/java/apps/NexusII/src/MT_Bounded_Queue.java b/java/apps/NexusII/src/MT_Bounded_Queue.java deleted file mode 100644 index a9b493fa263..00000000000 --- a/java/apps/NexusII/src/MT_Bounded_Queue.java +++ /dev/null @@ -1,226 +0,0 @@ - -// package NexusII.util ; - -// The minimun functionality to be associated with a queue -interface Queue -{ -public void nq(Object item); -public Object dq(); -public boolean is_full(); -public boolean is_empty(); -public static final int DEF_SIZE = 1; -}; - -// Specific Conditions associated with MT_Bounded_Queue -// Is true if there is space in the queue - -class Not_Full_Condition extends Timed_Wait -{ - -public Not_Full_Condition(MT_Bounded_Queue q) - { - super(q); - } - -public synchronized boolean condition() - { - MT_Bounded_Queue mq_ = (MT_Bounded_Queue) object_; - return !mq_.is_full (); - } - -} - -// Is true if there's something in the queue - -class Not_Empty_Condition extends Timed_Wait -{ - -public Not_Empty_Condition(MT_Bounded_Queue q) - { - super(q); - } - -public synchronized boolean condition() - { - // Delegate to the appropriate conditional - // check on the MessageQueue. - MT_Bounded_Queue mq_ = (MT_Bounded_Queue) object_; - return !mq_.is_empty (); - } - -private MT_Bounded_Queue mq_ ; -} - - - - -// Encapsulates a bounded - synchronized queue - -public class MT_Bounded_Queue implements Queue -{ - - -private Object[] queue_ ; -private int front_ ; -private int back_ ; -private int max_size_ ; -private int size_ ; -private Not_Empty_Condition not_empty_condition_ ; -private Not_Full_Condition not_full_condition_ ; -private int nq_count_ ; -private int dq_count_ ; - -// The counters counts the number of nq's and dq's operations made on this -// instance of the queue - -public int dq_count() -{ - return dq_count_ ; -} - -public int nq_count() -{ - return nq_count_ ; -} - -public MT_Bounded_Queue() - { - // call the other constructor with DEF_SIZE - this(DEF_SIZE); - } - -public MT_Bounded_Queue(int max_size) - { - this.front_ = 0 ; - this.back_ = 0 ; - this.max_size_ = max_size ; - this.size_ = 0 ; - // these are included for STATISTICS - this.nq_count_ = 0 ; - this.dq_count_ = 0 ; - this.queue_ = new Object[this.max_size_]; - not_full_condition_ = new Not_Full_Condition(this); - not_empty_condition_ = new Not_Empty_Condition(this); - } - -// Blocking nq -public synchronized void nq(Object item) - { - // Wait till the queue has space - while(is_full()) - { - try { - wait(); - } catch (InterruptedException e) {} - } - - // enqueue here - queue_[back_] = item ; - back_ = (back_ + 1) % max_size_ ; - size_++ ; - // One more enqueue operation has occured - nq_count_ ++ ; - // wakeup the sleeping guys - notifyAll(); - } - - // Timed nq -// returns -1 if timed_out -public synchronized int nq(Object item,long msec_timeout) - { - // Wait till the queue has space - try { - not_full_condition_.timed_wait(msec_timeout); - } catch (InterruptedException e) {} - catch (TimeoutException t) - { - return -1 ; - } - - // enqueue here - queue_[back_] = item ; - back_ = (back_ + 1) % max_size_ ; - size_++ ; - - // One more enqueue operation has occured - nq_count_ ++ ; - // wakeup the sleeping consumers - not_empty_condition_.broadcast (); - return 0 ; - } - - - - - // Blockin dq -public synchronized Object dq() - { - // wait till the queue has something in it - while(is_empty()) - { - try { - wait(); - } catch (InterruptedException e) {} - } - - // dequeue here - Object return_object = queue_[front_] ; - front_ = (front_ + 1) % max_size_ ; - size_ -- ; - // One more enqueue operation has occured - dq_count_ ++ ; - //wake up the sleeping producers - notifyAll(); - return return_object ; - } - - - // Timed dq - -public synchronized Object dq(long msec_timeout) - { - // wait till the queue has something in it - try { - not_empty_condition_.timed_wait(msec_timeout); - } catch (InterruptedException e) {} - catch (TimeoutException t) - { - return null; - } - - // dequeue here - Object return_object = queue_[front_] ; - front_ = (front_ + 1) % max_size_ ; - size_ -- ; - - // One more enqueue operation has occured - dq_count_ ++ ; - - //wake up the sleeping guys - not_full_condition_.broadcast(); - return return_object ; - } - -public boolean is_empty() - { - if (size_ == 0) - return true ; - else - return false ; - - } - -public boolean is_full() - { - if (size_ == max_size_) - return true ; - else - return false ; - } - -} - - - - - diff --git a/java/apps/NexusII/src/MT_Bounded_Queue_Group.java b/java/apps/NexusII/src/MT_Bounded_Queue_Group.java deleted file mode 100644 index 734dc51a84b..00000000000 --- a/java/apps/NexusII/src/MT_Bounded_Queue_Group.java +++ /dev/null @@ -1,79 +0,0 @@ -//package NexusII.server; - -//import NexusII.util.*; -import java.util.*; - - -public class MT_Bounded_Queue_Group { - - public Vector q_group_ = new Vector(); - - public MT_Bounded_Queue_Group(int num) { - - q_group_ = new Vector(num); - - } - - public MT_Bounded_Queue_Group() { - - // q_group_ = new Vector(); - - } - - public String toString() { - - return q_group_.toString(); - - } - - // always returns true - public boolean addToGroup(MT_Bounded_Queue q) { - - q_group_.addElement(q); - return true; // for now - - } - - - // returns false if the q was not part of the group - public boolean delFromGroup(MT_Bounded_Queue q) { - - return q_group_.removeElement(q); - - } - - - public boolean checkInGroup(MT_Bounded_Queue q) { - - return q_group_.contains(q); - - } - - - // returns number of q's on which data was successfully enqueued - public int nq(Object o) { - - if(q_group_.isEmpty() ) - return 0; - - Enumeration e = q_group_.elements(); - - int i = 0; - while(e.hasMoreElements()) { - - MT_Bounded_Queue q = (MT_Bounded_Queue) e.nextElement(); - q.nq(o); - i++; - - } - - return i; - } - -} - - - - - - diff --git a/java/apps/NexusII/src/NexusClientApplet.java b/java/apps/NexusII/src/NexusClientApplet.java deleted file mode 100644 index 58b26930718..00000000000 --- a/java/apps/NexusII/src/NexusClientApplet.java +++ /dev/null @@ -1,494 +0,0 @@ -/* - $RCSfile$ - $Author$ - - Last Update: $Date$ - $Revision$ - - REVISION HISTORY: - $Log$ - Revision 1.1 1997/01/31 01:10:59 sumedh - Added the Nexus II source code files. - -# Revision 1.3 1996/12/06 07:25:29 rajeev -# Got SetRoomName to work -- needed for LROOMS -# -# Revision 1.2 1996/12/06 04:48:21 rajeev -# added handling for l_users and L_room packets from server -# -# Revision 1.1 1996/12/06 03:37:22 rajeev -# Initial revision -# - - This is the client applet - Part of Nexus-II project !! - Copyright : Aravind Gopalan, Rajeev Bector, Sumedh Mungee -*/ - -// package NexusII; - -// I hate packages - -import java.applet.Applet; -import java.awt.* ; -import java.io.*; -import java.net.*; -import java.util.*; - -//import NexusII.networking.* ; -//import NexusII.client.* ; -//import NexusII.util.* ; - -// get the awtCommand package now -import awtCommand.* ; - -// The applet runs the root thread -- easy access to graphics now ... - -public class NexusClientApplet extends CApplet implements consts,Runnable { - - // Who am I -- will be modified if the /nick command is given - public static String myName = new String("anonymous"); - - /* All Event Handlers */ - - // To check if applet is connected - boolean connected = false; - - // The connector handler - connectionHandler nexusConnector ; - - // join handler - joinHandler nexusJoiner ; - - // command handler - commandParser nexusParser ; - - commandHandler commandLineHandler ; - // Streams for writing and reading from Socket - DataOutputStream outStream; - DataInputStream inStream; - - // Thread which does everything for the applet - Thread mainThread ; - - // this is just a visit - // host where I live actually ;-) - String host; - - // Which server to connect to - Integer serverPort ; - - // Where are the queues for reading and writing - // reader and writers will access these and also the interpretor and dep. - - MT_Bounded_Queue read_q ; - MT_Bounded_Queue write_q ; - MT_Bounded_Queue root_q ; - // Where Aravind writes his commands - MT_Bounded_Queue command_q ; - - - - - // *********************************************************** - // Graphics objects - // *********************************************************** - - // Total applet size - int minWidth_ = 500; - int minHeight_ = 450; - - // State variables needed to be maintained - boolean connected_ = false; - int numRooms_ = 0; - - // Buttons - private CButton bConn; - private CButton bJoin; - private CButton bLeave; - private CButton bRooms; - private CButton bUsers; - - private CTextField tfCommandLine = new CTextField(80); - private CTextField tfRoomName = new CTextField(16); - private List lRooms = new List(10,false); - private Label roomLabel = new Label("Rooms:"); - private List lUsers = new List(10,false); - private Label userLabel = new Label("Users:"); - -// private RoomSpace roomspace = new RoomSpace(); - private Panel roomspace = new Panel(); - - public Dimension preferredSize() { - return minimumSize(); - } - - public Dimension minimumSize() { - return new Dimension(minWidth_, minHeight_); - } - - // ----------------------------------------------------------------- - // Basically draws up all the components (not sub-components) of the - // Applet window ... - // Pretty much straightforward barring quirks of AWT -- ArGo - void SetUpButtons(GridBagLayout gbl, GridBagConstraints gbc) { - // The Connect Button - gbc.weightx = 1.0; - gbc.weighty = 0.5; - gbc.gridx = 2; - gbc.gridy = 1; - gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.anchor = GridBagConstraints.CENTER; - gbc.ipady = 5; - bConn = new CButton("Connect"); - bConn.setActionCommand(nexusConnector); - gbl.setConstraints(bConn, gbc); - add(bConn); - gbc.ipady = 0; - - // The remaining buttons - gbc.fill = GridBagConstraints.BOTH; - gbc.anchor = GridBagConstraints.CENTER; - gbc.weightx = 1.0; - gbc.weighty = 0.5; - gbc.insets = new Insets(2,2,2,2); - gbc.ipadx = 2; - gbc.ipady = 2; - - // Join Button - gbc.gridx = 0; - gbc.gridy = 3; - bJoin = new CButton("Join"); - gbl.setConstraints(bJoin,gbc); - add(bJoin); - - // Leave Button - gbc.gridx = 1; - gbc.gridy = 3; - bLeave = new CButton("Leave"); - gbl.setConstraints(bLeave,gbc); - add(bLeave); - - // List Rooms Button - gbc.gridx = 0; - gbc.gridy = 4; - bRooms = new CButton("List Rooms"); - gbl.setConstraints(bRooms,gbc); - add(bRooms); - - // List Users Button - gbc.gridx = 1; - gbc.gridy = 4; - bUsers = new CButton("List Users"); - gbl.setConstraints(bUsers,gbc); - add(bUsers); - - } // of SetUpButtons - - void SetUpGraphics() { - - resize(preferredSize()); - - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints gbc = new GridBagConstraints(); - setFont(new Font("Helvetica", Font.PLAIN, 14)); - setLayout (gbl); - - gbc.weightx = 1.0; - gbc.weighty = 1.0; - - // For the list of rooms - // First the Room list label - gbc.weightx = 0; - gbc.weighty = 0; - gbc.gridx = 0; - gbc.gridy = 0; - gbc.anchor = GridBagConstraints.SOUTHWEST; - gbc.fill = GridBagConstraints.NONE; - gbl.setConstraints(roomLabel,gbc); - add(roomLabel); - // Now the Room combo -- list + text field - // the actual list - gbc.weightx = 1.0; - gbc.weighty = 1.0; - gbc.gridy = 1; - gbc.fill = GridBagConstraints.VERTICAL; - gbc.anchor = GridBagConstraints.NORTH; - // gbc.insets = new Insets(0,2,0,2); - gbl.setConstraints(lRooms,gbc); - add(lRooms); - if (DEBUG) - lRooms.addItem("Room_1"); - // The text field - gbc.weightx = 0; - gbc.weighty = 0; - gbc.gridy = 2; - gbc.anchor = GridBagConstraints.NORTH; - gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.insets = new Insets(0,0,0,0); - gbl.setConstraints(tfRoomName,gbc); - add(tfRoomName); - - // Similarly for the list of users - // label - gbc.weightx = 0; - gbc.weighty = 0; - gbc.gridx = 1; - gbc.gridy = 0; - gbc.anchor = GridBagConstraints.SOUTHWEST; - gbc.fill = GridBagConstraints.NONE; - gbc.insets = new Insets(0,0,0,0); - gbl.setConstraints(userLabel,gbc); - add(userLabel); - // The list - gbc.weightx = 1; - gbc.weighty = 1; - gbc.gridy = 1; - gbc.fill = GridBagConstraints.VERTICAL; - gbc.anchor = GridBagConstraints.NORTH; - gbl.setConstraints(lUsers,gbc); - add(lUsers); - if (DEBUG) - lUsers.addItem("USer #1"); - - // Setup all the buttons - SetUpButtons(gbl,gbc) ; - - // The command line - gbc.gridx = 0; - gbc.gridy = 5; - gbc.ipadx = 0; - gbc.ipady = 0; - gbc.insets = new Insets(0,0,0,0); - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbc.fill = GridBagConstraints.NONE; - gbc.anchor = GridBagConstraints.CENTER; - gbl.setConstraints(tfCommandLine,gbc); - add(tfCommandLine); - - - // We are done -- startup with all buttons except connect disabled - OnDisconnect(); - return; - } - - public void init() { - //Get the address of the host the applet was downloaded from - host = getCodeBase().getHost(); - // Get servers portnumber from the home page - serverPort = Integer.valueOf(getParameter("serverport")); - - - // Create the nexusconnector object whose execute will be called later - // on pressing the connect button - nexusConnector = new connectionHandler(host,serverPort,this); - - if(DEBUG){ - System.out.println("Server Portnumber is " + serverPort + "\n"); - } - - // initialize the graphics - SetUpGraphics(); - } // of method init - - public synchronized void start() { - // Aravind will create the "connect" button here and register an instance - - if (DEBUG) { - System.out.println("In start() method."); - } - } - - - // Here is the stop for the applet - // Called when the user goes away from the page - public synchronized void stop() { - if (!DEBUG) { - showStatus("Stop has been called "); - } - - if (connected) { - nexusConnector.execute(null,null,null); - } - } - - - - - // ----------------------------------------------------------------------- - // Public Access functions - public Hashtable Mapper() { - return nexusJoiner.Mapper(); - } - - public String GetRoomName() { - StringTokenizer t = new StringTokenizer(tfRoomName.getText()); - if(t.hasMoreTokens()) { - return t.nextToken(); - } - else - return "" ; - } - - public void AddRoomName(String name) { - int count = lRooms.countItems(); - for (int i=0;i<count;i++) - if (lRooms.getItem(i).equalsIgnoreCase(name)) - return; - lRooms.addItem(name); - } - - public void SetRoomName(String name) { - int count = lRooms.countItems(); - for(int i=0;i<count;i++) { - if(lRooms.getItem(i).equalsIgnoreCase(name)) { - // Have to simulate a select event by doing the selection ourselves - lRooms.select(i); - tfRoomName.setText(lRooms.getSelectedItem()); - tfRoomName.selectAll(); - break ; - } - } - } - - public void sendNickToServer(String name) { - nexusJoiner.sendTestPacket("ROOT","NICK",name,nexusConnector.writer_q()); - } - - - // will run the mainthread - public void run() { - if(DEBUG) { - System.out.println("Root thread is starting -- "); - } - - root_q = new MT_Bounded_Queue(QUEUE_SIZE); - nexusJoiner.Mapper().put("ROOT",root_q); - // continously wait for something to read and then update the graphics - // objects ---- - if(DEBUG) { - nexusJoiner.sendTestPacket("ROOT","LROOMS","a b c d",root_q); - } - - for(;;) { - dataPacket rootPacket = (dataPacket)root_q.dq(); - if(DEBUG) { - System.out.println("Root got a packet --- "); - } - if(rootPacket.contentType().equalsIgnoreCase("LROOMS")) { - update_lrooms(rootPacket.content()); - } - else if(rootPacket.contentType().equalsIgnoreCase("LUSERS")) { - update_lusers(rootPacket.destination(),rootPacket.content()); - } - } - - } - - - - // This method will update the graphics of lrooms - void update_lrooms(String data) { - lRooms.disable(); - tfRoomName.disable(); - lRooms.clear(); - - StringTokenizer t = new StringTokenizer(data); - while(t.hasMoreTokens()) { - lRooms.addItem(t.nextToken()); - } - if (lRooms.countItems() != 0) { - lRooms.select(0); - tfRoomName.setText(lRooms.getItem(0)); - } - tfRoomName.enable(); - lRooms.enable(); - repaint(); - } - - void update_lusers(String name,String data) { - lUsers.disable(); - userLabel.setText("Users: "+ name); - lUsers.clear(); - StringTokenizer t = new StringTokenizer(data); - while(t.hasMoreTokens()) { - lUsers.addItem(t.nextToken()); - } - lUsers.enable(); - repaint(); - } - - // ----------------------------------------------------------------------- - // User Input handling -- ArGo - - // Function to handle Connect button being pressed - public void OnConnect(){ - // Create the event handlers -- - nexusJoiner = new joinHandler(nexusConnector.writer_q(),this); - nexusParser = new commandParser(nexusConnector.writer_q(),this); - commandLineHandler = new commandHandler(this); - // start the main thread in the applets context - mainThread = new Thread(this); - mainThread.start(); - // test - // Graphics here -- - bJoin.enable(); - bJoin.setActionCommand(nexusJoiner); - bLeave.enable(); - bLeave.setActionCommand(nexusJoiner); - bRooms.enable(); - bRooms.setActionCommand(nexusParser); - bUsers.enable(); - bUsers.setActionCommand(nexusParser); - tfCommandLine.enable(); - tfCommandLine.setActionCommand(commandLineHandler); - tfRoomName.enable(); - lRooms.enable(); - lUsers.enable(); - // Change the name to "Disconnect" and ensure that update happens - bConn.setLabel("Disconnect"); - validate(); // Don't know if this is necessary - connected = true; // Applet is now connected - } - - // Function to handle Connect button being pressed - public void OnDisconnect(){ - bJoin.disable(); - bLeave.disable(); - bRooms.disable(); - bUsers.disable(); - tfCommandLine.disable(); - tfRoomName.disable(); - lRooms.disable(); - lUsers.disable(); - // Change the name back to "Connect" and ensure update happens - bConn.setLabel("Connect"); - validate(); - // Stop the ROOT room thread - if (connected) { - mainThread.stop(); - connected = false; // Applet is disconnected - } - } - - // Basically take care of the inputs - public boolean handleEvent(Event event) { - if (event.target == lRooms) { - if (event.id == Event.LIST_SELECT) { // selected the item - tfRoomName.setText(lRooms.getSelectedItem()); - tfRoomName.selectAll(); - if (DEBUG) - System.out.println("Actually handling the select event"); - return true; - } - } - return super.handleEvent(event); - } - - public void update(Graphics g) { - paint(g); - } -} // of class NexusClientApplet - - - diff --git a/java/apps/NexusII/src/NexusIIserver.java b/java/apps/NexusII/src/NexusIIserver.java deleted file mode 100644 index e3b5a52acd5..00000000000 --- a/java/apps/NexusII/src/NexusIIserver.java +++ /dev/null @@ -1,280 +0,0 @@ -// The Nexus II server. -// Sumedh Mungee <sumedh@cs.wustl.edu> - -import java.net.*; -import java.io.*; -import java.util.*; -import ACE.OS.*; -import ACE.SOCK_SAP.*; - -public class NexusIIserver implements consts { - - // Entry point into the server - public static void main(String args[]) throws IOException { - - if(args.length != 1) { - System.out.println("Usage: java NexusIIserver <port_num>"); - return; - } - - // Create a "Hotel", which is a factory to generate Rooms - // as and when required. - RoomFactory Hotel = new RoomFactory(); - - System.out.println("NexusII server booting"); - SOCKAcceptor sacceptor = new SOCKAcceptor( (new Integer(args[0])).intValue()); - - System.out.println("NexusII is now accepting connections on port " + (new Integer(args[0])).intValue()); - - for(;;) { - - SOCKStream s = new SOCKStream(); - sacceptor.accept(s); - // Accepted connection - // construct a client handler.. - // Pass in the connected socket as an argument, - // and a reference to the Hotel, in case it needs - // to create rooms.. - // and away you go.. - new Thread(new ClientHandler(s, Hotel)).start(); - - } - } -} - - -// This thread handles the clients.. -// It uses 2 additional threads for read/write network operations -// These threads are dedicated to read/write from the -// respective read/write queues.. -class ClientHandler implements Runnable,consts { - - private SOCKStream s_; - private RoomFactory Hotel_; - private MT_Bounded_Queue rq_ = new MT_Bounded_Queue(QUEUE_SIZE); - private MT_Bounded_Queue wq_ = new MT_Bounded_Queue(QUEUE_SIZE); - private String my_name_; - private Vector roomlist_ = new Vector(); - private boolean finished_ = false; - private String init_image_; - - public ClientHandler(SOCKStream s, RoomFactory h) { - s_ = s; - Hotel_ = h; - init_image_ = new String(System.getProperty("mywebaddress") + NEXUS_LOGO); - } - - public void run() { - // Construct the reader/writer threads with the queues and the - // corresponding socket data streams as parameters. - Thread r_ = new socketReaderThread(rq_, new DataInputStream(s_.inputStream())); - Thread w_ = new socketWriterThread(wq_, new DataOutputStream(s_.outputStream())); - r_.start(); - w_.start(); - - // now start parsing the messages, and take action.. - // todo: optimize the below.. - - while(!finished_) { - dataPacket d = (dataPacket) rq_.dq(); - if(d.contentType().startsWith("INIT")) - nexus_init(d); - if(d.contentType().startsWith("JOIN")) - nexus_join(d); - if(d.contentType().startsWith("LEAVE")) - nexus_leave(d); - if(d.contentType().startsWith("QUIT")) - nexus_quit(d); - if(d.contentType().startsWith("TEXT")) - nexus_text(d); - if(d.contentType().startsWith("LUSERS")) - nexus_lusers(d); - if(d.contentType().startsWith("LROOMS")) - nexus_lrooms(d); - if(d.contentType().startsWith("NICK")) - nexus_nick(d); - if(d.contentType().startsWith("URL")) - nexus_url(d); - } - } - - // The following classes implement the server functions.. - - private void nexus_init(dataPacket packet) { - my_name_ = new String(packet.clientName()); - wq_.nq(packet); - } - - private void nexus_join(dataPacket packet) { - Room r = Hotel_.getRoom(packet.content()); - if(r.checkClient(this)) - return; - r.addClient(this); - roomlist_.addElement(r); - writeRoom(r, my_name_ + " has joined the room "); - String contenttype = new String("url"); - dataPacket d = new dataPacket(my_name_, packet.content(), contenttype, (new Integer(init_image_.length())).toString() , init_image_); - wq_.nq(d); - } - - private void nexus_text(dataPacket packet) { - Room r = Hotel_.getRoom(packet.destination()); - r.getQ().nq(packet); - } - - private void nexus_lusers(dataPacket packet) { - - Room r = Hotel_.getRoom(packet.content()); - Enumeration e = r.clientList(); - StringBuffer sb = new StringBuffer(); - while(e.hasMoreElements()) - sb.append(" " + ((ClientHandler)e.nextElement()).getName() + " "); - dataPacket d = new dataPacket(my_name_, packet.destination(), packet.contentType(), (new Integer(sb.length())).toString(), sb.toString()); - wq_.nq(d); - } - - private void nexus_lrooms(dataPacket packet) { - String s = Hotel_.listRooms(); - dataPacket d = new dataPacket(my_name_, packet.destination(), packet.contentType(), (new Integer(s.length())).toString(), s.toString()); - wq_.nq(d); - } - - private void nexus_nick(dataPacket packet) { - Enumeration e = roomlist_.elements(); - while(e.hasMoreElements()) - writeRoom((Room)e.nextElement(), my_name_ + " is now known as " + packet.content()); - - my_name_ = new String(packet.content()); - } - - private void nexus_leave(dataPacket packet) { - - Room r = Hotel_.getRoom(packet.content()); - writeRoom(r, my_name_ + " has left the room " + packet.content()); - if(r.delClient(this)) Hotel_.delRoom(r); - roomlist_.removeElement(r); - } - - private void nexus_quit(dataPacket packet) { - - Enumeration e = roomlist_.elements(); - while(e.hasMoreElements()) { - Room r = (Room)e.nextElement(); - writeRoom(r, my_name_ + " has quit " ); - r.delClient(this); - } - finished_ = true; - } - - private void nexus_url(dataPacket packet) { - try { - URL u = new URL(packet.content()); - - // first extract the filename stripped of its path. - int index = u.getFile().lastIndexOf("/"); - String infilename = u.getFile().substring(index + 1); - - // next construct the name of the temporary file - String outfilename = (System.getProperty("mywebdir") + "_" + packet.destination() + "." + infilename); - - // now the temporary URL assigned to this request - String imageURL = new String(System.getProperty("mywebaddress") + "_" + packet.destination() + "." + infilename); - - // Open temporary file for writing - FileOutputStream fout = new FileOutputStream(outfilename); - - // Now contact alien ship - InputStream i = u.openStream(); - byte[] buffer = new byte[1024]; - - // And download the image - for(;;) { - int num = i.read(buffer); - if(num < 0) - break; - fout.write(buffer, 0, num); - } - - fout.close(); - i.close(); - - // Get room for which this request was issued - Room r = Hotel_.getRoom(packet.destination()); - - // invalidate previous entry - File f = new File(r.getLastImageName()); - if(f.exists()) f.delete(); - - // add new image name - r.putNextImageName(outfilename); - writeRoom(r,"Asynchronously transferring image " + packet.content() + " from " + my_name_ ); - dataPacket d = new dataPacket(my_name_, packet.destination(), packet.contentType(), (new Integer(imageURL.length())).toString(), imageURL); - r.getQ().nq(d); // multicast this imageURL onto the room.. - - } - catch(java.net.MalformedURLException ue) { - System.out.println("warning:Invalid URL requested"); - } - catch(java.io.IOException e) { - System.out.println("warning: IOException occurred"); - } - - } - - // Sends a "system" message msg onto room r - private void writeRoom(Room r, String msg) { - StringBuffer sb = new StringBuffer(); - sb.append("==>"); - sb.append(msg); - dataPacket d = new dataPacket(my_name_, r.getName() , "TEXT" , (new Integer(sb.length())).toString(), sb.toString()); - r.getQ().nq(d); - } - - public String getName() { - return my_name_; - } - - public MT_Bounded_Queue getQ() { - return wq_; - } - -} -// ---------------------------------------------------------------------- -/** This class implements a room factory. getRoom returns an existing room, - or else creates it and returns a reference to a new room. - -**/ -class RoomFactory implements consts { - - private Vector Hotel_; - public RoomFactory() { - Hotel_ = new Vector(); - } - public synchronized Room getRoom(String name) { - Enumeration e = Hotel_.elements(); - while(e.hasMoreElements()) { - Room r = (Room) e.nextElement(); - if(r.getName().equals(name)) - return r; - } - addRoom(name); - return getRoom(name); - } - - private synchronized void addRoom(String name) { - Room r = new Room(name); - Hotel_.addElement(r); - } - public synchronized void delRoom(Room r) { - Hotel_.removeElement(r); - } - public synchronized String listRooms() { - Enumeration e = Hotel_.elements(); - StringBuffer sb = new StringBuffer(); - while(e.hasMoreElements()) - sb.append(" " + ((Room)e.nextElement()).getName() + " "); - return sb.toString(); - } -} - - diff --git a/java/apps/NexusII/src/Producer.java b/java/apps/NexusII/src/Producer.java deleted file mode 100644 index 4153f7d79df..00000000000 --- a/java/apps/NexusII/src/Producer.java +++ /dev/null @@ -1,87 +0,0 @@ -// This class encapsulates a Producer. Each new instance of this class -// creates a different thread which tries to nq into the queue -// Currently queues random values generated by the Random class -// If timeout expires, the Producer instance returns - -//package NexusII.util ; - -import java.util.Random ; - -public class Producer extends Thread -{ - -// If no time out is desired, timeout value is set to one. so the run method -// knows which nq to call - -public Producer(MT_Bounded_Queue queue) - { - this.queue_ = queue ; - this.iterations_ = new Integer(DEFAULT_ITERATIONS); - this.time_out_ = -1 ; - } - -// Include the name of the thread as a parameter -public Producer(MT_Bounded_Queue queue, String name) - { - super(name); - this.queue_ = queue ; - this.iterations_ = new Integer(DEFAULT_ITERATIONS); - this.time_out_ = -1 ; - } - -// If the number of iterations are also included -- -public Producer(MT_Bounded_Queue queue, String name, Integer iterations) - { - super(name); - this.queue_ = queue ; - iterations_ = iterations ; - this.time_out_ = -1 ; - } - -// Finally, if the timeout period is also included - -public Producer(MT_Bounded_Queue queue, String name, Integer iterations, long msec_timeout) - { - super(name); - this.queue_ = queue ; - iterations_ = iterations ; - this.time_out_ = msec_timeout ; - } - -// The hook method called by start() - -public void run() - { - // Initialize the random number generator - Random rand = new Random(); - for(int i=0;i<iterations_.intValue();i++) - { - int err = 0 ; - // Get the next random value for insertion into queue - Integer new_item = new Integer(rand.nextInt()) ; - - // Doesnt make sense to have a negative timeout -- default - if(time_out_ < 0) - queue_.nq(new_item); - else - err = queue_.nq(new_item,time_out_); - - // If timedout stop this thread - if(err == -1) - { - System.out.println(getName() + ": Timed Out \n"); - return ; - } - - System.out.println(getName() + ": enqueued " + new_item.intValue()); - } - - } - -private static final int DEFAULT_ITERATIONS = 1 ; -protected MT_Bounded_Queue queue_ ; -private Integer iterations_ ; -private long time_out_ ; -} - - diff --git a/java/apps/NexusII/src/Room.java b/java/apps/NexusII/src/Room.java deleted file mode 100644 index 4a9a294c653..00000000000 --- a/java/apps/NexusII/src/Room.java +++ /dev/null @@ -1,97 +0,0 @@ -// RoomThread and Room implement the concept of a chat "room" -// Sumedh Mungee <sumedh@cs.wustl.edu> - - -import java.util.*; -import java.io.File; - -// This class(&thread) is responsible for multicasting -// packets on its incoming "client" queues, onto one or -// more outgoing queues, which are picked up by the client. -class RoomThread implements Runnable, consts { - - private MT_Bounded_Queue rq_; - private Vector clientlist_; - - public RoomThread(MT_Bounded_Queue rq, Vector clientlist) { - rq_ = rq; - clientlist_ = clientlist; - } - - public void run() { - for(;;) { - dataPacket d = (dataPacket) rq_.dq(); // Extract packet - Enumeration e = clientlist_.elements(); // Iterate over clients - while(e.hasMoreElements()) - ((ClientHandler)e.nextElement()).getQ().nq(d); // Enqueue packet - } - } -} - - -public class Room implements consts { - - private String name_; // name of this "room" - private String last_image_ = new String("NexusII.gif"); // filename of the last image broadcast - private Thread roomthread_; - private MT_Bounded_Queue rq_ = new MT_Bounded_Queue(); - private Vector clientlist_ = new Vector(); - - // Constructors - public Room(String name) { - int i; - name_ = new String(name); - roomthread_ = new Thread(new RoomThread(rq_, clientlist_)); - roomthread_.start(); - } - - // Client management methods follow.. - - public synchronized void addClient(ClientHandler client) { - clientlist_.addElement(client); - } - // Returns true if this room has now become empty - public synchronized boolean delClient(ClientHandler client) { - clientlist_.removeElement(client); - return clientlist_.isEmpty(); - } - - public synchronized boolean checkClient(ClientHandler client) { - return clientlist_.contains(client); - } - - public synchronized Enumeration clientList() { - return clientlist_.elements(); - } - - public String getName() { - return name_; - } - - public MT_Bounded_Queue getQ() { - return rq_; - } - - public synchronized String getLastImageName() { - return last_image_; - } - - public synchronized void putNextImageName(String s) { - last_image_ = s; - } - - protected void finalize() { - roomthread_.stop(); - File f = new File(last_image_); - if(f.exists()) - f.delete(); - roomthread_ = null; - } -} - - - - - - - diff --git a/java/apps/NexusII/src/RoomFrame.java b/java/apps/NexusII/src/RoomFrame.java deleted file mode 100644 index e9da19b31d6..00000000000 --- a/java/apps/NexusII/src/RoomFrame.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - $RCSfile$ - $Author$ - - Last Update: $Date$ - $Revision$ - - REVISION HISTORY: - $Log$ - Revision 1.1 1997/01/31 01:11:02 sumedh - Added the Nexus II source code files. - -# Revision 1.2 1996/12/07 06:25:18 rajeev -# backup -# -# Revision 1.1 1996/12/07 06:15:12 rajeev -# Initial revision -# - - -*/ -import java.awt.*; -import awtCommand.*; -import java.util.* ; - -//import NexusII.client.* ; -//import NexusII.util.* ; -//import NexusII.networking.*; - -class RoomFrame extends CFrame implements consts { - private static String rcsId = new String("$Id$"); - - // Graphics Objects - private CTextField tfInput ; - private CTextArea taOutput ; - private CButton bLeave ; - private ImageCanvas icOutput; - private Font normalFont = new Font("Helvetica", Font.PLAIN, 14); - private Font boldFont = new Font("Helvetica", Font.BOLD, 14); - private Font italicFont = new Font("Helvetica", Font.ITALIC, 14); - private static final int LINE_LENGTH = 70; - - // Other required objects - private MT_Bounded_Queue write_q_ ; - private NexusClientApplet applet_ ; - private String myName_ ; - - public RoomFrame(MT_Bounded_Queue write_q, - NexusClientApplet applet, - String name) { - super(name); - write_q_ = write_q ; - applet_ = applet ; - myName_ = name ; - SetUpGraphics(); - this.pack(); - this.show(); - } - - void SetUpGraphics() { - // Initialize the graphics objects - // The input text line - tfInput = new CTextField(LINE_LENGTH); - textHandler handlerT = new textHandler(write_q_,applet_,myName_); - tfInput.setActionCommand(handlerT); - // The leave button - bLeave = new CButton(LEAVE_STR); - bLeave.setActionCommand(applet_.nexusJoiner); - - icOutput = new ImageCanvas(myName_); - taOutput = new CTextArea(10,LINE_LENGTH); - - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints gbc = new GridBagConstraints(); - setFont(normalFont); - setLayout (gbl); - - gbc.insets = new Insets(5,5,5,5); - gbc.ipadx = 5; - gbc.ipady = 5; - gbc.weightx = 1.0; - gbc.weighty = 1.0; - - // First the Image so that sizes are fixed - gbc.gridx = 1; - gbc.gridy = 0; - gbc.anchor = GridBagConstraints.CENTER; - gbc.fill = GridBagConstraints.BOTH; - gbl.setConstraints(icOutput, gbc); - add(icOutput); - - // The Text Output Area - gbc.gridx = 0; - gbc.gridy = 0; - gbc.weighty = 0.0; - gbc.anchor = GridBagConstraints.SOUTH; - gbc.fill = GridBagConstraints.BOTH; - gbl.setConstraints(taOutput,gbc); - taOutput.setEditable(false); - add(taOutput); - - // The Text Input Field - gbc.gridx = 0; - gbc.gridy = 1; - gbc.weighty = 0.0; - gbc.anchor = GridBagConstraints.NORTH; - gbc.fill = GridBagConstraints.HORIZONTAL; - gbl.setConstraints(tfInput,gbc); - add(tfInput); - - // The Leave Button - gbc.gridx = 1; - gbc.gridy = 1; - gbc.anchor = GridBagConstraints.NORTH; - gbc.fill = GridBagConstraints.HORIZONTAL; - gbl.setConstraints(bLeave,gbc); - add(bLeave); - - resize(800,280); - setResizable(true); // Allow the user to resize - validate(); - } - - public boolean handleEvent(Event event) { - if (event.id == Event.WINDOW_DESTROY) - dispose(); - return super.handleEvent(event); - } - - // This function will be called by the RoomHandler when it receives - // anything for this room and will add the data - public void addText(String tobeadded) { - if (false) { - String speaker = null; - String msg = null; - int pos = tobeadded.indexOf(':'); - if (pos >= 0) - speaker = tobeadded.substring(0,pos+1); - else - speaker = new String(""); - msg = tobeadded.substring(pos+1); - Font oldf = taOutput.getFont(); - taOutput.setFont(boldFont); - taOutput.appendText(speaker); - taOutput.setFont(italicFont); - taOutput.appendText(msg+"\n"); - taOutput.setFont(oldf); - } - else { - taOutput.appendText(tobeadded+"\n"); - } - return; - } - - // This function will also be called by the RoomHandler whenit receives - // Image data for this room. - public void updateImage(Image im) { - if(DEBUG) { - System.out.println("Room : I got an image"); - } - icOutput.setImage(im); - } - - -} - - - -/** - * The ImageCanvas Class -- for the image in the class - */ -class ImageCanvas extends Canvas implements consts { - - Image image_ = null; - int defWidth_ = 128; - int defHeight_ = 128; - int margin = 5; - - String name_ = new String("Nexus Room"); - Font nameFont = new Font("Helvetica",0,14); - - public ImageCanvas(String s) - { - name_ = s; - } - - public Dimension preferredSize() { - return minimumSize(); - } - public Dimension minimumSize() { - return new Dimension(defWidth_, defHeight_); - } - - public void setImage(Image newIm) { - image_ = newIm; - repaint(); - } - public Image getImage() { - return image_; - } - - public void name(String n) { - name_ = n; - } - public String name() { - return name_; - } - - public void paint(Graphics g) { - Dimension d = size(); - int width = d.width; - int height = d.height; - - if (DEBUG) - System.out.println("ImageCanvas:: width = "+width+ " height="+height); - - g.setColor(Color.black); - g.fillRect(0,0,width-1,height-1); - g.setColor(Color.white); - g.fillRect(margin,margin,width-2*margin,height-2*margin); - // Create image if reqd - if (image_ == null) - image_ = createImage(width-2*margin,height-2*margin); - - g.drawImage(image_, margin, margin, - width-2*margin, height-2*margin, Color.white, this); - g.setColor(Color.blue); - g.setFont(nameFont); - FontMetrics fm = g.getFontMetrics(); - g.drawString(name_,(width - fm.stringWidth(name_))/2, - (int)(height*0.9 - fm.getMaxDescent())); - validate(); - return; - } - - public void update(Graphics g) { - paint(g); - } - -} // End of the Image Canvas Class - - - -// this is the event handler for the textfield -- whenever anything is typed -class textHandler implements Command,consts,Runnable { - private MT_Bounded_Queue write_q_ ; - private NexusClientApplet applet_ ; - private String name_ ; - Object what_ ; - - public textHandler(MT_Bounded_Queue write_q, - NexusClientApplet applet, - String name) { - write_q_ = write_q ; - applet_ = applet ; - name_ = name ; - } - - public void execute(Object target, Event evt, Object what) { - // get the string and send it across in a different thread - what_ = what ; - // clear the field in the gui - ((TextField)target).setText(""); - // send it off - new Thread(this).start(); - } - - // send off the string in a different thread - public void run() { - String data = (String)what_; - // check if data begins with / and is followed by url - if(!data.startsWith("/url")) { - - String user = NexusClientApplet.myName ; - String command = user + ":" + data ; - String len = Integer.toString(command.length()); - dataPacket packet = new dataPacket(NexusClientApplet.myName,name_, - "TEXT",len,command); - write_q_.nq(packet); - } - else { - // it is /url - StringTokenizer t = new StringTokenizer(data); - // take out the /url from here - String ur = t.nextToken(); - // data now - String command = t.nextToken(); - String len = Integer.toString(command.length()); - dataPacket packet = new dataPacket(NexusClientApplet.myName,name_, - "URL",len,command); - write_q_.nq(packet); - } - } -} // end of class - - - diff --git a/java/apps/NexusII/src/RoomSpace.java b/java/apps/NexusII/src/RoomSpace.java deleted file mode 100644 index 9afb78ddff1..00000000000 --- a/java/apps/NexusII/src/RoomSpace.java +++ /dev/null @@ -1,110 +0,0 @@ -import java.awt.*; - -class RoomFrame extends Frame // implements Runnable -{ - - // Graphics Objects - private Panel panel = new Panel(); - private TextField tfInput = new TextField(80); - private TextArea taOutput = new TextArea(80,10); - Button bLeave = new Button("Leave"); - ImageCanvas icOutput = new ImageCanvas(); - - void InitGraphics() - { - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints gbc = new GridBagConstraints(); - setFont(new Font("Helvetica", Font.PLAIN, 14)); - panel.setLayout (gbl); - - gbc.weightx = 1.0; - gbc.weighty = 1.0; - - // First the Image so that sizes are fixed - gbc.gridx = 1; - gbc.gridy = 0; - gbc.anchor = GridBagConstraints.CENTER; - gbc.fill = GridBagConstraints.NONE; - gbl.setConstraints(icOutput, gbc); - panel.add(icOutput); - - // The Text Output Area - gbc.gridx = 0; - gbc.gridy = 0; - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.HORIZONTAL; - gbl.setConstraints(taOutput,gbc); - taOutput.setEditable(false); - panel.add(taOutput); - - // The Text Input Field - gbc.gridx = 0; - gbc.gridy = 1; - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.HORIZONTAL; - gbl.setConstraints(tfInput,gbc); - panel.add(tfInput); - - // The Leave Button - gbc.gridx = 1; - gbc.gridy = 1; - gbc.anchor = GridBagConstraints.WEST; - gbc.fill = GridBagConstraints.HORIZONTAL; - gbl.setConstraints(bLeave,gbc); - panel.add(bLeave); - } - - - public RoomFrame() - { - this("Anonymous"); - } - - public RoomFrame(String s) - { - InitGraphics(); - super(s); - this.pack(); - this.show(); - } - - public boolean handleEvent(Event event) - { - if (event.id == Event.WINDOW_DESTROY) - dispose(); - return super.handleEvent(event); - } - -} - -class ImageCanvas extends Canvas { - - Image image_; - int imgWidth_ = 128; - int imgHeight_ = 128; - - public Dimension preferredSize() { - return minimumSize(); - } - - public Dimension minimumSize() { - return new Dimension(imgWidth_, imgHeight_); - } - - public void image(Image newIm) { - image_ = newIm; - } - - public Image image() { - return image_; - } - - public void paint(Graphics g) { - g.drawImage(image_,0,0,this); - } - - public void update() { - paint(); - } - -} // End of the Image Canvas Class diff --git a/java/apps/NexusII/src/Timed_Wait.java b/java/apps/NexusII/src/Timed_Wait.java deleted file mode 100644 index 792db39ceb9..00000000000 --- a/java/apps/NexusII/src/Timed_Wait.java +++ /dev/null @@ -1,86 +0,0 @@ -// package NexusII.util ; - - -// Subclass the Exception class to get TimeoutException - -class TimeoutException extends Exception -{ - public TimeoutException() - { - super(); - } - - public TimeoutException(String s) - { - super(s); - } - -} - -// Timed_wait class. This can used by enq and deq to do timed_waits -public abstract class Timed_Wait -{ - // By default the object is itself -public Timed_Wait () - { - object_ = this; - } - // If the calling class specifies objects, delegate to it. -public Timed_Wait (Object obj) - { - object_ = obj; - } - - // This is the object we delegate to if a - // subclass gives us a particular object, - // otherwise, we ``delegate'' to ourself - // (i.e., to this). -protected Object object_; - - // This hook method must be overridden - // by a subclass to provide the condition. - -public abstract boolean condition (); - - // This will borrow the monitor lock from the calling class - -public final void timed_wait(long msec_timeout) -throws InterruptedException, TimeoutException - { - // wait if the condition is false - if (!condition()) - { - long start = System.currentTimeMillis() ; - long wait_time = msec_timeout ; - - for(;;) - { - // anyway have to wait atleast till waittime - object_.wait(wait_time); - - // on coming out check for the condition again - if(!condition()) - { - long now = System.currentTimeMillis() ; - long time_so_far = now - start ; - - // if timed out - if(time_so_far >= msec_timeout) - throw new TimeoutException() ; - else - // retry !! we have some time left - wait_time = msec_timeout - time_so_far ; - } - else // the condition is true here - break ; - } - } - } - - // Notify all threads waiting on the object_. -public final void broadcast () - { - object_.notifyAll (); - } -} - diff --git a/java/apps/NexusII/src/Timer.java b/java/apps/NexusII/src/Timer.java deleted file mode 100644 index df781274913..00000000000 --- a/java/apps/NexusII/src/Timer.java +++ /dev/null @@ -1,31 +0,0 @@ -// This class encapsulates a Timer mechanism -// Can be used for Profiling of parts of code and gathering statistics - -package NexusII ; - -public class Timer { - -public Timer() -{ - start_ = 0 ; -} - -public void start() - -{ - start_ = System.currentTimeMillis(); -} - -public long elapsed_time() -{ - return System.currentTimeMillis() - start_ ; -} - -public void stop() -{ - start_ = 0 ; -} - -private long start_ = 0 ; - -} diff --git a/java/apps/NexusII/src/commandHandler.java b/java/apps/NexusII/src/commandHandler.java deleted file mode 100644 index 4cf80d04235..00000000000 --- a/java/apps/NexusII/src/commandHandler.java +++ /dev/null @@ -1,44 +0,0 @@ -// To handle the events generated by command-line. The user will be saying -// /nick <nick-name> - -import java.awt.* ; -import java.util.* ; - -//import NexusII.client.* ; - -import awtCommand.* ; - - -public class commandHandler implements Command,consts { - NexusClientApplet applet_ ; - // will handle the /nick command for now -- urgent - public commandHandler(NexusClientApplet applet ) { - applet_ = applet ; - } - - public void execute(Object target,Event evt,Object what) { - // Right now assume that it is just a nick command - if(DEBUG) { - System.out.println("Nick typed in ---- "); - } - StringTokenizer t = new StringTokenizer((String)what) ; - // string for holding /nick and <nickname> - String command = null ; - if(t.hasMoreTokens()) { - command = t.nextToken(); - } - - if(command.equalsIgnoreCase("/nick")) { - if(t.hasMoreTokens()) { - // have to send a nick packet to server - applet_.myName = new String(t.nextToken()); - applet_.sendNickToServer(applet_.myName); - - } - } - // clear the field in the gui - ((TextField)target).setText(""); - - } -} -// of class diff --git a/java/apps/NexusII/src/commandParser.java b/java/apps/NexusII/src/commandParser.java deleted file mode 100644 index 64e6da66122..00000000000 --- a/java/apps/NexusII/src/commandParser.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - $RCSfile$ - $Author$ - - Last Update: $Date$ - $Revision$ - - REVISION HISTORY: - $Log$ - Revision 1.1 1997/01/31 01:11:06 sumedh - Added the Nexus II source code files. - -# Revision 1.1 1996/12/07 06:27:38 rajeev -# Initial revision -# -# Revision 1.1 1996/12/02 06:05:08 rajeev -# Initial revision -# -# Revision 1.1 1996/12/02 06:02:24 rajeev -# Initial revision -# - -*/ -// why not use java utilities !! - -import java.util.* ; -import java.lang.* ; -import java.awt.* ; - - - -//import NexusII.client.* ; -//import NexusII.util.* ; -//import NexusII.networking.* ; - - - -import awtCommand.* ; - -// This class takes a command parses it and packetizes it and puts it in the -// global send queue. It works in its own thread of control and after nqing -// its run() method falls off. It does its work and dies -// Will act as an eventHandler for TextField most probably - -public class commandParser implements Command,consts,Runnable { - - String command ; - MT_Bounded_Queue q_ ; - NexusClientApplet applet_ ; - // constructor - - public commandParser(MT_Bounded_Queue write_q,NexusClientApplet applet) { - // create a reference to the write_q - q_ = write_q ; - // note the applet name - applet_ = applet ; - - } - - - public void execute(Object target, Event evt, Object what) { - // Get the text which was entered there -- - command = new String((String) what) ; - // run in a separate thread - Thread main = new Thread(this); - main.start(); - } - - // The parser etc. run here - public synchronized void run() { - String actual_command = new String(); - String data = new String(); - String data_len = new String(); - if(DEBUG) { - System.out.println("commandParser thread running --- \n"); - } - - // Do the parsing first - if(command.equalsIgnoreCase(LUSERS_STR)) { - actual_command = new String("LUSERS") ; - data = applet_.GetRoomName() ; - data_len = new String(String.valueOf(data.length())); - if(data.length() == 0) - return ; - } - - else if(command.equalsIgnoreCase(LROOMS_STR)) { - actual_command = new String("LROOMS") ; - data = new String("") ; - data_len = new String("0") ; - } - - String room = new String("ROOT"); - - if(DEBUG) { - System.out.println("The room is " + room + "\n"); - } - - /* - StringBuffer databuffer = new StringBuffer(); - - // Get the data - while(t.hasMoreTokens()) { - databuffer.append(t.nextToken()); - } - String data = new String(databuffer); - if(DEBUG) { - System.out.println("The data is " + data + "\n"); - } - - // data length - String data_len = String.valueOf(data.length()); - // Now make a packet - */ - - dataPacket pack = new dataPacket(NexusClientApplet.myName,room,actual_command,data_len,data); - // enqueue it now - q_.nq(pack); - - } // my job is over - -} -// of class - diff --git a/java/apps/NexusII/src/connectionHandler.java b/java/apps/NexusII/src/connectionHandler.java deleted file mode 100644 index 5e9d3823a68..00000000000 --- a/java/apps/NexusII/src/connectionHandler.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - $RCSfile$ - $Author$ - - Last Update: $Date$ - $Revision$ - - REVISION HISTORY: - $Log$ - Revision 1.1 1997/01/31 01:11:07 sumedh - Added the Nexus II source code files. - -# Revision 1.1 1996/12/07 06:27:38 rajeev -# Initial revision -# -# Revision 1.1 1996/12/02 06:05:30 rajeev -# Initial revision -# -# Revision 1.1 1996/12/02 06:02:24 rajeev -# Initial revision -# - -*/ -// This class will handle the event generated when user presses "connect/dis -// connect" button. It will maintain all the state associated with a -// connection ; -// In particular, it will create reader,writer and demux threads and stop -// them when user pressed disconnect. It also sends the init and quit -// packet to the server -// -- Rajeev Bector 11/26/96 - -// package NexusII.networking ; - -import awtCommand.* ; - -import java.net.* ; -import java.awt.* ; -import java.io.* ; -import java.util.* ; -import ACE.OS.*; -import ACE.SOCK_SAP.*; - -public class connectionHandler implements Command,consts,Runnable { - - // The socket for reading and writing - // private Socket nexusSocket; - private SOCKConnector nexusConnector_ = new SOCKConnector(); - private SOCKStream nexusStream_ = new SOCKStream(); - - // Threads which will do reading and writing from Socket - private Thread readerThread ; - private Thread writerThread ; - - // Threads which demuxes the data from Write Queue - private Thread demuxThread; - - // The socket - // private Socket nexusSocket_ ; - - // Data Streams which flow the data out - private DataInputStream is_ ; - private DataOutputStream os_ ; - - // links to the outside world - private MT_Bounded_Queue read_q_ ; - private MT_Bounded_Queue write_q_ ; - - Integer port_ ; - String host_ ; - - NexusClientApplet applet_ ; - // Constructor - public connectionHandler(String host,Integer port,NexusClientApplet applet) { - host_ = host ; - port_ = port ; - applet_ = applet ; - } // of constructor - - // This will be called when the "connect/disconnet" button is pressed - - public void execute(Object target, Event evt, Object what) { - // run in a separate thread - new Thread(this).start(); - } - - public synchronized void run() { - - // If not connected -- then connect - if(!applet_.connected) { - - // Initialize the queues now - read_q_ = new MT_Bounded_Queue(QUEUE_SIZE); - write_q_ = new MT_Bounded_Queue(QUEUE_SIZE); - - // Try to connect to the server now - // nexusSocket_ = new Socket(host_,port_.intValue()); - try { - nexusConnector_.connect(nexusStream_, host_, port_.intValue()); - } - catch(SocketException s) { } - catch(IOException i) { } - // Attach Streams to read and write end os socket - os_ = new DataOutputStream(nexusStream_.outputStream()); - is_ = new DataInputStream(nexusStream_.inputStream()); - - // do something now - - // create and start the socket reader first - readerThread = new socketReaderThread(read_q_,is_); - readerThread.start(); - - // now create the writer also -- subclass of consumer - writerThread = new socketWriterThread(write_q_,os_); - writerThread.start(); - // Have to send the init packet to the server - sayHelloToServer(); - - - // Do all the graphics needed and also init the join handlers etc. - applet_.OnConnect(); - - // make sure that when demux is created -- joinHandler is there ... !! - - // Create the demux here -- he'll spawn off the rooms - demuxThread = new nexusDemuxThread(read_q_,applet_.Mapper()); - demuxThread.start(); - - } // of if !connected - - // if connected already then I have to disconnect --- have to - // write code for this - else { - - // first leave all the rooms - for(Enumeration e = applet_.Mapper().keys(); e.hasMoreElements();) { - String name = (String) e.nextElement() ; - applet_.SetRoomName(name); - applet_.nexusJoiner.execute(null,null,LEAVE_STR); - } - // send a quit packet to the server - sayByeToServer(); - - // Have to send a leave for all the rooms and leave all the rooms - - // stop the running threads - readerThread.stop(); - demuxThread.stop(); - - // Again meddle with graphics - applet_.OnDisconnect(); - return ; - } - } // of run - - // This method returns the underlying socket descriptor - public Socket handle() { - return nexusStream_.socket(); - } - - public DataInputStream getinStream() { - return is_ ; - } - - public DataOutputStream getoutStream() { - return os_ ; - } - - public MT_Bounded_Queue reader_q() { - return read_q_ ; - } - - - public MT_Bounded_Queue writer_q() { - if(write_q_ == null) - System.out.println("Sending a null write_q"); - return write_q_ ; - } - - // This method will compose a hello packet and send it off -- cannot run - // this in a separate thread. Has to send this first surely to our TCP - // Connection - - public void sayHelloToServer() { - // hello doesnt have any body - byte[] packetHeader = new byte[PACKET_HEADER_LENGTH] ; - String clientID = new String(NexusClientApplet.myName); - String roomID = new String("ROOT"); - String contentType = new String("INIT"); - String contentLength = new String("0"); - - // Make a proper packet out of it - dataPacket initPacket = new dataPacket(clientID,roomID,contentType,contentLength); - - // enqueue that packet for socketWriter to read - write_q_.nq(initPacket); - - } - - // This method send a Quit command to the server -- to say that it is - // pushing off - public void sayByeToServer() { - byte[] packetHeader = new byte[PACKET_HEADER_LENGTH] ; - String clientID = new String(NexusClientApplet.myName); - String roomID = new String("null"); - String contentType = new String("QUIT"); - String contentLength = new String("0"); - - // Make a proper packet out of it - dataPacket quitPacket = new dataPacket(clientID,roomID,contentType,contentLength); - - // enqueue that packet for socketWriter to read - write_q_.nq(quitPacket); - } // of sayByeToServer - -} // of class - - - - - - - - - - - - - - - - - - - - - diff --git a/java/apps/NexusII/src/consts.java b/java/apps/NexusII/src/consts.java deleted file mode 100644 index 304ec41a41e..00000000000 --- a/java/apps/NexusII/src/consts.java +++ /dev/null @@ -1,40 +0,0 @@ -// package NexusII.client ; - -// An interface for all the public constants shared by clientApplet -// All classes that need to access constants will implement this - -public interface consts { - // Length of each field in the header - public static final int FIELD_LENGTH = 32 ; - - // Total length of header - public static final int PACKET_HEADER_LENGTH = 128; - - // Offset where we can find the data length - public static final int DATA_LEN_OFFSET = 96; - - // Size of Queues where reader and writer work - public static final int QUEUE_SIZE = 20 ; - - // Separator used by tokens in the packet - public static final String SEPARATOR = " " ; - - // End of message - public static final String END_OF_DATA = "\n" ; - - // Useful for debugging -- set to false for release version (demo) -- Aravind - public static final boolean DEBUG = false; - - // Size of hash tables - public static final int HASH_SIZE = 16 ; - - public static final String JOIN_STR = "Join" ; - public static final String LEAVE_STR = "Leave" ; - public static final String LUSERS_STR = "List Users" ; - public static final String LROOMS_STR = "List Rooms" ; - - public static final int SERVER_PORT = 42429 ; - public static final String NEXUS_LOGO = "Nexus_Logo.gif"; -} - - diff --git a/java/apps/NexusII/src/dataPacket.java b/java/apps/NexusII/src/dataPacket.java deleted file mode 100644 index 1bd2dfeb6ab..00000000000 --- a/java/apps/NexusII/src/dataPacket.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - $RCSfile$ - $Author$ - - Last Update: $Date$ - $Revision$ - - REVISION HISTORY: - $Log$ - Revision 1.1 1997/01/31 01:11:08 sumedh - Added the Nexus II source code files. - -# Revision 1.2 1996/12/07 06:27:38 rajeev -# yaah paranoid backup ... -# -# Revision 1.1 1996/12/06 18:23:45 rajeev -# Initial revision -# -# Revision 1.1 1996/12/02 06:07:53 rajeev -# Initial revision -# -# Revision 1.1 1996/12/02 06:02:24 rajeev -# Initial revision -# - -*/ -// This class encapsulates a dataPacket -// Will encapsulate the byteStream as a characterStream into a single thing -// no packets for now -// package NexusII.networking ; - -//import NexusII.client.* ; - -public class dataPacket implements consts, Cloneable{ - - private String clientName ; - private String roomName ; - private String contentType ; - private String contentLength ; - private String content ; - - // constructor -- will create the data packet - public dataPacket(byte[] header, byte[] body) { - int len = FIELD_LENGTH ; - clientName = new String(header,0,0,len); - roomName = new String(header,0,1*len,len); - contentType = new String(header,0,2*len,len); - contentLength = new String(header,0,3*len,len); - content = new String(body,0); - if(DEBUG) - System.out.println("datapacket: Constructed packet with header " + header + " and body " + body); - } - - // another constructor for length 0 packets - public dataPacket(String client, String room, String type,String len) - { - clientName = new String(client); - roomName = new String(room); - contentType = new String(type); - contentLength = new String(len); - content = new String(); - } - - // another one for some data also - public dataPacket(String client, String room, String type,String len,String data) - { - this(client,room,type,len); - content = new String(data); - } - - // return the data in bytized header and body - public void bytize(byte[] header, byte[] body) - { - // clear the header and body -- fill them with whitespace - String white_space = new String(" "); - - if(DEBUG) { - System.out.println("dataPacket: length is " + new Integer(contentLength.trim()).intValue() + "\n"); - } - - int len = FIELD_LENGTH ; - // copy the header - clientName.getBytes(0,clientName.length(),header,0); - roomName.getBytes(0,roomName.length(),header,len*1); - contentType.getBytes(0,contentType.length(),header,len*2); - contentLength.getBytes(0,contentLength.length(),header,len*3); - - int body_len = (new Integer(contentLength.trim())).intValue(); - // copy the body also - content.getBytes(0,body_len,body,0); - } - - public int contentLength() { - return new Integer(contentLength.trim()).intValue(); - } - - // Returns the destination for the current packet - public String destination(){ - return roomName.trim() ; - } - - public String contentType() { - return contentType.trim() ; - } - - - public String content() { - return content.trim() ; - } - - public String clientName() { - return clientName.trim() ; - } - -} -// of class datapacket - - - - - - - - diff --git a/java/apps/NexusII/src/joinHandler.java b/java/apps/NexusII/src/joinHandler.java deleted file mode 100644 index 3ff071c26ed..00000000000 --- a/java/apps/NexusII/src/joinHandler.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - $RCSfile$ - $Author$ - - Last Update: $Date$ - $Revision$ - - REVISION HISTORY: - $Log$ - Revision 1.1 1997/01/31 01:11:09 sumedh - Added the Nexus II source code files. - -# Revision 1.1 1996/12/07 06:27:38 rajeev -# Initial revision -# -# Revision 1.1 1996/12/02 06:06:22 rajeev -# Initial revision -# -# Revision 1.1 1996/12/02 06:02:24 rajeev -# Initial revision -# - -*/ - -// This class will handle the event generated when user presses "join/leave" -// button. It will maintain all the state associated with all the rooms -// It'll also create and maintain the rooms -// -- Rajeev Bector 11/26/96 - -// package NexusII.networking ; - -// This is a SINGLETON - - -import java.net.* ; -import java.util.* ; -import java.awt.* ; -import java.io.* ; - - -//import NexusII.client.* ; -//import NexusII.util.* ; -//import NexusII.networking.* ; - -import awtCommand.* ; - -public class joinHandler implements Command,consts { - MT_Bounded_Queue write_q_ ; - Hashtable name_to_q_ ; - Hashtable name_to_handler_ ; - NexusClientApplet applet_ ; - - // This will be called when the "join/leave" button is pressed - public joinHandler(MT_Bounded_Queue writer_q,NexusClientApplet applet) { - write_q_ = writer_q ; - applet_ = applet ; - // init. the Hashtables - name_to_q_ = new Hashtable(HASH_SIZE); - name_to_handler_ = new Hashtable(HASH_SIZE); - - } - - public Hashtable Mapper() { - return name_to_q_ ; - } - - public void execute(Object target, Event evt, Object what) { - - String roomName = applet_.GetRoomName() ; - if(roomName.length()==0) { - return ; - } - - // if it is the join button - if(((String)what).equalsIgnoreCase(JOIN_STR)) { - //if already joined -- return - if(name_to_q_.get(roomName) != null) - return ; - - // room doesnt exist - // Just in case the room name isn't listed - applet_.AddRoomName(roomName); - // create a new queue for the room to use - - MT_Bounded_Queue q_ = new MT_Bounded_Queue(QUEUE_SIZE); - if(DEBUG) { - System.out.println("joinHandler: inserted the queue in hash "); - } - name_to_q_.put(roomName,q_); - roomHandler handler = new roomHandler(roomName,q_,write_q_,applet_); - name_to_handler_.put(roomName,handler); - - // send a request to the server - sayJoinToServer(roomName); - // sendTestPacket(roomName,"URL","http://cumbia.cs.wustl.edu:4242/~sumedh/NexusII/NexusII.gif",q_); - } // of join - - else { - // its a "leave packet" - if(name_to_q_.get(roomName) == null) - return ; - // remove the entry from the queue - name_to_q_.remove(roomName); - - roomHandler handle = (roomHandler) name_to_handler_.get(roomName); - if(DEBUG) - System.out.println("joinHandler:Stopiing the room thread" + roomName); - handle.mystop(); - // handle = null ; - - // remove the entry from the queue - name_to_handler_.remove(roomName); - sayLeaveToServer(roomName); - } // of else - } // of execute - - private void sayJoinToServer(String roomName) { - //if (DEBUG) - // System.out.println("In the say J to server..."); - byte[] packetHeader = new byte[PACKET_HEADER_LENGTH] ; - String clientID = new String(NexusClientApplet.myName); - String roomID = new String("ROOT"); - String contentType = new String("JOIN"); - String contentLength = String.valueOf(roomName.length()); - String content = new String(roomName); - // Make a proper packet out of it - dataPacket joinPacket = new dataPacket(clientID,roomID,contentType,contentLength,content); - - // enqueue that packet for socketWriter to read - write_q_.nq(joinPacket); - } - - private void sayLeaveToServer(String roomName) { - byte[] packetHeader = new byte[PACKET_HEADER_LENGTH] ; - String clientID = new String(NexusClientApplet.myName); - String roomID = new String("ROOT"); - String contentType = new String("LEAVE"); - String contentLength = new String(Integer.toString(roomName.length())); - String content = new String(roomName); - - // Make a proper packet out of it - dataPacket leavePacket = new dataPacket(clientID,roomID,contentType,contentLength,content); - - // enqueue that packet for socketWriter to read - write_q_.nq(leavePacket); - } - - - public void sendTestPacket(String roomName,String type,String content,MT_Bounded_Queue readq) { - byte[] packetHeader = new byte[PACKET_HEADER_LENGTH] ; - String clientID = new String(NexusClientApplet.myName); - String contentLength = new String(Integer.toString(content.length())); - - - // Make a proper packet out of it - dataPacket testPacket = new dataPacket(clientID,roomName,type,contentLength,content); - - // enqueue that packet for socketWriter to read - readq.nq(testPacket); - } - - -} - -// of class - - - - - - - - - - - - - - - - diff --git a/java/apps/NexusII/src/makefile b/java/apps/NexusII/src/makefile deleted file mode 100644 index c3cff521511..00000000000 --- a/java/apps/NexusII/src/makefile +++ /dev/null @@ -1,15 +0,0 @@ -all: client server - -client: ../classes/NexusClientApplet.class - -../classes/NexusClientApplet.class: - javac -d ../classes -depend -g NexusClientApplet.java - -server: ../classes/NexusIIserver.class - -../classes/NexusIIserver.class: - javac -d ../classes -depend -g NexusIIserver.java - -clean: - rm -f ../classes/*.class *~ - diff --git a/java/apps/NexusII/src/nexusDemuxThread.java b/java/apps/NexusII/src/nexusDemuxThread.java deleted file mode 100644 index 96d0fdd06e1..00000000000 --- a/java/apps/NexusII/src/nexusDemuxThread.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - $RCSfile$ - $Author$ - - Last Update: $Date$ - $Revision$ - - REVISION HISTORY: - $Log$ - Revision 1.1 1997/01/31 01:11:10 sumedh - Added the Nexus II source code files. - -# Revision 1.1 1996/12/07 06:27:38 rajeev -# Initial revision -# -# Revision 1.2 1996/12/05 05:39:47 sumedh -# ok -# -# Revision 1.1 1996/12/02 06:08:20 rajeev -# Initial revision -# -# Revision 1.1 1996/12/02 06:02:24 rajeev -# Initial revision -# - -*/ - -// Will take the packets from the input queue -// Parse the packet -// Call the room handler thread which Aravind will provide - -// Mapper object is the one which returns the room_q reference if you pass -// it the room number. Aravind has to implement this object called roomMapper -// which has an instance called mapper in the Applet context. This will be -// referred by nexusDemuxThread whenever it has anything to put in the room_q - -// package NexusII.networking ; - -//import NexusII.util.* ; -//import NexusII.client.* ; - -import java.util.* ; - -public class nexusDemuxThread extends Thread implements consts { - MT_Bounded_Queue q_ ; - dataPacket packet ; - Hashtable mapper_ ; - - // constructor - public nexusDemuxThread(MT_Bounded_Queue read_q,Hashtable mapper) { - q_ = read_q ; - mapper_ = mapper ; - } - - public void run() { - // run till infinity - for(;;) { - if(DEBUG) { - System.out.println("Demux running ---- "); - } - // take out packets from the queue - // parse to find out which room they belong to - packet = ((dataPacket)q_.dq()); - if(DEBUG) { - System.out.println("Demux got something ---- "); - } - - String roomName = packet.destination().trim(); - if(DEBUG) { - System.out.println("demux: destination is : " + roomName); - } - if(DEBUG) { - System.out.println("Hashtable size is " + new Integer(mapper_.size())); - } - // Get a reference to which queue to put it in - MT_Bounded_Queue room_q = (MT_Bounded_Queue)mapper_.get(roomName); - - // nq the packet on the room q - if(room_q != null) { - room_q.nq(packet); - System.out.println("deMux: I have enqueued it successfully"); - } - else - { - System.out.println("demux: room_q was null: i couldnt do much"); - } - } - } - // of run -} -// of class - - - - - -// 11/24/96 -- Rajeev Bector diff --git a/java/apps/NexusII/src/roomHandler.java b/java/apps/NexusII/src/roomHandler.java deleted file mode 100644 index bd125631b74..00000000000 --- a/java/apps/NexusII/src/roomHandler.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - $RCSfile$ - $Author$ - - Last Update: $Date$ - $Revision$ - - REVISION HISTORY: - $Log$ - Revision 1.1 1997/01/31 01:11:11 sumedh - Added the Nexus II source code files. - -# Revision 1.4 1996/12/07 06:22:49 rajeev -# taking a backup ! -# -# Revision 1.3 1996/12/06 06:20:07 rajeev -# Changes to include leave handler -# -# Revision 1.2 1996/12/06 04:49:44 rajeev -# working now hopefully ! -# -# Revision 1.1 1996/12/06 03:44:32 rajeev -# Initial revision -# - -*/ - -// per room -import java.awt.* ; -import awtCommand.* ; -import java.io.* ; -import java.net.* ; -//import NexusII.client.* ; -//import NexusII.util.* ; -//import NexusII.networking.*; - -public class roomHandler implements Runnable,consts{ - - String roomName_ ; - MT_Bounded_Queue read_q_ ; - MT_Bounded_Queue write_q_ ; - RoomFrame rf_; - Thread mainThread ; - NexusClientApplet applet_ ; - - // I dont know what to do currently - public roomHandler(String roomName, MT_Bounded_Queue reader_q,MT_Bounded_Queue writer_q,NexusClientApplet applet) { - roomName_ = roomName ; - read_q_ = reader_q ; - write_q_ = writer_q ; - applet_ = applet ; - rf_ = new RoomFrame(write_q_,applet_,roomName_); - // whenever this frame gets the mouse focus, handler will be called - FrameHandler fh_ = new FrameHandler(applet_); - rf_.setGotFocusCommand(fh_); - mainThread = new Thread(this); - mainThread.start(); - } - - - public void mystop() { - // dispose the graphics part here - if(DEBUG) - System.out.println("Roomhandlers stop called \n"); - rf_.hide(); - rf_.dispose(); - // no longer need the roomframe - rf_ = null ; - mainThread.stop(); - } - - public void run() { - if(DEBUG) { - System.out.println("Room receiver running ---- "); - } - while(Thread.currentThread() == mainThread) { - // get the data packet - dataPacket packet = (dataPacket)(read_q_.dq()) ; - if(DEBUG) - System.out.println("Room - I got something\n"); - - // if the packet is of text type -- display it - if(packet.contentType().trim().equalsIgnoreCase("TEXT")) { - rf_.addText(packet.content()); - } - // if the packet is a url address -- pull the image across - // this url has to be an image as of now - if(packet.contentType().equalsIgnoreCase("URL")) { - Image im = null ; - try { - im = applet_.getImage(new URL(packet.content())); - } catch (MalformedURLException i) { - // nothing as of now - } - // display the image - rf_.updateImage(im); - - } - - if (DEBUG) - System.out.println("roomhandler" + roomName_ + " got data"); - } - } - - public String toString() { - return roomName_ ; - } - -} // of class roomHandler - -// is executed when the room frame gets mouse focus - -class FrameHandler implements Command { - NexusClientApplet applet_ ; - public FrameHandler(NexusClientApplet applet) { - applet_ = applet ; - } - - public void execute(Object target, Event evt, Object what) { - if(target instanceof Frame) { - applet_.SetRoomName(((RoomFrame)target).getTitle()); - } - } -} - diff --git a/java/apps/NexusII/src/socketReaderThread.java b/java/apps/NexusII/src/socketReaderThread.java deleted file mode 100644 index 35679c504b4..00000000000 --- a/java/apps/NexusII/src/socketReaderThread.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - $RCSfile$ - $Author$ - - Last Update: $Date$ - $Revision$ - - REVISION HISTORY: - $Log$ - Revision 1.1 1997/01/31 01:11:11 sumedh - Added the Nexus II source code files. - -# Revision 1.1 1996/12/07 06:27:38 rajeev -# Initial revision -# -# Revision 1.3 1996/12/03 01:35:37 rajeev -# fixed a big bug with respect to trim() -# -# Revision 1.2 1996/12/03 01:01:27 rajeev -# // fixed the bug at line 76 -# -# Revision 1.1 1996/12/02 06:08:56 rajeev -# Initial revision -# -# Revision 1.1 1996/12/02 06:02:24 rajeev -# Initial revision -# - -*/ -// The socketReaderThread is like a Producer who reads from the socket and -// nqs it onto the queue. Thats it ... Big Deal. huh ! - -// This threads task is -// 1. Take things from SocketBuffer. -// 2. Ensure that Full Packets are read -// 3. Put the packet onto the queue - -//package NexusII.networking ; - -// get hold of java classes -//import NexusII.client.* ; -//import NexusII.util.* ; - -import java.io.* ; - - -public class socketReaderThread extends Producer implements Runnable,consts -{ - DataInputStream is_ ; - - // new constructor - // Pass the queue and socketid to the constructor - - public socketReaderThread(MT_Bounded_Queue q, DataInputStream is) { - // call the super constructor - super(q); - is_ = is ; - } - - // This will just override the run method and thats it - // I want to have my own run ! - - public void run() { - // run indefinitely -- i am a daemon anyway - if(DEBUG) { - System.out.println("--- This is socketReaderThread --- \n"); - } - - for(;;) { - - // read header bytes from stream - int field_len = FIELD_LENGTH ; - byte[] packetHeader = new byte[PACKET_HEADER_LENGTH]; - try { - is_.readFully(packetHeader,0,PACKET_HEADER_LENGTH); - } - catch (IOException e) { - // do something here - System.out.println("socketReader: I/O exception in read: I am quitting"); - // what to do here -- right now quit - return ; - } - if(DEBUG){ - System.out.println("socketReader read:" + new String(packetHeader,0)); - } - - // take out the length field from this - String length = new String(packetHeader,0,DATA_LEN_OFFSET,field_len); - - // Read this much more from the socket - if(DEBUG) { - System.out.println("The length of packet is " + length); - } - - Integer Test = new Integer(length.trim()); - int len = Test.intValue(); - if(DEBUG) { - System.out.println("srt: attempting to read " + Test + " bytes "); - } - - byte[] packetBody = new byte[len] ; - try { - if(len != 0) - is_.readFully(packetBody,0,len); - } - catch (IOException e) { - // do something here - System.out.println("socketReader: I/O exception in read: I am quitting"); - // what to do here -- right now quit - return ; - } - - // The header and the body are there now -- so make a packet - dataPacket packet = new dataPacket(packetHeader,packetBody); - if(DEBUG) - System.out.println("srt: Now nq'ing item body " + packet.content() ); - queue_.nq(packet); - if(DEBUG) - System.out.println("srt: Done nq'ing.."); - - // go back to reading the socket now - } - // of for(;;) - } - // of method run -} diff --git a/java/apps/NexusII/src/socketWriterThread.java b/java/apps/NexusII/src/socketWriterThread.java deleted file mode 100644 index 395449b6a53..00000000000 --- a/java/apps/NexusII/src/socketWriterThread.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - $RCSfile$ - $Author$ - - Last Update: $Date$ - $Revision$ - - REVISION HISTORY: - $Log$ - Revision 1.1 1997/01/31 01:11:12 sumedh - Added the Nexus II source code files. - -# Revision 1.1 1996/12/07 06:27:38 rajeev -# Initial revision -# -# Revision 1.1 1996/12/02 06:09:22 rajeev -# Initial revision -# -# Revision 1.1 1996/12/02 06:02:24 rajeev -# Initial revision -# - -*/ -// The socketWriterThread is like a Consumer who reads from the write_q and -// puts it onto the socket. Thats it ... Big Deal. huh ! - -// This threads task is -// 1. Write things to SocketBuffer. -// 2. Ensure that Full Packets are sent -// 3. Read the packet off the queue - -//package NexusII.networking ; - -// get hold of java classes - -import java.io.* ; - -//import NexusII.client.* ; -//import NexusII.util.* ; - -public class socketWriterThread extends Consumer implements Runnable,consts -{ - DataOutputStream os_ ; - - // new constructor - // Pass the queue and outstream to the constructor - - public socketWriterThread(MT_Bounded_Queue q, DataOutputStream os) { - // call the super constructor - super(q); - os_ = os ; - } - - // This will just override the run method and thats it - // I want to have my own run ! - - public void run() { - // run indefinitely -- i am a daemon anyway - if(DEBUG) { - System.out.println("--- This is socketWriterThread --- \n"); - } - boolean bye_sent = false ; - while(!bye_sent) { - - // read the packet from the queue - dataPacket packet = (dataPacket) queue_.dq(); - if(DEBUG){ - System.out.println("socketWriterThread: I got something -- \n"); - } - - // read length bytes from packet - int len = packet.contentLength() ; - if(DEBUG) { - System.out.println("socketWriterThread: length is " + new Integer(len)); - } - - - int field_len = FIELD_LENGTH ; - - // Allocate storage for holding the fields - - byte[] packetHeader = new byte[PACKET_HEADER_LENGTH]; - byte[] packetBody = new byte[len] ; - - // Fill them - packet.bytize(packetHeader,packetBody); - - // put it on the wire now -- - - try { - os_.write(packetHeader,0,PACKET_HEADER_LENGTH); - } - catch (IOException e) { - // do something here - } - if(DEBUG){ - System.out.println("I wrote:" + new String(packetHeader,0)); - } - - try { - os_.write(packetBody,0,len); - } - catch (IOException e) { - // do something here - } - if(DEBUG){ - System.out.println("I wrote:" + new String(packetBody,0)); - } - // this is to handle if the user presses disconnect without leaving the - // room - if(packet.contentType().equalsIgnoreCase("QUIT")) - bye_sent = true ; - // go back to reading the queue now - } - // of for(;;) - } - // of method run - -} diff --git a/java/apps/NexusII/src/url_to_url.java b/java/apps/NexusII/src/url_to_url.java deleted file mode 100644 index 0fe08ab6db3..00000000000 --- a/java/apps/NexusII/src/url_to_url.java +++ /dev/null @@ -1,33 +0,0 @@ -// This method takes in a url and a prefix name and pulls that url across the -// network, stores it in a local file named prefix - -// for now it assumes that the url is an image only ! - -import java.net.* ; -import java.io.* ; -import java.awt.* ; -public class url_to_url { - Image im ; - - public url_to_url(URL url,String prefix) { - try { - im = (Image)url.getContent(); - } catch (IOException i) {} - String www_path = System.getProperty("www-path"); - String home_dir = System.getProperty("user.home"); - String dir = home_dir + www_path ; - System.out.println("web dir is this : " + dir); - - } - - public static void main(String[] argv) { - URL test = null ; - try { - test = new URL("http://www.cs.wustl.edu/~rajeev/images/sand.jpg"); - } catch ( MalformedURLException e) {} - - url_to_url t = new url_to_url(test,"root") ; - - } - -} diff --git a/java/apps/NexusII/start b/java/apps/NexusII/start deleted file mode 100755 index c699c96da60..00000000000 --- a/java/apps/NexusII/start +++ /dev/null @@ -1,27 +0,0 @@ -#! /bin/sh - -## This is an example script to launch the server. - -# the mywebaddress variable should point to a URL which is world-readable -# the mywebdir variable should point to the actual pathname of the URL -# which is specified by the mywebaddress variable -# The server needs to have write access to the mywebdir directory. -# Thus, the server saves images into the "mywebdir", and clients -# can access them via the "mywebaddress" URL. - -# the 222222 number is the port number on which the server is to be launched -# the same port number should appear in the html document containing -# the client applet (see start.html for an example) - -# while running the server, the ./classes should be part of the CLASSPATH. -# while running the client, the client classes as well as the awtCommand -# toolkit should be world-readable. (The awtcommand toolkit is included -# in this toolkit, under the classes directory.) - - -umask 022 -java -Dmywebaddress=http://cumbia.cs.wustl.edu/NexusII/tmp/ -Dmywebdir=/project/cumbia/sumedh/web/apache/root/NexusII/tmp/ NexusIIserver 222222 - - - - diff --git a/java/apps/NexusII/start.html b/java/apps/NexusII/start.html deleted file mode 100644 index cd591295b4a..00000000000 --- a/java/apps/NexusII/start.html +++ /dev/null @@ -1,3 +0,0 @@ -<applet code=NexusClientApplet.class width=550 height=500> - <param name=serverport value="222222"> -</applet> diff --git a/java/classes/README.TXT b/java/classes/README.TXT deleted file mode 100644 index ba771e6615d..00000000000 --- a/java/classes/README.TXT +++ /dev/null @@ -1,2 +0,0 @@ -The .class files are not included in the release archive. When properly -setup and built, a JACE subdirectory will be here. diff --git a/java/doc/images/GridBagEx.gif b/java/doc/images/GridBagEx.gif Binary files differdeleted file mode 100644 index 16c326d88ca..00000000000 --- a/java/doc/images/GridBagEx.gif +++ /dev/null diff --git a/java/doc/images/OpenBookIcon.gif b/java/doc/images/OpenBookIcon.gif Binary files differdeleted file mode 100644 index 86384f7733f..00000000000 --- a/java/doc/images/OpenBookIcon.gif +++ /dev/null diff --git a/java/doc/images/blue-ball-small.gif b/java/doc/images/blue-ball-small.gif Binary files differdeleted file mode 100644 index d4c5cde5b00..00000000000 --- a/java/doc/images/blue-ball-small.gif +++ /dev/null diff --git a/java/doc/images/blue-ball.gif b/java/doc/images/blue-ball.gif Binary files differdeleted file mode 100644 index edc29b786ce..00000000000 --- a/java/doc/images/blue-ball.gif +++ /dev/null diff --git a/java/doc/images/class-index.gif b/java/doc/images/class-index.gif Binary files differdeleted file mode 100644 index 7f276bcb242..00000000000 --- a/java/doc/images/class-index.gif +++ /dev/null diff --git a/java/doc/images/constructor-index.gif b/java/doc/images/constructor-index.gif Binary files differdeleted file mode 100644 index 435cac42386..00000000000 --- a/java/doc/images/constructor-index.gif +++ /dev/null diff --git a/java/doc/images/constructors.gif b/java/doc/images/constructors.gif Binary files differdeleted file mode 100644 index d1a6ae507ca..00000000000 --- a/java/doc/images/constructors.gif +++ /dev/null diff --git a/java/doc/images/cyan-ball-small.gif b/java/doc/images/cyan-ball-small.gif Binary files differdeleted file mode 100644 index 7f74357443a..00000000000 --- a/java/doc/images/cyan-ball-small.gif +++ /dev/null diff --git a/java/doc/images/cyan-ball.gif b/java/doc/images/cyan-ball.gif Binary files differdeleted file mode 100644 index 97ca1f2b6e3..00000000000 --- a/java/doc/images/cyan-ball.gif +++ /dev/null diff --git a/java/doc/images/error-index.gif b/java/doc/images/error-index.gif Binary files differdeleted file mode 100644 index 22835ff8c64..00000000000 --- a/java/doc/images/error-index.gif +++ /dev/null diff --git a/java/doc/images/exception-index.gif b/java/doc/images/exception-index.gif Binary files differdeleted file mode 100644 index e3830d9c52e..00000000000 --- a/java/doc/images/exception-index.gif +++ /dev/null diff --git a/java/doc/images/green-ball-small.gif b/java/doc/images/green-ball-small.gif Binary files differdeleted file mode 100644 index 17fea5b32bb..00000000000 --- a/java/doc/images/green-ball-small.gif +++ /dev/null diff --git a/java/doc/images/green-ball.gif b/java/doc/images/green-ball.gif Binary files differdeleted file mode 100644 index 71e1b2ec2db..00000000000 --- a/java/doc/images/green-ball.gif +++ /dev/null diff --git a/java/doc/images/interface-index.gif b/java/doc/images/interface-index.gif Binary files differdeleted file mode 100644 index bf93dda9e35..00000000000 --- a/java/doc/images/interface-index.gif +++ /dev/null diff --git a/java/doc/images/magenta-ball-small.gif b/java/doc/images/magenta-ball-small.gif Binary files differdeleted file mode 100644 index bd0584b3c67..00000000000 --- a/java/doc/images/magenta-ball-small.gif +++ /dev/null diff --git a/java/doc/images/magenta-ball.gif b/java/doc/images/magenta-ball.gif Binary files differdeleted file mode 100644 index 5da03b84d2b..00000000000 --- a/java/doc/images/magenta-ball.gif +++ /dev/null diff --git a/java/doc/images/method-index.gif b/java/doc/images/method-index.gif Binary files differdeleted file mode 100644 index a05e7051160..00000000000 --- a/java/doc/images/method-index.gif +++ /dev/null diff --git a/java/doc/images/methods.gif b/java/doc/images/methods.gif Binary files differdeleted file mode 100644 index 949e01b8a33..00000000000 --- a/java/doc/images/methods.gif +++ /dev/null diff --git a/java/doc/images/package-index.gif b/java/doc/images/package-index.gif Binary files differdeleted file mode 100644 index f894d4210d7..00000000000 --- a/java/doc/images/package-index.gif +++ /dev/null diff --git a/java/doc/images/red-ball-small.gif b/java/doc/images/red-ball-small.gif Binary files differdeleted file mode 100644 index f6b3c372ca1..00000000000 --- a/java/doc/images/red-ball-small.gif +++ /dev/null diff --git a/java/doc/images/red-ball.gif b/java/doc/images/red-ball.gif Binary files differdeleted file mode 100644 index dca92960148..00000000000 --- a/java/doc/images/red-ball.gif +++ /dev/null diff --git a/java/doc/images/variable-index.gif b/java/doc/images/variable-index.gif Binary files differdeleted file mode 100644 index 65cc029e722..00000000000 --- a/java/doc/images/variable-index.gif +++ /dev/null diff --git a/java/doc/images/variables.gif b/java/doc/images/variables.gif Binary files differdeleted file mode 100644 index e8a735399a6..00000000000 --- a/java/doc/images/variables.gif +++ /dev/null diff --git a/java/doc/images/yellow-ball-small.gif b/java/doc/images/yellow-ball-small.gif Binary files differdeleted file mode 100644 index 8e5f57cdfcb..00000000000 --- a/java/doc/images/yellow-ball-small.gif +++ /dev/null diff --git a/java/doc/images/yellow-ball.gif b/java/doc/images/yellow-ball.gif Binary files differdeleted file mode 100644 index 2b8c0bb3d6b..00000000000 --- a/java/doc/images/yellow-ball.gif +++ /dev/null diff --git a/java/examples/Logger/README b/java/examples/Logger/README deleted file mode 100644 index 1da7dbcbb19..00000000000 --- a/java/examples/Logger/README +++ /dev/null @@ -1,29 +0,0 @@ -This directory contains a simple client/server Java implementation of the -distributed logging server described in several papers in the C++ -Report (which can be obtained via the following WWW URLs: -http://www.cs.wustl.edu/~schmidt/{Reactor1-93.ps.gz,Reactor2-93.ps.gz}). - -The example consists of the following two directories: - - . client - NOT YET CONVERTED - This program talks directly to the server logging - daemon. The server daemon must be started before you - can run this test. - - . simple-server - - This program runs a simple - implementation of the - distributed logging server daemon. It also contains - code for a simple client as well. - - . Acceptor-server - NOT YET CONVERTED - This program runs templated, Acceptor-based - single-threaded Reactive implementation of the - distributed logging server daemon. - -The server implemented in "simple" is completely compatible with the -client defined in the C++ version of ACE. - diff --git a/java/examples/Logger/simple-server/LogRecord.java b/java/examples/Logger/simple-server/LogRecord.java deleted file mode 100644 index e29ed6e32b9..00000000000 --- a/java/examples/Logger/simple-server/LogRecord.java +++ /dev/null @@ -1,145 +0,0 @@ -/** - * Class used to communicate logging information; compatible with - * the C++ ACE ACE_Log_Record class. - * - * @author Chris Cleeland - */ - -//package ACE.SimpleLogger; - -import java.util.Date; -import java.io.DataOutputStream; -import java.io.DataInputStream; -import java.io.PrintStream; -import java.io.IOException; - -public class LogRecord -{ - final public static int MAXLOGMSGLEN = 4 * 1024; - - private int type_; - private int length_; - private int timeStamp_; - private int pid_; - private byte[] msgData_ = new byte[MAXLOGMSGLEN]; - private final static int numIntMembers = 4; - private final static int sizeofIntInBytes = 4; - - /** - * Create a default instance. - */ - public LogRecord() - { - this(0, (int) ((new Date()).getTime()/1000), 0); - } - - /** - * Create a LogRecord. This is the designated initializer. - * @param priority a numeric specification of the priority (ascending) - * @param time_stamp time attached to the log entry in Unix <pre>time_t</pre> format - * @param pid the process ID; not currently used - */ - public LogRecord(int priority, - int timeStamp, - int pid) - { - type(priority); - timeStamp(timeStamp); - length(0); - pid(pid); - } - - /** - * Conversion to string. Only includes the <pre>msgData_</pre> member. - */ - public String toString() - { - return new String(msgData_, 0); - } - - /** - * Place a textual representation of the record on a PrintStream. - * @param hostname name of the host generating this record - * @param verbose if <b>true</b>, print information in the form, (give example) - * @param ps A PrintStream instance to which the output should go. - * @see PrintStream,String - */ - public void print(String hostname, - boolean verbose, - PrintStream ps) - { - String toprint; - if (verbose) - { - long cur = (long)timeStamp() * (long)1000; - Date now = new Date(cur); - - /* 01234567890123456789012345 */ - /* Wed Oct 18 14:25:36 1989n0 */ - toprint = now.toString().substring(4) + "@" - + hostname + "@" + pid_ + "@" + type_ + "@" - + this.toString(); - } - else - { - toprint = this.toString(); - } - ps.println(toprint); - } - - /** - * Streaming methods - */ - public void streamInFrom(DataInputStream dis) throws IOException - { - // Order here must match layout order in the C++ class. - // This, of course, is VERY fragile, and ought not be used as - // a model for anything except how NOT to do anything. - type(dis.readInt()); - length(dis.readInt()); - timeStamp(dis.readInt()); - pid(dis.readInt()); - - // Does readFully() allocate space for the buffer? Either - // way, we won't have memory leaks :-) - int dataLength = (int) (length_ - numIntMembers * sizeofIntInBytes); - msgData_ = new byte[dataLength]; - dis.readFully(msgData_, 0, dataLength); - } - - public void streamOutTo(DataOutputStream dos) throws IOException - { - dos.writeInt(type()); - dos.writeInt(length()); - dos.writeInt(timeStamp()); - dos.writeInt(pid()); - int dataLength = (int) (length_ - numIntMembers * sizeofIntInBytes); - dos.write(msgData_, 0, dataLength); - } - - /** - * Accessor methods - */ - public int type() { return type_; } - public void type(int t) { type_ = t; } - - public int length() { return length_; } - public void length(int l) { length_ = l; } - private void setLen(int msgLen) - { length(msgLen + numIntMembers * sizeofIntInBytes); } - - public int timeStamp() { return timeStamp_; } - public void timeStamp(int t){ timeStamp_ = t; } - - public int pid() { return pid_; } - public void pid(int p) { pid_ = p; } - - public byte[] msgData() { return msgData_; } - public void msgData(byte[] m){ msgData_ = m; setLen(m.length); } - public void msgData(String m) - { - m.getBytes(0, m.length(), msgData_, 0); - setLen(m.length()); - } -}; - diff --git a/java/examples/Logger/simple-server/LoggerConstants.java b/java/examples/Logger/simple-server/LoggerConstants.java deleted file mode 100644 index db62d2fff6e..00000000000 --- a/java/examples/Logger/simple-server/LoggerConstants.java +++ /dev/null @@ -1,7 +0,0 @@ -// package ACE.Logger; - -public class LoggerConstants -{ - final public static int DEFAULT_SERVER_PORT = 4000; - final public static String DEFAULT_SERVER_HOSTNAME = "localhost"; -} diff --git a/java/examples/Logger/simple-server/LoggingAcceptor.java b/java/examples/Logger/simple-server/LoggingAcceptor.java deleted file mode 100644 index 7925e3d5a15..00000000000 --- a/java/examples/Logger/simple-server/LoggingAcceptor.java +++ /dev/null @@ -1,33 +0,0 @@ -//package ACE.SimpleLogger; - -import JACE.SOCK_SAP.*; -import java.io.IOException; - -public class LoggingAcceptor extends Thread -{ - private SOCKAcceptor peerAcceptor_; - - public LoggingAcceptor(int port) throws IOException - { - peerAcceptor_ = new SOCKAcceptor(port); - this.setName("LoggingAcceptor"); - System.err.println("Waiting for connection on port " + - port); - } - - public void run() - { - try - { - while (true) - { - LoggingHandler handler = new LoggingHandler(); - peerAcceptor_.accept(handler.stream()); - handler.open(); - } - } - catch (IOException e) - { - } - } -}; diff --git a/java/examples/Logger/simple-server/LoggingClient.java b/java/examples/Logger/simple-server/LoggingClient.java deleted file mode 100644 index e6ea986c011..00000000000 --- a/java/examples/Logger/simple-server/LoggingClient.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Main class that acts as an example logging client. - */ - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import LogRecord; -import LoggerConstants; - -public class LoggingClient implements Runnable -{ - private String loggerHost_; - private int port_; - private int maxIter_; - private static final int DEFAULT_ITERATIONS = 10; - - public static void main(String[] args) - { - // Really need to put code in here to parse options - int iter; - int port; - String host; - - iter = (args.length > 0) ? Integer.parseInt(args[0]) - : DEFAULT_ITERATIONS; - port = (args.length > 1) ? Integer.parseInt(args[1]) - : LoggerConstants.DEFAULT_SERVER_PORT; - host = (args.length > 2) ? args[2] - : LoggerConstants.DEFAULT_SERVER_HOSTNAME; - - LoggingClient lc = new LoggingClient(iter, port, host); - lc.run(); - } - - public LoggingClient() - { - - this(DEFAULT_ITERATIONS, - LoggerConstants.DEFAULT_SERVER_PORT, - LoggerConstants.DEFAULT_SERVER_HOSTNAME); - } - - public LoggingClient(int iterations, int thePort, String theHost) - { - maxIter_ = iterations; - port_ = thePort; - loggerHost_ = theHost; - } - - public void run() - { - SOCKStream logger = new SOCKStream(); - SOCKConnector connector = new SOCKConnector(); - // INETAddr addr = new INETAddr(port_, loggerHost_); - - LogRecord rec = new LogRecord(9, 2, 0); - - try - { - connector.connect(logger, loggerHost_, port_); - - int oneSecond = 1000; - // Currently SOCKStream uses DataInputStream for its input stream, - // and PrintStream for its output stream. It probably ought to use - // DataOutputStream for the output stream for symmetry, or at least - // provide a mechanism for changing the type of the filter stream - // used (which might be better in the long run...give it the class - // id). - BufferedOutputStream bos = new BufferedOutputStream((OutputStream) logger.outputStream(), LogRecord.MAXLOGMSGLEN); - DataOutputStream dos = new DataOutputStream(bos); - - for (int i = 0; i < maxIter_; i++) - { - // Need to overload LogRecord.msgData to take a String - // argument so that it's easy to create instances with text - // inside. - rec.msgData("message = " + i); - try - { - dos.writeInt(rec.length()); - rec.streamOutTo(dos); - bos.flush(); - rec.print("localhost", true, System.err); - } - catch (IOException ex) { } - - try - { - Thread.sleep(oneSecond); - } - catch (InterruptedException ex) { } - } - - try { logger.close(); } catch (IOException ex) { } - - } - catch (SocketException ex) - { - System.err.println("socket exception: " + ex); - } - catch (IOException ex) - { - System.err.println("io exception: " + ex); - } - - } -} diff --git a/java/examples/Logger/simple-server/LoggingHandler.java b/java/examples/Logger/simple-server/LoggingHandler.java deleted file mode 100644 index aeffc991ac3..00000000000 --- a/java/examples/Logger/simple-server/LoggingHandler.java +++ /dev/null @@ -1,121 +0,0 @@ -/************************************************* - * - *@author Chris Cleeland - * - * What we really need to define is a run() (or whatever - * the Thread class has as its method to execute code), and - * have that do the usual delegated work of handle_input. - * We also need to figure out the best place to close the - * the socket, which probably ISN'T the finalizer. - * - *************************************************/ - -//package ACE.SimpleLogger; - -import JACE.SOCK_SAP.*; -import java.util.*; -import java.io.*; - -// Should this extend or simply be handed to a Thread instance to -// be run? -public class LoggingHandler extends Thread -{ - private SOCKStream cliStream_; - - /** - * Create a default Logging Handler - */ - public LoggingHandler() - { - this(new SOCKStream()); - } - - /** - * Create a LoggingHandler with an existing stream - */ - public LoggingHandler(SOCKStream aStream) - { - cliStream_ = aStream; - setName(); - } - - private void setName() - { - int portnum = ((cliStream_.socket() == null) - ? 0 - : cliStream_.socket().getLocalPort()); - this.setName("LoggingHandler#" + portnum); - } - - /** - * Start - */ - public void open() - { - this.start(); - } - - /** - */ - public SOCKStream stream() - { - return cliStream_; - } - - /** - * Handle logging events - */ - public void run() - { - DataInputStream dis = (DataInputStream) cliStream_.inputStream(); - - for (;;) - { - // Messages arrive in the following format: - // o 4 byte length (network format) - // o message, in ACE.LogRecord format - // - // Hey! We need exception catching in here too! - try - { - // Reconstitute a log message from the wire - LogRecord rec = new LogRecord(); - - // We don't really need this, because - // the object already knows how to - // extract itself properly. However, - // in order to interoperate with the - // C++ version, this must be extracted. - // Plus, it makes a convenient way to - // check everything. - int length = dis.readInt(); - - rec.streamInFrom(dis); - - if (rec.length() == length) - { - rec.print(cliStream_.socket().getInetAddress().getHostName(), - true, System.out); - System.out.flush(); - } - else - { - System.err.println("Logging_Handler: Length error receiving logging message\n"); - } - } - catch (EOFException eof) - { - System.err.println(Thread.currentThread().getName() - + ": end-of-file condition found; terminating."); - try { cliStream_.close(); } catch (IOException n) { } - this.stop(); - } - catch (IOException ioe) - { - System.err.println(Thread.currentThread().getName() - + ": IOException received -- " - + ioe.getMessage()); - } - } - } -}; diff --git a/java/examples/Logger/simple-server/Makefile b/java/examples/Logger/simple-server/Makefile deleted file mode 100644 index 5be1b0d048e..00000000000 --- a/java/examples/Logger/simple-server/Makefile +++ /dev/null @@ -1,34 +0,0 @@ -.SUFFIXES: .java .class - -CLASSDIR = . -DOCDIR = . - -JC = javac_g -JCOPTS = -g -d $(CLASSDIR) -JD = javadoc -JDOPTS = -d $(DOCDIR) - -COMPILE.java = $(JC) $(JCOPTS) $< -DOCCOMP.java = $(JD) $(JDOPTS) $< - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -CLASSES = LoggerConstants LogRecord LoggingHandler \ - LoggingAcceptor SimpleLogger LoggingClient -CLASSFILES = $(addsuffix .class,$(CLASSES)) -DOCFILES = $(addsuffix .html,$(CLASSES)) - -%.class: %.java - $(COMPILE.java) - -%.html: %.java - $(DOCCOMP.java) - -all: classes doc - -classes: $(CLASSFILES) -doc: $(DOCFILES) - -clean: - $(RM) *~ $(CLASSFILES) $(DOCFILES) - diff --git a/java/examples/Logger/simple-server/README b/java/examples/Logger/simple-server/README deleted file mode 100644 index 90393c1aae8..00000000000 --- a/java/examples/Logger/simple-server/README +++ /dev/null @@ -1,25 +0,0 @@ -====== -BASICS -====== - -This directory contains both the client (LoggingClient.java) and the -server (SimpleLogger.java). To compile, use GNU make with no specific -target. - -To execute, use "java <classname>" where <classname> is from the -following table: - - Application <classname> - =========================================== - client LoggingClient - server SimpleLogger - - -============== -KNOWN PROBLEMS -============== - -Interoperability between the C++ client and the Java server -implementation is fine. Interoperability between the C++ server and -the Java client seems to work right now. See the CVS information on -LoggingClient.java for details. diff --git a/java/examples/Logger/simple-server/SimpleLogger.java b/java/examples/Logger/simple-server/SimpleLogger.java deleted file mode 100644 index f562689e283..00000000000 --- a/java/examples/Logger/simple-server/SimpleLogger.java +++ /dev/null @@ -1,44 +0,0 @@ -//package ACE.SimpleLogger; - -import java.io.IOException; - -class SimpleLogger implements Runnable -{ - private LoggingAcceptor la; - private int port; - - public static void main(String[] args) - { - SimpleLogger sl = new SimpleLogger(); - sl.run(); - } - - public SimpleLogger() - { - this(LoggerConstants.DEFAULT_SERVER_PORT); - } - - public SimpleLogger(int port) - { - try - { - la = new LoggingAcceptor(port); - } - catch (IOException ioe) - { - System.err.println("SimpleLogger: unable to create LoggingAcceptor (" - + ioe.getMessage() + ")"); - } - } - - public void run() - { - la.run(); - try - { - la.join(); - } - catch (InterruptedException ie) - { } - } -}; diff --git a/java/gjt/Assert.java b/java/gjt/Assert.java deleted file mode 100644 index b704be9ff3c..00000000000 --- a/java/gjt/Assert.java +++ /dev/null @@ -1,33 +0,0 @@ -package gjt; - -/** - * A simple assertion mechanism for asserting validity of - * arguments.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - */ -public class Assert { - static public void notFalse(boolean b) - throws IllegalArgumentException { - if(b == false) - throw new IllegalArgumentException( - "boolean expression false"); - } - static public void notNull(Object obj) - throws IllegalArgumentException { - if(obj == null) - throw new IllegalArgumentException("null argument"); - } - - static public void notFalse(boolean b, String s) - throws IllegalArgumentException { - if(b == false) - throw new IllegalArgumentException(s); - } - static public void notNull(Object obj, String s) - throws IllegalArgumentException { - if(obj == null) - throw new IllegalArgumentException(s); - } -} diff --git a/java/gjt/Bargauge.java b/java/gjt/Bargauge.java deleted file mode 100644 index 27be8afad7b..00000000000 --- a/java/gjt/Bargauge.java +++ /dev/null @@ -1,80 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A bargauge which can be filled (wholly or partially) with a - * client-specified color. Fill color is specified at - * construction time; both fill color and fill percent may be - * set after construction time.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ThreeDRectangle - * @see gjt.test.BargaugeTest - */ -public class Bargauge extends Canvas { - private double percentFill = 0; - private ThreeDRectangle border = new ThreeDRectangle(this); - private Color fillColor; - - public Bargauge(Color fillColor) { - setFillColor(fillColor); - } - public void setFillColor(Color fillColor) { - this.fillColor = fillColor; - } - public void setFillPercent(double percentage) { - Assert.notFalse(percentage >= 0 && percentage <= 100); - percentFill = percentage; - } - public void resize(int w, int h) { - reshape(location().x, location().y, w, h); - } - public void reshape(int x, int y, int w, int h) { - super.reshape(x,y,w,h); - border.resize(w,h); - } - public Dimension minimumSize() { return preferredSize(); } - - public Dimension preferredSize() { - int w = border.getThickness() * 3; - return new Dimension(w, w*4); - } - public void paint(Graphics g) { - border.raise(); - border.paint(); - fill(); - } - public void fill() { - Graphics g = getGraphics(); - - if((g != null) && (percentFill > 0)) { - Rectangle b = border.getInnerBounds(); - int fillw = b.width; - int fillh = b.height; - - if(b.width > b.height) fillw *= percentFill/100; - else fillh *= percentFill/100; - - g.setColor(fillColor); - border.clearInterior(); - - if(b.width > b.height) - g.fillRect(b.x, b.y, fillw, b.height); - else - g.fillRect(b.x, b.y + b.height - fillh, - b.width, fillh); - } - } - protected String paramString() { - Dimension size = size(); - Orientation orient = size.width > size.height ? - Orientation.HORIZONTAL : - Orientation.VERTICAL; - String str = "fill percent=" + percentFill + "," + - "orientation=" + orient + "," + - "color" + fillColor; - return str; - } -} diff --git a/java/gjt/Border.java b/java/gjt/Border.java deleted file mode 100644 index ba80ef2e76a..00000000000 --- a/java/gjt/Border.java +++ /dev/null @@ -1,105 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A panel containing a single component, around which a border - * is drawn. Of course, the single component may be a - * container which may contain other components, so a Border - * can surround multiple components.<p> - * - * Thickness of the border, and the gap between the Component - * and the border are specified at time of construction. - * Default border thickness is 2 - default gap is 0.<p> - * - * Border color may be set via setLineColor(Color).<p> - * - * Border employs a DrawnRectangle to paint the border. Derived - * classes are free to override DrawnRectangle border() if they - * wish to use an extension of DrawnRectangle for drawing their - * border.<p> - * - * The following code snippet, from gjt.test.BorderTest creates - * and AWT Button, and embeds the button in a border. That - * border is then embedded in another border. The AWT Button - * winds up inside of a cyan border with a pixel width of 7, - * inside of a black border (pixel width 2):<p> - * - * <pre> - * private Border makeBorderedAWTButton() { - * Button button; - * Border cyanBorder, blackBorder; - * - * button = new Button("Button Inside Two Borders"); - * cyanBorder = new Border(button, 7); - * cyanBorder.setLineColor(Color.cyan); - * - * blackBorder = new Border(cyanBorder); - * - * return blackBorder; - * } - *</pre> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see DrawnRectangle - * @see ThreeDBorder - * @see EtchedBorder - * @see gjt.test.BorderTest - */ -public class Border extends Panel { - protected int thickness; - protected int gap; - protected DrawnRectangle border; - - protected static int _defaultThickness = 2; - protected static int _defaultGap = 0; - - public Border(Component borderMe) { - this(borderMe, _defaultThickness, _defaultGap); - } - public Border(Component borderMe, int thickness) { - this(borderMe, thickness, _defaultGap); - } - public Border(Component borderMe, int thickness, int gap) { - this.thickness = thickness; - this.gap = gap; - - setLayout(new BorderLayout()); - add("Center", borderMe); - } - public Insets insets() { - return new Insets(thickness+gap, thickness+gap, - thickness+gap, thickness+gap); - } - public Rectangle getInnerBounds() { - return border().getInnerBounds(); - } - public void setLineColor(Color c) { - border().setLineColor(c); - } - public Color getLineColor() { - return border().getLineColor(); - } - public void paint(Graphics g) { - border().paint(); - } - public void resize(int w, int h) { - Point location = location(); - reshape(location.x, location.y, w, h); - } - public void reshape(int x, int y, int w, int h) { - super.reshape(x, y, w, h); - border().resize(w, h); - } - protected String paramString() { - return super.paramString() + ",border=" + - border().toString() + ",thickness=" + thickness - + ",gap=" + gap; - } - protected DrawnRectangle border() { - if(border == null) - border = new DrawnRectangle(this, thickness); - return border; - } -} diff --git a/java/gjt/Box.java b/java/gjt/Box.java deleted file mode 100644 index 8feda366942..00000000000 --- a/java/gjt/Box.java +++ /dev/null @@ -1,81 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A Panel containing a single component; an etched rectangle is - * drawn around the component, and a Label is centered at the top - * of the rectangle. Of course, the single component may be - * a container, and therefore a Box may surround many components. - * <p> - * - * Both the Component around which the box is drawn, and the - * String drawn at the top of the box are specified at - * construction time.<p> - * - * Etching of the box is controlled by etchedIn() and - * etchedOut(). Default etching is etched in.<p> - * - * <em>Note: AWT 1.0.2 contains a bug which causes the - * Label.CENTER argument of the Label created for the title - * to be ignored, under Win95. Therefore, under Win95, the - * title will be off-center.</em><p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see EtchedRectangle - * @see gjt.test.BoxTest - */ -public class Box extends Panel { - private EtchedRectangle box = new EtchedRectangle(this); - private Label titleLabel; - - public Box(Component surrounded, String title) { - this(surrounded, new Label(title, Label.CENTER)); - } - public Box(Component surrounded, Label label) { - Assert.notNull(surrounded); - Assert.notNull(label); - - titleLabel = label; - - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints gbc = new GridBagConstraints(); - - setLayout(gbl); - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbc.anchor = GridBagConstraints.NORTH; - gbl.setConstraints(titleLabel, gbc); - add(titleLabel); - - gbc.insets = new Insets(0,10,10,10); - gbc.anchor = GridBagConstraints.CENTER; - gbc.weighty = 1.0; - gbc.weightx = 1.0; - gbc.fill = GridBagConstraints.BOTH; - gbl.setConstraints(surrounded,gbc); - add(surrounded); - } - public void etchedIn () { box.etchedIn (); } - public void etchedOut() { box.etchedOut(); } - public void paint (Graphics g) { box.paint(); } - - public void resize(int w, int h) { - reshape(location().x, location().y, w, h); - } - public void reshape(int x, int y, int w, int h) { - super.reshape(x,y,w,h); - - FontMetrics fm = titleLabel.getFontMetrics( - titleLabel.getFont()); - int top = insets().top + fm.getAscent(); - Dimension size = size(); - - box.reshape(0, top, size.width-1, size.height-top-1); - } - protected String paramString() { - return super.paramString() + ",etching=" + - (box.isEtchedIn() ? Etching.IN : Etching.OUT) + - ",title=" + titleLabel; - } -} diff --git a/java/gjt/BulletinLayout.java b/java/gjt/BulletinLayout.java deleted file mode 100644 index 848a280de03..00000000000 --- a/java/gjt/BulletinLayout.java +++ /dev/null @@ -1,100 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * Lays out components as though they were pinned to - * a bulletin board.<p> - * - * Components are simply reshaped to their location and their - * preferred size. BulletinLayout is preferrable to setting - * a container's layout manager to null and explicitly positioning - * and sizing components.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - */ -public class BulletinLayout implements LayoutManager { - public BulletinLayout() { - } - public void addLayoutComponent(String name, Component comp) { - } - public void removeLayoutComponent(Component comp) { - } - public Dimension preferredLayoutSize(Container target) { - Insets insets = target.insets(); - Dimension dim = new Dimension(0,0); - int ncomponents = target.countComponents(); - Component comp; - Dimension d; - Rectangle preferredBounds = new Rectangle(0,0); - Rectangle compPreferredBounds; - - for (int i = 0 ; i < ncomponents ; i++) { - comp = target.getComponent(i); - - if(comp.isVisible()) { - d = comp.preferredSize(); - compPreferredBounds = - new Rectangle(comp.location()); - compPreferredBounds.width = d.width; - compPreferredBounds.height = d.height; - - preferredBounds = - preferredBounds.union(compPreferredBounds); - } - } - dim.width += insets.left + insets.right; - dim.height += insets.top + insets.bottom; - - return dim; - } - public Dimension minimumLayoutSize(Container target) { - Insets insets = target.insets(); - Dimension dim = new Dimension(0,0); - int ncomponents = target.countComponents(); - Component comp; - Dimension d; - Rectangle minimumBounds = new Rectangle(0,0); - Rectangle compMinimumBounds; - - for (int i = 0 ; i < ncomponents ; i++) { - comp = target.getComponent(i); - - if(comp.isVisible()) { - d = comp.minimumSize(); - compMinimumBounds = - new Rectangle(comp.location()); - compMinimumBounds.width = d.width; - compMinimumBounds.height = d.height; - - minimumBounds = - minimumBounds.union(compMinimumBounds); - } - } - dim.width += insets.left + insets.right; - dim.height += insets.top + insets.bottom; - - return dim; - } - public void layoutContainer(Container target) { - Insets insets = target.insets(); - int ncomponents = target.countComponents(); - Component comp; - Dimension ps; - Point loc; - - for (int i = 0 ; i < ncomponents ; i++) { - comp = target.getComponent(i); - - if(comp.isVisible()) { - ps = comp.preferredSize(); - loc = comp.location(); - - comp.reshape(insets.left + loc.x, - insets.top + loc.y, - ps.width, ps.height); - } - } - } -} diff --git a/java/gjt/ButtonPanel.java b/java/gjt/ButtonPanel.java deleted file mode 100644 index 6fc72ecaab2..00000000000 --- a/java/gjt/ButtonPanel.java +++ /dev/null @@ -1,51 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * Button panel employs a BorderLayout to lay out a Separator in - * the north, and a Panel to which Buttons are added in the - * center.<p> - * - * Buttons may be added to the panel via two methods: - * <dl> - * <dd> void add(Button) - * <dd> Button add(String) - * </dl> - * <p> - * - * Button add(String) creates a Button and adds it to the - * panel, then returns the Button created, as a convenience to - * clients so that they do not have to go through the pain - * and agony of creating an ImageButton.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see MessageDialog - * @see QuestionDialog - * @see YesNoDialog - * @see gjt.test.DialogTest - * @see gjt.test.ComponentScrollerTest - */ -public class ButtonPanel extends Panel { - Panel buttonPanel = new Panel(); - Separator separator = new Separator(); - - public ButtonPanel() { - setLayout(new BorderLayout(0,5)); - add("North", separator); - add("Center", buttonPanel); - } - public void add(Button button) { - buttonPanel.add(button); - } - public Button add(String buttonLabel) { - Button addMe = new Button(buttonLabel); - buttonPanel.add(addMe); - return addMe; - } - protected String paramString() { - return super.paramString() + "buttons=" + - countComponents(); - } -} diff --git a/java/gjt/CardPanel.java b/java/gjt/CardPanel.java deleted file mode 100644 index c2ab1a9033c..00000000000 --- a/java/gjt/CardPanel.java +++ /dev/null @@ -1,48 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * CardPanel employs a BorderLayout to lay out North and Center - * panels; extensions of CardPanel must implement - * Component viewSelector(). The component returned from - * Component viewSelector() is centered in the North panel, and - * should contain UI controls that allow selection of the - * component to be displayed in the Center panel.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see IconCardPanel - * @see ChoiceCardPanel - * @see gjt.test.ChoiceCardPanelTest - * @see gjt.test.IconCardPanelTest - */ -public abstract class CardPanel extends Panel { - private Panel north, center; - private CardLayout cards; - - abstract public Component viewSelector(); - - public CardPanel() { - center = new Panel(); - north = new Panel(); - - setLayout(new BorderLayout()); - center.setLayout(cards = new CardLayout()); - north.setLayout (new BorderLayout()); - - add("North", north); - add("Center", center); - } - public void addNotify() { - super.addNotify(); - north.add("Center", viewSelector()); - north.add("South", new Separator()); - } - protected void addView(String name, Component component) { - center.add(name, component); - } - protected void showView(String name) { - cards.show(center, name); - } -} diff --git a/java/gjt/ChoiceCardPanel.java b/java/gjt/ChoiceCardPanel.java deleted file mode 100644 index 6273e03a5aa..00000000000 --- a/java/gjt/ChoiceCardPanel.java +++ /dev/null @@ -1,53 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * ChoiceCardPanel is an extension of CardPanel which presents - * an awt.Choice for selecting the panel to be displayed - * in the center panel.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see CardPanel - * @see IconCardPanel - * @see gjt.test.IconCardPanelTest - * @see gjt.test.ChoiceCardPanelTest - */ -public class ChoiceCardPanel extends CardPanel { - private ChoiceViewSelector viewSelector; - - public ChoiceCardPanel() { - viewSelector = new ChoiceViewSelector(this); - } - public Component viewSelector() { - return viewSelector; - } - public void addChoice(String name, - Component component) { - viewSelector.addItem(name); - super.addView(name, component); - } -} - -class ChoiceViewSelector extends Panel { - private ChoiceCardPanel mvp; - private Choice choice; - - public ChoiceViewSelector(ChoiceCardPanel panel) { - setLayout(new FlowLayout()); - add(choice = new Choice()); - mvp = panel; - } - public void addItem(String name) { - choice.addItem(name); - } - public boolean handleEvent(Event event) { - if(event.id == Event.ACTION_EVENT) { - if(event.target instanceof Choice) { - mvp.showView(choice.getSelectedItem()); - } - } - return super.handleEvent(event); - } -} diff --git a/java/gjt/ColumnLayout.java b/java/gjt/ColumnLayout.java deleted file mode 100644 index bc51b44e456..00000000000 --- a/java/gjt/ColumnLayout.java +++ /dev/null @@ -1,154 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * ColumnLayout lays out components in a column. At - * construction time, both horizontal orientation and vertical - * orientation may be specified, along with the gap to use - * between components.<p> - * - * Horizontal orientation must be one of the following: - * <dl> - * <dd> LEFT - * <dd> CENTER - * <dd> RIGHT - * </dl> - * - * Vertical orientation must be one of the following: - * <dl> - * <dd> TOP - * <dd> CENTER - * <dd> BOTTOM - * </dl> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see Orientation - * @see RowLayout - */ -public class ColumnLayout implements LayoutManager { - static private int _defaultGap = 5; - - private int gap; - private Orientation horizontalOrientation; - private Orientation verticalOrientation; - - public ColumnLayout() { - this(Orientation.CENTER, - Orientation.CENTER, _defaultGap); - } - public ColumnLayout(int gap) { - this(Orientation.CENTER, Orientation.CENTER, gap); - } - public ColumnLayout(Orientation horizontalOrient, - Orientation verticalOrient) { - this(horizontalOrient, verticalOrient, _defaultGap); - } - public ColumnLayout(Orientation horizontalOrient, - Orientation verticalOrient, int gap) { - Assert.notFalse(gap >= 0); - Assert.notFalse( - horizontalOrient == Orientation.LEFT || - horizontalOrient == Orientation.CENTER || - horizontalOrient == Orientation.RIGHT); - Assert.notFalse( - verticalOrient == Orientation.TOP || - verticalOrient == Orientation.CENTER || - verticalOrient == Orientation.BOTTOM); - - this.gap = gap; - this.verticalOrientation = verticalOrient; - this.horizontalOrientation = horizontalOrient; - } - - public void addLayoutComponent(String name, - Component comp) { - } - public void removeLayoutComponent(Component comp) { - } - - public Dimension preferredLayoutSize(Container target) { - Insets insets = target.insets(); - Dimension dim = new Dimension(0,0); - int ncomponents = target.countComponents(); - Component comp; - Dimension d; - - for (int i = 0 ; i < ncomponents ; i++) { - comp = target.getComponent(i); - - if(comp.isVisible()) { - d = comp.preferredSize(); - if(i > 0) - dim.height += gap; - - dim.height += d.height; - dim.width = Math.max(d.width, dim.width); - } - } - dim.width += insets.left + insets.right; - dim.height += insets.top + insets.bottom; - return dim; - } - public Dimension minimumLayoutSize(Container target) { - Insets insets = target.insets(); - Dimension dim = new Dimension(0,0); - int ncomponents = target.countComponents(); - Component comp; - Dimension d; - - for (int i = 0 ; i < ncomponents ; i++) { - comp = target.getComponent(i); - - if(comp.isVisible()) { - d = comp.minimumSize(); - - dim.width = Math.max(d.width, dim.width); - dim.height += d.height; - - if(i > 0) dim.height += gap; - } - } - dim.width += insets.left + insets.right; - dim.height += insets.top + insets.bottom; - - return dim; - } - public void layoutContainer(Container target) { - Insets insets = target.insets(); - int top = insets.top; - int left = 0; - int ncomponents = target.countComponents(); - Dimension preferredSize = target.preferredSize(); - Dimension targetSize = target.size(); - Component comp; - Dimension ps; - - if(verticalOrientation == Orientation.CENTER) - top += (targetSize.height/2) - - (preferredSize.height/2); - else if(verticalOrientation == Orientation.BOTTOM) - top = targetSize.height - preferredSize.height + - insets.top; - - for (int i = 0 ; i < ncomponents ; i++) { - comp = target.getComponent(i); - left = insets.left; - - if(comp.isVisible()) { - ps = comp.preferredSize(); - - if(horizontalOrientation == Orientation.CENTER) - left = (targetSize.width/2) - (ps.width/2); - else if( - horizontalOrientation == Orientation.RIGHT) { - left = targetSize.width - ps.width - - insets.right; - } - comp.reshape(left,top,ps.width,ps.height); - top += ps.height + gap; - } - } - } -} diff --git a/java/gjt/ComponentScroller.java b/java/gjt/ComponentScroller.java deleted file mode 100644 index 3aef71c4ea2..00000000000 --- a/java/gjt/ComponentScroller.java +++ /dev/null @@ -1,42 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * Scrolls any component. Component to be scrolled may be a - * container, so ultimately many components may be scrolled - * at once.<p> - * - * Component to be scrolled may be specified at construction - * time, or may be set after construction via - * void setComponent(Component).<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see BulletinLayout - * @see Scroller - * @see ScrollerLayout - * @see ImageScroller - * @see gjt.test.ComponentScrollerTest - */ -public class ComponentScroller extends Scroller { - private Component scrollMe; - - public ComponentScroller() { - } - public ComponentScroller(Component component) { - setComponent(component); - } - public void setComponent(Component component) { - scrollMe = component; - viewport.setLayout(new BulletinLayout()); - viewport.add (scrollMe); - viewport.move (0,0); - } - public void scrollTo(int x, int y) { - scrollMe.move(-x,-y); - } - public Dimension getScrollAreaSize() { - return scrollMe.preferredSize(); - } -} diff --git a/java/gjt/DialogClient.java b/java/gjt/DialogClient.java deleted file mode 100644 index 7e67cea758e..00000000000 --- a/java/gjt/DialogClient.java +++ /dev/null @@ -1,20 +0,0 @@ -package gjt; - -import java.awt.Dialog; - -/** - * DialogClients are notified when the Dialog with which they - * are associated is dismissed. A reference to the dismissed - * Dialog is passed as a parameter of dialogDismissed() in case - * a DialogClient is a client of more than one Dialog.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see MessageDialog - * @see QuestionDialog - * @see YesNoDialog - * @see gjt.test.DialogTest - */ -public interface DialogClient { - abstract public void dialogDismissed(Dialog d); -} diff --git a/java/gjt/DrawingPanel.java b/java/gjt/DrawingPanel.java deleted file mode 100644 index cda3fd69431..00000000000 --- a/java/gjt/DrawingPanel.java +++ /dev/null @@ -1,72 +0,0 @@ -package gjt; - -import java.awt.*; -import gjt.rubberband.*; - -/** - * An extension of gjt.rubberband.RubberbandPanel which serves - * as a panel used for drawing simple shapes (lines, rectangles, - * and ellipses). The shapes may be filled (except for lines, - * of course), and the color of the shapes may be specified.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see gjt.rubberband.RubberbandPanel - * @see gjt.rubberband.RubberbandEllipse - * @see gjt.rubberband.RubberbandLine - * @see gjt.rubberband.RubberbandRectangle - * @see gjt.test.RubberbandTest - * @see gjt.test.ToolbarTest - */ -public class DrawingPanel extends RubberbandPanel { - private Rubberband rbLine, rbRect, rbEllipse; - private Color color; - private boolean fill; - - public DrawingPanel() { - rbLine = new RubberbandLine (this); - rbRect = new RubberbandRectangle(this); - rbEllipse = new RubberbandEllipse (this); - - setRubberband(rbLine); - } - public void drawLines () { setRubberband(rbLine); } - public void drawRectangles() { setRubberband(rbRect); } - public void drawEllipses () { setRubberband(rbEllipse); } - - public void setColor(Color color) { this.color = color; } - public Color getColor() { return color; } - - public void setFill(boolean b) { fill = b; } - public boolean getFill() { return fill; } - - public boolean mouseUp(Event event, int x, int y) { - Rubberband rb = getRubberband(); - Graphics g = getGraphics(); - - super.mouseUp(event, x, y); - g.setColor(color); - - if(rb == rbLine) drawLine (rb, g); - else if(rb == rbRect) drawRectangle(rb, g); - else if(rb == rbEllipse) drawEllipse (rb, g); - - return true; - } - protected void drawLine(Rubberband rb, Graphics g) { - Point anchor = rb.getAnchor(), end = rb.getEnd(); - g.drawLine(anchor.x, anchor.y, end.x, end.y); - } - protected void drawRectangle(Rubberband rb, Graphics g) { - Rectangle r = rb.bounds(); - - if(fill) g.fillRect(r.x, r.y, r.width, r.height); - else g.drawRect(r.x, r.y, r.width, r.height); - } - protected void drawEllipse(Rubberband rb, Graphics g) { - Rectangle r = rb.bounds(); - - if(fill) g.fillArc(r.x, r.y, r.width, r.height, 0, 360); - else g.drawArc(r.x, r.y, r.width, r.height, 0, 360); - } -} diff --git a/java/gjt/DrawnRectangle.java b/java/gjt/DrawnRectangle.java deleted file mode 100644 index e96fd8d3673..00000000000 --- a/java/gjt/DrawnRectangle.java +++ /dev/null @@ -1,136 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A Rectangle which draws itself inside of a Component.<p> - * - * DrawnRectangles may have their thickness and line color set, - * and are capable of reporting their inner bounds (the area - * inside the lines).<p> - * - * Default thickness is 2.<p> - * - * If not set explicitly, the line color used is three shades - * darker than the background color of the Component being - * drawn into.<p> - * - * DrawnRectangles may be clear()ed, which clears both the - * exterior (the lines) and the interior (the area inside of - * the lines) of the DrawnRectangle.<p> - * - * DrawnRectangles may also be fill()ed with a specified color - * by calling fill(Color), or by calling setFillColor(Color) - * followed by fill().<p> - * - * By default, the fill Color is the background color of the - * Component drawn into.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ThreeDRectangle - * @see EtchedRectangle - * @see Border - * @see EtchedBorder - * @see ThreeDBorder - * @see gjt.test.DrawnRectangleTest - */ -public class DrawnRectangle extends Rectangle { - protected static int _defaultThickness = 2; - - protected Component drawInto; - private int thick; - private Color lineColor, fillColor; - - public DrawnRectangle(Component drawInto) { - this(drawInto, _defaultThickness, 0, 0, 0, 0); - } - public DrawnRectangle(Component drawInto, int thick) { - this(drawInto, thick, 0, 0, 0, 0); - } - public DrawnRectangle(Component drawInto, int x, int y, - int w, int h) { - this(drawInto, _defaultThickness, x, y, w, h); - } - public DrawnRectangle(Component drawInto, int thick, - int x, int y, int w, int h) { - Assert.notNull(drawInto); - Assert.notFalse(thick > 0); - - this.drawInto = drawInto; - this.thick = thick; - reshape(x,y,w,h); - } - public Component component() {return drawInto; } - public int getThickness () {return thick; } - public void setThickness (int thick) {this.thick = thick; } - - public void setLineColor(Color lineColor) { - this.lineColor = lineColor; - } - public void setFillColor(Color fillColor) { - this.fillColor = fillColor; - } - public void fill() { - fill(getFillColor()); - } - public Color getLineColor() { - if(lineColor == null) - lineColor = - drawInto.getBackground().darker().darker().darker(); - return lineColor; - } - public Color getFillColor() { - if(fillColor == null) - fillColor = drawInto.getBackground(); - return fillColor; - } - public Rectangle getInnerBounds() { - return new Rectangle(x+thick, y+thick, - width-(thick*2), height-(thick*2)); - } - public void paint() { - Graphics g = drawInto.getGraphics(); - paintFlat(g, getLineColor()); - } - private void paintFlat(Graphics g, Color color) { - if(g != null) { - g.setColor(color); - for(int i=0; i < thick; ++i) - g.drawRect(x+i, y+i, - width-(i*2)-1, height-(i*2)-1); - } - } - public void clearInterior() { - fill(drawInto.getBackground()); - } - public void clearExterior() { - paintFlat(drawInto.getGraphics(), - drawInto.getBackground()); - } - public void clear() { - clearExterior(); - clearInterior(); - } - public void fill(Color color) { - Graphics g = drawInto.getGraphics(); - - if(g != null) { - Rectangle r = getInnerBounds(); - g.setColor(color); - g.fillRect(r.x, r.y, r.width, r.height); - setFillColor(color); - } - } - public String toString() { - return super.toString() + "[" + paramString() + "]"; - } - public String paramString() { - return "color=" + getLineColor() + ",thickness=" + - thick + ",fillColor=" + getFillColor(); - } - protected Color brighter() { - return - getLineColor().brighter().brighter().brighter().brighter(); - } -} diff --git a/java/gjt/EtchedBorder.java b/java/gjt/EtchedBorder.java deleted file mode 100644 index 09ff845014b..00000000000 --- a/java/gjt/EtchedBorder.java +++ /dev/null @@ -1,59 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * An extension of Border that draws an etched border. - * - * Drawn etchedIn by default, drawing style used by paint() is - * controlled by etchedIn() and etchedOut(). Note that - * etchedIn() and etchedOut() do not result in anything being - * painted, but only set the state for the next call to paint(). - * To set the state and paint in one operation, use - * paintEtchedIn() and paintEtchedOut().<p> - * - * The current state of the border may be obtained by calling - * isEtchedIn().<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see Border - * @see ThreeDRectangle - * @see gjt.test.BorderTest - */ -public class EtchedBorder extends Border { - public EtchedBorder(Component borderMe) { - this(borderMe, _defaultThickness, _defaultGap); - } - public EtchedBorder(Component borderMe, - int borderThickness) { - this(borderMe, borderThickness, _defaultGap); - } - public EtchedBorder(Component borderMe, - int borderThickness, int gap) { - super(borderMe, borderThickness, gap); - } - public void etchedIn() { - ((EtchedRectangle)border()).etchedIn(); - } - public void etchedOut() { - ((EtchedRectangle)border()).etchedOut(); - } - public void paintEtchedIn() { - ((EtchedRectangle)border()).paintEtchedIn (); - } - public void paintEtchedOut() { - ((EtchedRectangle)border()).paintEtchedOut(); - } - public boolean isEtchedIn() { - return ((EtchedRectangle)border()).isEtchedIn(); - } - protected String paramString() { - return super.paramString() + (EtchedRectangle)border(); - } - protected DrawnRectangle border() { - if(border == null) - border = new EtchedRectangle(this, thickness); - return border; - } -} diff --git a/java/gjt/EtchedRectangle.java b/java/gjt/EtchedRectangle.java deleted file mode 100644 index b8026d42f8d..00000000000 --- a/java/gjt/EtchedRectangle.java +++ /dev/null @@ -1,97 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A DrawnRectangle that draws an etched border.<p> - * - * Drawn etched in by default, drawing style used by paint() is - * controlled by etchedIn() and etchedOut(). Note that - * etchedIn() and etchedOut() do not result in anything being - * painted, but only set the state for the next call to paint(). - * To set the state and paint in one operation, use - * paintEtchedIn() and paintEtchedOut().<p> - * - * Although it is permissible to set the thickness of - * EtchedRectangles, they tend to loose the etching effect - * if thickness is greater than 4.<p> - * - * The current state of the rectangle may be obtained by - * calling isEtchedIn(). - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see DrawnRectangle - * @see ThreeDRectangle - * @see gjt.test.DrawnRectangleTest - */ -public class EtchedRectangle extends DrawnRectangle { - protected static Etching _defaultEtching = Etching.IN; - private Etching etching; - - public EtchedRectangle(Component drawInto) { - this(drawInto, _defaultEtching, - _defaultThickness, 0, 0, 0, 0); - } - public EtchedRectangle(Component drawInto, int thickness) { - this(drawInto, _defaultEtching, thickness, 0, 0, 0, 0); - } - public EtchedRectangle(Component drawInto, int x, int y, - int w, int h) { - this(drawInto, _defaultEtching, - _defaultThickness, x, y, w, h); - } - public EtchedRectangle(Component drawInto, int thickness, - int x, int y, - int w, int h) { - this(drawInto, _defaultEtching, thickness, x, y, w, h); - } - public EtchedRectangle(Component drawInto, Etching etching, - int thickness, int x, int y, - int w, int h) { - super(drawInto, thickness, x, y, w, h); - this.etching = etching; - } - public void etchedIn () { etching = Etching.IN; } - public void etchedOut () { etching = Etching.OUT; } - public boolean isEtchedIn() { return etching == Etching.IN;} - - public void paint() { - if(etching == Etching.IN) paintEtchedIn(); - else paintEtchedOut(); - } - public void paintEtchedIn() { - Graphics g = drawInto.getGraphics(); - if(g != null) - paintEtched(g, getLineColor(), brighter()); - - etchedIn(); - } - public void paintEtchedOut() { - Graphics g = drawInto.getGraphics(); - if(g != null) - paintEtched(g, brighter(), getLineColor()); - - etchedOut(); - } - public String paramString() { - return super.paramString() + "," + etching; - } - private void paintEtched(Graphics g, - Color topLeft, - Color bottomRight) { - int thickness = getThickness(); - int w = width - thickness; - int h = height - thickness; - - g.setColor(topLeft); - for(int i=0; i < thickness/2; ++i) - g.drawRect(x+i, y+i, w, h); - - g.setColor(bottomRight); - - for(int i=0; i < thickness/2; ++i) - g.drawRect(x+(thickness/2)+i, - y+(thickness/2)+i, w, h); - } -} diff --git a/java/gjt/Etching.java b/java/gjt/Etching.java deleted file mode 100644 index ad40d9caaea..00000000000 --- a/java/gjt/Etching.java +++ /dev/null @@ -1,22 +0,0 @@ -package gjt; - -/** - * Constants for Etching. - * - * This class may not be instantiated. - * - * @version 1.0, Apr 11 1996 - * @author David Geary - */ -public class Etching { - public static final Etching OUT = new Etching(); - public static final Etching IN = new Etching(); - - public String toString() { - if(this == Etching.OUT) - return getClass().getName() + "=OUT"; - else - return getClass().getName() + "=IN"; - } - private Etching() { } -} diff --git a/java/gjt/ExclusiveImageButtonPanel.java b/java/gjt/ExclusiveImageButtonPanel.java deleted file mode 100644 index f1d0878a499..00000000000 --- a/java/gjt/ExclusiveImageButtonPanel.java +++ /dev/null @@ -1,47 +0,0 @@ -package gjt; - -import java.awt.Image; - -/** - * An ImageButtonPanel which fits all of its ImageButtons with - * a StickyImageButtonController. ExclusiveImageButtonPanel - * relies upon its superclass' controller: a - * RadioImageButtonPanelController, which ensures that only one - * of the ImageButtons is selected at a time.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ImageButton - * @see ImageButtonPanel - * @see gjt.test.ToolbarTest - */ -public class ExclusiveImageButtonPanel extends - ImageButtonPanel { - public ExclusiveImageButtonPanel(Orientation orient) { - this(orient, 5); - } - public ExclusiveImageButtonPanel(Orientation orient, - int gap) { - super(orient, gap); - } - public ExclusiveImageButtonPanel(Orientation orient, - Orientation horient, - Orientation vorient, - int gap) { - super(orient, horient, vorient, gap); - } - public void add(ImageButton button) { - super.add(button); - new StickyImageButtonController(button); - } - public ImageButton add(Image image) { - ImageButton button = super.add(image); - new StickyImageButtonController(button); - return button; - } - public ImageButton add(Image image, String name) { - ImageButton button = super.add(image, name); - new StickyImageButtonController(button); - return button; - } -} diff --git a/java/gjt/FontDialog.java b/java/gjt/FontDialog.java deleted file mode 100644 index 182ca582884..00000000000 --- a/java/gjt/FontDialog.java +++ /dev/null @@ -1,362 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A dialog used for selecting a font. FontDialog is - * constructed with a Frame, DialogClient, initial font to - * display, and boolean that indicates modality.<p> - * - * FontDialog contains a preview panel which previews the - * currently selected font. Updating of the preview panel is - * triggered by a preview button at the bottom of the dialog.<p> - * - * FontDialog contains 3 methods which define the labels for - * the buttons it contains: - * <dl> - * <dd> String getPreviewButtonLabel() - * <dd> String getOkButtonLabel() - * <dd> String getCancelButtonLabel() - * </dl><p> - * - * By default the 3 methods return "Preview", "Ok" and "Cancel" - * respectively. FontDialog may be extended and the 3 methods - * overridden to customize the labels displayed in the - * buttons.<p> - * - * FontDialog uses Toolkit to get a list of fonts by invoking - * Toolkit.getFontList(). This is done in the getFontNames() - * method, which may be overridden by extensions of FontDialog - * in case the standard set of font names are inadequate.<p> - * - * Finally, font sizes are obtained by the getFontSizes() - * method. FontDialog defines 8 sizes by default: 8, 12, 14, - * 16, 18, 24, 48 and 64. Extensions of FontDialog may override - * getFontSizes() to provide a different list of sizes.<p> - * - * See gjt.test.FontDialogTest for an example of an extension - * of FontDialog which overrides the methods discussed above.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see java.awt.Dialog - * @see java.awt.Toolkit - * @see DialogClient - * @see gjt.test.FontDialogTest - */ -public class FontDialog extends Dialog { - private static String _defaultSizes[] = - { "8", "12", "14", "16", "18", "24", "48", "64" }; - - private FontPanel fontPanel; - private Font fontSelected; - private DialogClient client; - - public FontDialog(Frame frame, - DialogClient client, - Font font, // initial font - boolean modal) { - super(frame, "Select A Font", modal); - this.client = client; - - setLayout(new BorderLayout()); - add("Center", fontPanel = new FontPanel(this, font)); - } - public boolean handleEvent(Event event) { - if(event.id == Event.WINDOW_DESTROY) - done(null); - - return super.handleEvent(event); - } - public String[] getFontNames() { - return getToolkit().getFontList(); - } - public String[] getFontSizes() { - return _defaultSizes; - } - - public String getPreviewButtonLabel() { return "Preview"; } - public String getOkButtonLabel () { return "Ok"; } - public String getCancelButtonLabel () { return "Cancel"; } - - public void show() { - Point frameLoc = getParent().location(); - reshape(frameLoc.x + 50, frameLoc.x + 50, 550, 450); - super.show(); - } - public void done(Font font) { - fontSelected = font; - client.dialogDismissed(this); - hide (); - dispose(); - } - public Font getFontSelected() { - return fontSelected; - } - public void listSelectedInPicker() { - fontPanel.getPreviewButton().requestFocus(); - } -} - -class FontPanel extends Panel { - private static Font defaultFont = - new Font("TimesRoman", Font.PLAIN, 12); - - private FontPreviewPanel preview; - private FontSelectionPanel fsp; - - public FontPanel(FontDialog dialog, Font f) { - Font font = f == null ? defaultFont : f; - - setLayout(new BorderLayout()); - add("North", preview = new FontPreviewPanel ()); - add("Center", fsp = - new FontSelectionPanel(dialog, preview, font)); - } - public Button getPreviewButton() { - return fsp.getPreviewButton(); - } -} - -class FontPreviewPanel extends Panel { - TextField textField = new TextField(); - Box box = new Box(textField, "Preview"); - - public FontPreviewPanel() { - textField.setEditable(false); - - setLayout(new BorderLayout()); - add("Center", box); - } - public void setPreviewFont(Font font) { - String name = font.getName(); - String size = String.valueOf(font.getSize()); - String style = new String(); - - if(font.isPlain () == true) style = "Plain"; - else { - if(font.isBold () == true) style += "Bold"; - if(font.isItalic() == true) style += "Italic"; - } - textField.setFont(font); - textField.setText(name + " " + style + " " + size); - retrofitPreviewPanel(); - } - private void retrofitPreviewPanel() { - Dimension tfps, tfs; - FontPanel fontPanel = (FontPanel)getParent(); - - tfps = textField.preferredSize(); - tfs = textField.size(); - - if(tfps.width != tfs.width || - tfps.height != tfs.height) { - fontPanel.invalidate(); - fontPanel.getParent().validate(); - box.repaint(); // Only necessary on Win95 - } - } -} - -class FontSelectionPanel extends Panel { - private FontPickerPanel picker; - private FontButtonsPanel buttons; - private FontPreviewPanel preview; - private Font initialFont; - - public FontSelectionPanel(FontDialog dialog, - FontPreviewPanel preview, - Font initialFont) { - this.preview = preview; - this.initialFont = initialFont; - - picker = new FontPickerPanel (dialog, initialFont); - buttons = new FontButtonsPanel(dialog, picker, preview); - - setLayout(new BorderLayout()); - add("Center", picker); - add("South", buttons); - } - public void addNotify() { - super.addNotify(); - preview.setPreviewFont(initialFont); - } - public Button getPreviewButton() { - return buttons.getPreviewButton(); - } -} - -class FontPickerPanel extends Panel { - private FontDialog dialog; - private Button previewButton; - private List fonts = new List(); - private List styles = new List(); - private List sizes = new List(); - private Font initialFont; - - public FontPickerPanel(FontDialog dialog, - Font initialFont) { - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints gbc = new GridBagConstraints(); - Label family = new Label("Family"); - Label style = new Label("Style"); - Label size = new Label("Size"); - - this.initialFont = initialFont; - this.dialog = dialog; - - populateFonts (); - populateStyles(); - populateSizes (); - - setLayout(gbl); - - gbc.anchor = GridBagConstraints.NORTH; - gbc.gridwidth = 1; - gbl.setConstraints(family, gbc); add(family); - gbl.setConstraints(style, gbc); add(style); - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbl.setConstraints(size, gbc); add(size); - - gbc.gridwidth = 1; - gbc.weighty = 1.0; - gbc.weightx = 1.0; - gbc.fill = GridBagConstraints.BOTH; - gbl.setConstraints(fonts, gbc); add(fonts); - gbl.setConstraints(styles, gbc); add(styles); - gbl.setConstraints(sizes, gbc); add(sizes); - } - public boolean handleEvent(Event event) { - if(event.id == Event.LIST_SELECT) { - dialog.listSelectedInPicker(); - return true; - } - return false; - } - public void addNotify() { - super.addNotify(); - String initialFamily = initialFont.getName(); - int initialSize = initialFont.getSize(); - int initialStyle = initialFont.getStyle(); - - styles.select(initialStyle); - - for(int i=0; i < fonts.countItems(); ++i) { - String nextFamily = fonts.getItem(i); - if(nextFamily.equals(initialFamily)) - fonts.select(i); - } - for(int i=0; i < sizes.countItems(); ++i) { - String nextSize = sizes.getItem(i); - if(nextSize.equals(String.valueOf(initialSize))) - sizes.select(i); - } - } - public String fontSelected() { - return fonts.getSelectedItem (); - } - public String styleSelected() { - return styles.getSelectedItem(); - } - public int sizeSelected() { - String szstring = sizes.getSelectedItem(); - - if(szstring != null) { - Integer integer = new Integer(szstring); - return integer.intValue(); - } - else - return 0; - } - private void populateFonts() { - String names[] = dialog.getFontNames(); - - for(int i=0; i < names.length; ++i) { - fonts.addItem(names[i]); - } - } - private void populateSizes() { - String sizeArray[] = dialog.getFontSizes(); - - for(int i=0; i < sizeArray.length; ++i) { - sizes.addItem(sizeArray[i]); - } - } - private void populateStyles() { - styles.addItem("Plain"); - styles.addItem("Bold"); - styles.addItem("Italic"); - styles.addItem("BoldItalic"); - } -} - -class FontButtonsPanel extends Panel { - private FontDialog dialog; - private FontPickerPanel picker; - private FontPreviewPanel preview; - private Button previewButton, - okButton, - cancelButton; - - public FontButtonsPanel(FontDialog dialog, - FontPickerPanel picker, - FontPreviewPanel preview) { - this.picker = picker; - this.preview = preview; - this.dialog = dialog; - - add(previewButton = - new Button(dialog.getPreviewButtonLabel())); - add(cancelButton = - new Button(dialog.getCancelButtonLabel())); - add(okButton = - new Button(dialog.getOkButtonLabel())); - } - public void addNotify() { - super.addNotify(); - cancelButton.requestFocus(); - } - public boolean action(Event event, Object object) { - Button button = (Button)event.target; - boolean handledEvent = true; - - if(event.target == previewButton) { - Font selectedFont = fontSelected(); - - if(selectedFont != null) { - preview.setPreviewFont(selectedFont); - okButton.requestFocus(); - } - } - else if(event.target == okButton) - dialog.done(fontSelected()); - else if(event.target == cancelButton) - dialog.done(null); - else - handledEvent = false; - - return handledEvent; - } - public Button getPreviewButton() { - return previewButton; - } - private Font fontSelected() { - String font = picker.fontSelected (); - String style = picker.styleSelected(); - int size = picker.sizeSelected (); - int istyle = Font.PLAIN; - - if(font != null && style != null && size > 0) { - if(style.equals("Bold")) istyle = Font.BOLD; - if(style.equals("Plain")) istyle = Font.PLAIN; - if(style.equals("Italic")) istyle = Font.ITALIC; - - if(style.equals("BoldItalic")) - istyle = Font.BOLD + Font.ITALIC; - - return new Font(font, istyle, size); - } - else - return null; - } -} diff --git a/java/gjt/GJT.DSP b/java/gjt/GJT.DSP deleted file mode 100644 index e2060a0ad72..00000000000 --- a/java/gjt/GJT.DSP +++ /dev/null @@ -1,456 +0,0 @@ -# Microsoft Developer Studio Project File - Name="GJT" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 5.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Java Virtual Machine Java Project" 0x0809 - -CFG=GJT - Java Virtual Machine Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "GJT.MAK". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "GJT.MAK" CFG="GJT - Java Virtual Machine Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "GJT - Java Virtual Machine Release" (based on\ - "Java Virtual Machine Java Project") -!MESSAGE "GJT - Java Virtual Machine Debug" (based on\ - "Java Virtual Machine Java Project") -!MESSAGE - -# Begin Project -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -JAVA=jvc.exe - -!IF "$(CFG)" == "GJT - Java Virtual Machine Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "" -# PROP BASE Intermediate_Dir "" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "..\classes-r" -# PROP Intermediate_Dir "" -# PROP Target_Dir "" -# ADD BASE JAVA /O -# ADD JAVA /O - -!ELSEIF "$(CFG)" == "GJT - Java Virtual Machine Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "" -# PROP BASE Intermediate_Dir "" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "..\classes" -# PROP Intermediate_Dir "" -# PROP Target_Dir "" -# ADD BASE JAVA /g -# ADD JAVA /g - -!ENDIF - -# Begin Target - -# Name "GJT - Java Virtual Machine Release" -# Name "GJT - Java Virtual Machine Debug" -# Begin Source File - -SOURCE=.\Assert.java -# End Source File -# Begin Source File - -SOURCE=.\test\AttributesPanel.java -# End Source File -# Begin Source File - -SOURCE=.\Bargauge.java -# End Source File -# Begin Source File - -SOURCE=.\test\BargaugeTest.java -# End Source File -# Begin Source File - -SOURCE=.\image\BleachImageFilter.java -# End Source File -# Begin Source File - -SOURCE=.\test\BleachImageFilterTest.java -# End Source File -# Begin Source File - -SOURCE=.\Border.java -# End Source File -# Begin Source File - -SOURCE=.\test\BorderTest.java -# End Source File -# Begin Source File - -SOURCE=.\Box.java -# End Source File -# Begin Source File - -SOURCE=.\test\BoxTest.java -# End Source File -# Begin Source File - -SOURCE=.\BulletinLayout.java -# End Source File -# Begin Source File - -SOURCE=.\test\BumpAnimationTest.java -# End Source File -# Begin Source File - -SOURCE=.\ButtonPanel.java -# End Source File -# Begin Source File - -SOURCE=.\CardPanel.java -# End Source File -# Begin Source File - -SOURCE=.\ChoiceCardPanel.java -# End Source File -# Begin Source File - -SOURCE=.\test\ChoiceCardPanelTest.java -# End Source File -# Begin Source File - -SOURCE=.\animation\CollisionArena.java -# End Source File -# Begin Source File - -SOURCE=.\animation\CollisionDetector.java -# End Source File -# Begin Source File - -SOURCE=.\ColumnLayout.java -# End Source File -# Begin Source File - -SOURCE=.\test\ColumnLayoutTest.java -# End Source File -# Begin Source File - -SOURCE=.\ComponentScroller.java -# End Source File -# Begin Source File - -SOURCE=.\test\ComponentScrollerTest.java -# End Source File -# Begin Source File - -SOURCE=.\test\ConnectionsPanel.java -# End Source File -# Begin Source File - -SOURCE=.\DialogClient.java -# End Source File -# Begin Source File - -SOURCE=.\test\DialogTest.java -# End Source File -# Begin Source File - -SOURCE=.\image\DissolveFilter.java -# End Source File -# Begin Source File - -SOURCE=.\DrawingPanel.java -# End Source File -# Begin Source File - -SOURCE=.\DrawnRectangle.java -# End Source File -# Begin Source File - -SOURCE=.\test\DrawnRectangleTest.java -# End Source File -# Begin Source File - -SOURCE=.\animation\EdgeCollisionDetector.java -# End Source File -# Begin Source File - -SOURCE=.\EtchedBorder.java -# End Source File -# Begin Source File - -SOURCE=.\EtchedRectangle.java -# End Source File -# Begin Source File - -SOURCE=.\Etching.java -# End Source File -# Begin Source File - -SOURCE=.\ExclusiveImageButtonPanel.java -# End Source File -# Begin Source File - -SOURCE=.\FontDialog.java -# End Source File -# Begin Source File - -SOURCE=.\test\FontDialogTest.java -# End Source File -# Begin Source File - -SOURCE=.\GJTDialog.java -# End Source File -# Begin Source File - -SOURCE=.\IconCardPanel.java -# End Source File -# Begin Source File - -SOURCE=.\test\IconCardPanelTest.java -# End Source File -# Begin Source File - -SOURCE=.\ImageButton.java -# End Source File -# Begin Source File - -SOURCE=.\ImageButtonController.java -# End Source File -# Begin Source File - -SOURCE=.\ImageButtonEvent.java -# End Source File -# Begin Source File - -SOURCE=.\ImageButtonPanel.java -# End Source File -# Begin Source File - -SOURCE=.\ImageButtonPanelController.java -# End Source File -# Begin Source File - -SOURCE=.\test\ImageButtonTest.java -# End Source File -# Begin Source File - -SOURCE=.\ImageCanvas.java -# End Source File -# Begin Source File - -SOURCE=.\image\ImageDissolver.java -# End Source File -# Begin Source File - -SOURCE=.\test\ImageDissolverTest.java -# End Source File -# Begin Source File - -SOURCE=.\ImageScroller.java -# End Source File -# Begin Source File - -SOURCE=.\test\ImageScrollerTest.java -# End Source File -# Begin Source File - -SOURCE=.\LabelCanvas.java -# End Source File -# Begin Source File - -SOURCE=.\test\LabelCanvasTest.java -# End Source File -# Begin Source File - -SOURCE=.\MessageDialog.java -# End Source File -# Begin Source File - -SOURCE=.\test\MessageDialogTest.java -# End Source File -# Begin Source File - -SOURCE=.\MouseController.java -# End Source File -# Begin Source File - -SOURCE=.\test\OccupationOracle.java -# End Source File -# Begin Source File - -SOURCE=.\Orientation.java -# End Source File -# Begin Source File - -SOURCE=.\animation\Playfield.java -# End Source File -# Begin Source File - -SOURCE=.\ProgressDialog.java -# End Source File -# Begin Source File - -SOURCE=.\QuestionDialog.java -# End Source File -# Begin Source File - -SOURCE=.\RadioImageButtonPanelController.java -# End Source File -# Begin Source File - -SOURCE=.\RowLayout.java -# End Source File -# Begin Source File - -SOURCE=.\test\RowLayoutTest.java -# End Source File -# Begin Source File - -SOURCE=.\rubberband\Rubberband.java -# End Source File -# Begin Source File - -SOURCE=.\rubberband\RubberbandEllipse.java -# End Source File -# Begin Source File - -SOURCE=.\rubberband\RubberbandLine.java -# End Source File -# Begin Source File - -SOURCE=.\rubberband\RubberbandPanel.java -# End Source File -# Begin Source File - -SOURCE=.\rubberband\RubberbandRectangle.java -# End Source File -# Begin Source File - -SOURCE=.\test\RubberbandTest.java -# End Source File -# Begin Source File - -SOURCE=.\Scroller.java -# End Source File -# Begin Source File - -SOURCE=.\ScrollerLayout.java -# End Source File -# Begin Source File - -SOURCE=.\SelectionEvent.java -# End Source File -# Begin Source File - -SOURCE=.\Separator.java -# End Source File -# Begin Source File - -SOURCE=.\test\SeparatorTest.java -# End Source File -# Begin Source File - -SOURCE=.\animation\Sequence.java -# End Source File -# Begin Source File - -SOURCE=.\test\SimpleAnimationTest.java -# End Source File -# Begin Source File - -SOURCE=.\test\SimpleBargaugeTest.java -# End Source File -# Begin Source File - -SOURCE=.\SpringyImageButtonController.java -# End Source File -# Begin Source File - -SOURCE=.\animation\Sprite.java -# End Source File -# Begin Source File - -SOURCE=.\animation\SpriteCollisionDetector.java -# End Source File -# Begin Source File - -SOURCE=.\StateButton.java -# End Source File -# Begin Source File - -SOURCE=.\StateButtonController.java -# End Source File -# Begin Source File - -SOURCE=.\test\StateButtonTest.java -# End Source File -# Begin Source File - -SOURCE=.\StickyImageButtonController.java -# End Source File -# Begin Source File - -SOURCE=.\Stopwatch.java -# End Source File -# Begin Source File - -SOURCE=.\StopwatchClient.java -# End Source File -# Begin Source File - -SOURCE=.\test\TenPixelBorder.java -# End Source File -# Begin Source File - -SOURCE=.\ThreeDBorder.java -# End Source File -# Begin Source File - -SOURCE=.\ThreeDBorderStyle.java -# End Source File -# Begin Source File - -SOURCE=.\ThreeDRectangle.java -# End Source File -# Begin Source File - -SOURCE=.\test\TitledPanel.java -# End Source File -# Begin Source File - -SOURCE=.\Toolbar.java -# End Source File -# Begin Source File - -SOURCE=.\test\ToolbarTest.java -# End Source File -# Begin Source File - -SOURCE=.\test\TwoDrinkersAnimationTest.java -# End Source File -# Begin Source File - -SOURCE=.\test\UnitTest.java -# End Source File -# Begin Source File - -SOURCE=.\Util.java -# End Source File -# Begin Source File - -SOURCE=.\YesNoDialog.java -# End Source File -# End Target -# End Project diff --git a/java/gjt/GJT.DSW b/java/gjt/GJT.DSW deleted file mode 100644 index fb82e10ad55..00000000000 --- a/java/gjt/GJT.DSW +++ /dev/null @@ -1,29 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 5.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "GJT"=.\GJT.DSP - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - diff --git a/java/gjt/GJTDialog.java b/java/gjt/GJTDialog.java deleted file mode 100644 index 7fc0bd39f40..00000000000 --- a/java/gjt/GJTDialog.java +++ /dev/null @@ -1,51 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A base class for gjt dialog classes, this concrete class - * establishes the relationship between a dialog and its - * client (DialogClient).<p> - * - * Note that show() is overridden to ensure that the dialog is - * centered in the frame which is specified as its parent. This - * is necessary due to a bug in the Win95 implementation of the - * AWT (version 1.0.2) that causes dialogs to be displayed at - * a screen coordinate of 0,0. While the overridden show() is - * not necessary under non-Win95 Java implementations, it - * alleviates the Win95 bug and results in no dire consequences - * on other platforms.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see MessageDialog - * @see QuestionDialog - * @see YesNoDialog - * @see ProgressDialog - * @see gjt.test.DialogTest - */ -public class GJTDialog extends Dialog { - protected DialogClient client; - - public GJTDialog(Frame frame, - String title, - DialogClient client, - boolean modal) { - super(frame, title, modal); - setClient(client); - } - public void setClient(DialogClient client) { - this.client = client; - } - public void show() { // Fixes bug under Win95 - Dimension frameSize = getParent().size(); - Point frameLoc = getParent().location(); - Dimension mySize = size(); - int x,y; - - x = frameLoc.x + (frameSize.width/2) -(mySize.width/2); - y = frameLoc.y + (frameSize.height/2)-(mySize.height/2); - reshape(x,y,size().width,size().height); - super.show(); - } -} diff --git a/java/gjt/IconCardPanel.java b/java/gjt/IconCardPanel.java deleted file mode 100644 index 78940bf8f4f..00000000000 --- a/java/gjt/IconCardPanel.java +++ /dev/null @@ -1,55 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A CardPanel whose Component viewSelector() returns - * a panel with image buttons to control the selection of the - * panel to be displayed beneath the view selector panel.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see CardPanel - * @see ChoiceCardpanel - * @see gjt.test.IconCardPanelTest - */ -public class IconCardPanel extends CardPanel { - private ImageButtonPanel viewSelector; - - public IconCardPanel() { - viewSelector = new IconViewSelector(this); - } - public Component viewSelector() { - return viewSelector; - } - public void addImageButton(Image image, - String name, - Component component) { - ImageButton newButton; - - viewSelector.add( - newButton = new ImageButton(image), name); - newButton.setController( - new StickyImageButtonController(newButton)); - super.addView(name, component); - } -} - -class IconViewSelector extends ImageButtonPanel { - private IconCardPanel mvp; - - public IconViewSelector(IconCardPanel panel) { - super(Orientation.HORIZONTAL); - setLayout(new FlowLayout()); - mvp = panel; - } - public boolean handleEvent(Event event) { - if(event.id == Event.MOUSE_DOWN) { - if(event.target instanceof ImageButton) { - ImageButton ib = (ImageButton)event.target; - mvp.showView(getButtonName(ib)); - } - } - return super.handleEvent(event); - } -} diff --git a/java/gjt/ImageButton.java b/java/gjt/ImageButton.java deleted file mode 100644 index 07bdeff0ef8..00000000000 --- a/java/gjt/ImageButton.java +++ /dev/null @@ -1,209 +0,0 @@ -package gjt; - -import java.awt.*; -import java.awt.image.FilteredImageSource; - -import gjt.image.BleachImageFilter; - -/** - * An Image painted in a Canvas, bordered by a ThreeDRectangle. - * <p> - * - * ImageButtons have two constructors, both of which take an - * Image. The Image passed to the constructor must not be null; - * this is enforced by an assertion.<p> - * - * Default border thickness is 2 pixels - thickness may be set - * at construction time only.<p> - * - * Event handling is delegated to an ImageButtonController. By - * default, all ImageButtons are fitted with an instance of - * SpringyImageButtonController, however, - * setController(ImageButtonController) may be used to fit an - * ImageButton with a different derivation of - * ImageButtonController after construction.<p> - * - * ImageButtons ensure that their Images are completely loaded - * before they are displayed.<p> - * - * Drawn either raised or inset, current state may be queried - * via the isRaised() method.<p> - * - * disable() disables response to input and repaints the image - * with a bleached version. enable() restores the original - * image and enables response to input. The intensity of the - * bleaching effect may be controlled (for all ImageButtons) - * via the static setBleachPercent(int) method.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ThreeDRectangle - * @see ImageButtonController - * @see ImageButtonEvent - * @see SpringyImageButtonController - * @see StickyImageButtonController - * @see BleachImageFilter - * @see gjt.test.ImageButtonTest - */ -public class ImageButton extends Canvas { - private static BleachImageFilter _bleachFilter; - private static int _bleachPercent = 50; - private static int _offset = 1; - private static int _defaultThickness = 2; - - private ThreeDRectangle border = new ThreeDRectangle(this); - private boolean isDisabled = false; - private Dimension preferredSize = new Dimension(0,0); - private int thickness; - private Image image, disabledImage; - private ImageButtonController controller; - - public static int setBleachPercent() { - return _bleachPercent; - } - public static void getBleachPercent(int p) { - _bleachPercent = p; - } - public ImageButton(Image image) { - this(image, _defaultThickness, null); - } - public ImageButton(Image image, - ImageButtonController controller) { - this(image, _defaultThickness, controller); - } - public ImageButton(Image image, int thickness, - ImageButtonController controller) { - Assert.notNull(image); - Assert.notFalse(thickness > 0); - - if(controller == null) - this.controller = - new SpringyImageButtonController(this); - else - this.controller = controller; - - border.setThickness(this.thickness = thickness); - setImage(image); - } - public void setImage(Image image) { - Util.waitForImage(this, this.image = image); - - preferredSize.width = image.getWidth (this) + - (2*thickness); - preferredSize.height = image.getHeight(this) + - (2*thickness); - } - public Dimension minimumSize() { - return preferredSize; - } - public Dimension preferredSize() { - return preferredSize; - } - public boolean isRaised () { return border.isRaised(); } - public boolean isDisabled() { return isDisabled; } - - public void enable() { - isDisabled = false; - repaint(); - } - public void disable() { - isDisabled = true; - - if(disabledImage == null) - createDisabledImage(); - - repaint(); - } - public void resize(int w, int h) { - reshape(location().x, location().y, w, h); - } - public void reshape(int x, int y, int w, int h) { - super.reshape(x,y,w,h); - border.resize(w,h); - } - public void paint(Graphics g) { - if(isRaised()) paintRaised(); - else paintInset (); - } - public void paintInset() { - Point upperLeft = findUpperLeft(); - Graphics g = getGraphics(); - Image image = isDisabled() ? - disabledImage : this.image; - Dimension size = size(); - - if(g != null) { - border.clearInterior(); - g.drawImage(image, - upperLeft.x + thickness + _offset, - upperLeft.y + thickness + _offset,this); - - g.setColor(getBackground().darker()); - for(int i=0; i < _offset; ++i) { - g.drawLine(thickness+i,thickness+i, - size.width-thickness-i,thickness+i); - g.drawLine(thickness+i,thickness+i, - thickness+i,size.height-thickness-i); - } - border.paintInset(); - } - } - public void paintRaised() { - Point upperLeft = findUpperLeft(); - Graphics g = getGraphics(); - Image image = isDisabled() ? - disabledImage : this.image; - - if(g != null) { - border.clearInterior(); - g.drawImage(image, upperLeft.x + thickness, - upperLeft.y + thickness, this); - border.paintRaised(); - } - } - public boolean isInside(int x, int y) { - Dimension size = size(); - return x >= 0 && x < size.width && y >= 0 && - y < size.height; - } - public void setController(ImageButtonController controller){ - this.controller = controller; - } - public ImageButtonController getController() { - return controller; - } - public boolean mouseDown(Event event, int x, int y) { - if(isDisabled()) return false; - else return controller.mouseDown(event,x,y); - } - public boolean mouseUp(Event event, int x, int y) { - if(isDisabled()) return false; - else return controller.mouseUp(event,x,y); - } - public boolean mouseDrag(Event event, int x, int y) { - if(isDisabled()) return false; - else return controller.mouseDrag(event,x,y); - } - - private void createDisabledImage() { - if(_bleachFilter == null) - _bleachFilter = - new BleachImageFilter(_bleachPercent); - - if(_bleachPercent != _bleachFilter.percent()) - _bleachFilter.percent(_bleachPercent); - - FilteredImageSource fis = - new FilteredImageSource(image.getSource(), - _bleachFilter); - - Util.waitForImage(this, disabledImage=createImage(fis)); - } - private Point findUpperLeft() { - Dimension size = size(); - return new Point((size.width/2) - - (preferredSize.width/2), - (size.height/2) - - (preferredSize.height/2)); - } -} diff --git a/java/gjt/ImageButtonController.java b/java/gjt/ImageButtonController.java deleted file mode 100644 index 0f6aa6f4add..00000000000 --- a/java/gjt/ImageButtonController.java +++ /dev/null @@ -1,79 +0,0 @@ -package gjt; -import java.awt.Event; - -/** - * A controller for an ImageButton, this abstract class - * establishes the association between itself and an ImageButton - * and delivers events to its ImageButton.<p> - * - * ImageButtonControllers must be constructed with an - * ImageButton; the ImageButton's controller gets set by - * ImageButtonController's constructor.<p> - * - * The ImageButton passed into the constructor must not be null; - * this is enforced by an assertion.<p> - * - * Methods defined in the MouseController interface are left - * for subclasses to implement. ImageButtonController defines - * mouseMove(), mouseEnter() and mouseExit() as no-ops, so - * that extensions of ImageButtonController only have to - * implement mouseDown(), mouseUp() and mouseDrag(). Note - * that extensions are still free to override mouseMove(), - * mouseEnter() and mouseExit() if desired.<p> - * - * Subclasses should also call the protected XXXButton(Event) - * methods below, where XXX is either arm, disarm, activate, or - * deactivate as appropriate. SpringyImageButtonController is - * a good example of this (so is StickyImageButtonController, - * but it is more complicated than it's springy sibling).<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see MouseController - * @see ImageButton - * @see ImageButtonEvent - * @see SpringyImageButtonController - * @see StickyImageButtonController - * @see gjt.test.ImageButtonTest - */ -public abstract class ImageButtonController - implements MouseController { - private ImageButton button; - - ImageButtonController(ImageButton button) { - Assert.notNull(button); - this.button = button; - button.setController(this); - } - public ImageButton getButton() { - return button; - } - public boolean mouseEnter(Event event, int x, int y) { - return false; - } - public boolean mouseExit (Event event, int x, int y) { - return false; - } - public boolean mouseMove (Event event, int x, int y) { - return false; - } - - protected void armButton(Event event) { - button.deliverEvent( - new ImageButtonEvent(button, - event, - ImageButtonEvent.ARM)); - } - protected void disarmButton(Event event) { - button.deliverEvent( - new ImageButtonEvent(button, - event, - ImageButtonEvent.DISARM)); - } - protected void activateButton(Event event) { - button.deliverEvent( - new ImageButtonEvent(button, - event, - ImageButtonEvent.ACTIVATE)); - } -} diff --git a/java/gjt/ImageButtonEvent.java b/java/gjt/ImageButtonEvent.java deleted file mode 100644 index bb7f196698f..00000000000 --- a/java/gjt/ImageButtonEvent.java +++ /dev/null @@ -1,103 +0,0 @@ -package gjt; - -import java.awt.Event; - -/** - * An extension of java.awt.Event, specifically designed for - * ImageButton events.<p> - * - * ImageButtonEvents are constructed with 3 arguments: - * <dl> - * <dd> ImageButton in which the event occurred - * <dd> The AWT event that triggered the image button event - * <dd> The id of the event. - * </dl> - * - * An ImageButtonEvent's id (the constructor's 3rd argument), - * must be one of the following: - * - * <dl> - * <dd> ImageButtonEvent.ARM - * <dd> ImageButtonEvent.DISARM - * <dd> ImageButtonEvent.ACTIVATE - * </dl> - * - * ImageButtonEvent has only a constructor and a paramString() - * method. Containers that contain ImageButtons should check - * for ImageButtonEvents like so: <p> - * - * <pre> - * // handleEvent(Event) method of a container that - * // contains ImageButtons. - * - * public boolean handleEvent(Event event) { - * if(event instanceof ImageButtonEvent) { - * ImageButtonEvent ibevent = - * (ImageButtonEvent)event; - * - * if(ibevent.isArmed()) { - * // do something for arming - * } - * if(ibevent.isDisarmed()) { - * // do something for disarming - * } - * if(ibevent.isActivated()) { - * // do something for activation - * } - * } - * } - * </pre> - * - * ImageButtonController is the only GJT class that creates - * ImageButtonEvents. - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ImageButton - * @see ImageButtonController - * @see SpringyImageButtonController - * @see StickyImageButtonController - * @see gjt.test.ImageButtonTest - */ -public class ImageButtonEvent extends Event { - public static final int ARM = 1; - public static final int DISARM = 2; - public static final int ACTIVATE = 3; - - private int eventType; - - public ImageButtonEvent(ImageButton button, - Event event, - int type) { - super(button, event.when, event.id, event.x, event.y, - event.key, event.modifiers, event.arg); - - Assert.notFalse(type == ARM || - type == DISARM || - type == ACTIVATE); - - eventType = type; - id = -1; - } - public boolean isArmed() { - return eventType == ARM; - } - public boolean isDisarmed() { - return eventType == DISARM; - } - public boolean isActivated() { - return eventType == ACTIVATE; - } - protected String paramString() { - String str = new String(); - - if(eventType == ImageButtonEvent.ARM) - str = "ARM"; - else if(eventType == ImageButtonEvent.DISARM) - str = "DISARM"; - else if(eventType == ImageButtonEvent.ACTIVATE) - str = "ACTIVATE"; - - return super.paramString() + str; - } -} diff --git a/java/gjt/ImageButtonPanel.java b/java/gjt/ImageButtonPanel.java deleted file mode 100644 index 0d033b7967b..00000000000 --- a/java/gjt/ImageButtonPanel.java +++ /dev/null @@ -1,106 +0,0 @@ -package gjt; - -import java.awt.*; -import java.util.Enumeration; -import java.util.Hashtable; - -/** - * A panel which contains a collection of ImageButtons, - * arranged either horizontally or vertically.<p> - * - * Handling of mouse events is delegated to an image button - * panel controller. By default, an image button panel is - * outfitted with an instance of RadioImageButtonPanelController - * which implements mutually exclusive selection behavior. - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ImageButton - * @see RadioImageButtonPanelController - * @see gjt.test.ToolbarTest - */ -public class ImageButtonPanel extends Panel { - static private int _defaultGap = 5; - - private Hashtable nameAndButtonPairs = new Hashtable(); - private ImageButtonPanelController controller; - - public ImageButtonPanel(Orientation orient) { - this(orient, Orientation.CENTER, - Orientation.CENTER, _defaultGap); - } - public ImageButtonPanel(Orientation orient, int gap) { - this(orient, Orientation.CENTER, - Orientation.CENTER, gap); - } - public ImageButtonPanel(Orientation orient, - Orientation horient, - Orientation vorient, int gap) { - Assert.notFalse(orient == Orientation.HORIZONTAL || - orient == Orientation.VERTICAL); - - if(orient == Orientation.VERTICAL) - setLayout(new ColumnLayout(horient, vorient, gap)); - else - setLayout(new RowLayout(horient, vorient, gap)); - - setController( - new RadioImageButtonPanelController(this)); - } - public void setController(ImageButtonPanelController c) { - this.controller = c; - } - public Insets insets() { return new Insets(10,10,10,10); } - - public ImageButton add(Image image, String name) { - ImageButton button = new ImageButton(image); - add(button); - nameAndButtonPairs.put(name, button); - return button; - } - public ImageButton add(Image image) { - return add(image, "noname"); - } - public void add(ImageButton button) { - add(button, "noname"); - } - public void add(ImageButton button, String name) { - nameAndButtonPairs.put(name, button); - super.add(button); - } - public ImageButton getButtonByName(String name) { - return (ImageButton)nameAndButtonPairs.get(name); - } - public String getButtonName(ImageButton button) { - Enumeration e = nameAndButtonPairs.keys(); - ImageButton nbutt; - String nstr; - - while(e.hasMoreElements()) { - nstr = (String)e.nextElement(); - nbutt = (ImageButton)nameAndButtonPairs.get(nstr); - - if(nbutt.equals(button)) - return nstr; - } - return null; - } - public void addSpacer(int sizeInPixels) { - Assert.notFalse(sizeInPixels > 0); - Canvas spacer = new Canvas(); - spacer.resize(sizeInPixels, sizeInPixels); - add(spacer); - } - public boolean mouseDown(Event event, int x, int y) { - return controller != null ? - controller.mouseDown(event,x,y) : false; - } - public boolean mouseDrag(Event event, int x, int y) { - return controller != null ? - controller.mouseDrag(event,x,y) : false; - } - public boolean mouseUp(Event event, int x, int y) { - return controller != null ? - controller.mouseUp(event,x,y) : false; - } -} diff --git a/java/gjt/ImageButtonPanelController.java b/java/gjt/ImageButtonPanelController.java deleted file mode 100644 index 74f900001b6..00000000000 --- a/java/gjt/ImageButtonPanelController.java +++ /dev/null @@ -1,47 +0,0 @@ -package gjt; - -import java.awt.Event; - -/** - * A controller for an ImageButtonPanel, this abstract class - * does nothing more than establish the association between an - * ImageButton and its controller.<p> - * - * ImageButtonControllers must be constructed with an - * ImageButtonPanel; the ImageButtonPanels' controller gets set - * by the constructor.<p> - * - * The ImageButton passed into the constructor must not be null; - * this is enforced by an assertion.<p> - * - * Methods defined in the MouseController interface are left - * for subclasses to implement.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see MouseController - * @see ImageButtonPanel - * @see gjt.test.Toolbar - */ -abstract class ImageButtonPanelController implements - MouseController { - private ImageButtonPanel panel; - - ImageButtonPanelController(ImageButtonPanel panel) { - Assert.notNull(panel); - this.panel = panel; - panel.setController(this); - } - public ImageButtonPanel panel() { - return panel; - } - public boolean mouseEnter(Event event, int x, int y) { - return false; - } - public boolean mouseExit (Event event, int x, int y) { - return false; - } - public boolean mouseMove (Event event, int x, int y) { - return false; - } -} diff --git a/java/gjt/ImageCanvas.java b/java/gjt/ImageCanvas.java deleted file mode 100644 index 49e3bc72f3f..00000000000 --- a/java/gjt/ImageCanvas.java +++ /dev/null @@ -1,31 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A Canvas that displays an image.<p> - * - * update() is overridden to call paint() directly, thus - * bypassing the default implementation of update() which - * erases the background of the canvas before calling paint(). - * This eliminates nasty flashing.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see Util - */ -class ImageCanvas extends Canvas { - private Image image; - - public ImageCanvas(Image image) { - this.image = image; - Util.waitForImage(this, image); - resize(image.getWidth(this), image.getHeight(this)); - } - public void paint(Graphics g) { - g.drawImage(image, 0, 0, this); - } - public void update(Graphics g) { - paint(g); - } -} diff --git a/java/gjt/ImageScroller.java b/java/gjt/ImageScroller.java deleted file mode 100644 index 79fdc86ea3c..00000000000 --- a/java/gjt/ImageScroller.java +++ /dev/null @@ -1,62 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * An extension of Scroller that smoothly scrolls an Image.<p> - * - * An Image must be supplied at construction time. The image - * may be reset any time after construction.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see Scroller - * @see ImageCanvas - * @see gjt.test.ScrollerTest - */ -public class ImageScroller extends Scroller { - private Image image; - private ScrollerImageCanvas canvas; - - public ImageScroller(Image image) { - viewport.setLayout(new BorderLayout()); - setImage(image); - } - public void resetImage(Image image) { - viewport.remove(canvas); - setImage(image); - invalidate(); - validate(); - } - public void scrollTo(int x, int y) { - Graphics g = canvas.getGraphics(); - if(g != null) { - g.translate(-x,-y); - g.drawImage(image, 0, 0, this); - } - } - public Dimension getScrollAreaSize() { - return new Dimension(image.getWidth(this), - image.getHeight(this)); - } - private void setImage(Image image) { - this.image = image; - hbar.setValue(0); - vbar.setValue(0); - viewport.add("Center", - canvas = new ScrollerImageCanvas(this, image)); - } -} - -class ScrollerImageCanvas extends ImageCanvas { - private ImageScroller scroller; - - public ScrollerImageCanvas(ImageScroller scroller, - Image image) { - super(image); - this.scroller = scroller; - } - public void paint(Graphics g) { - scroller.repaint(); - } -} diff --git a/java/gjt/LabelCanvas.java b/java/gjt/LabelCanvas.java deleted file mode 100644 index ba733249b76..00000000000 --- a/java/gjt/LabelCanvas.java +++ /dev/null @@ -1,93 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A selectable label. Clients can set the insets around the - * label via setInsets(Insets). - * - * LabelCanvases generate SelectionEvents when they are - * selected or deselected.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see SelectionEvent - * @see gjt.test.LabelCanvasTest - */ -public class LabelCanvas extends Canvas { - private String label; - private boolean selected = false; - private Insets insets = new Insets(2,2,2,2); - private Point labelLoc = new Point(0,0); - - public LabelCanvas(String label) { - this.label = label; - } - public void paint(Graphics g) { - if(selected == true) paintSelected(g); - else - g.drawString(label, labelLoc.x, labelLoc.y); - } - public void setInsets(Insets insets) { - this.insets = insets; - repaint(); - } - public String getLabel () { return label; } - public boolean isSelected() { return selected; } - public void select () { selected = true; repaint(); } - public void deselect () { selected = false; repaint(); } - - public void resize(int w, int h) { - reshape(location().x, location().y, w, h); - } - public void reshape(int x, int y, int w, int h) { - super.reshape(x, y, w, h); - labelLoc = labelLocation(getGraphics()); - } - public Dimension minimumSize() { - return preferredSize(); - } - public Dimension preferredSize() { - FontMetrics fm = getFontMetrics(getFont()); - return new Dimension( - insets.left + fm.stringWidth(label) + - insets.right, - insets.top + fm.getHeight() + - insets.bottom); - } - public boolean mouseDown(Event event, int x, int y) { - if(selected) deselect(); - else select (); - - int eventType = isSelected() ? - SelectionEvent.SELECT : - SelectionEvent.DESELECT; - - Event newEvent = new SelectionEvent(this, - event, - eventType); - deliverEvent(newEvent); - - return true; - } - protected void paintSelected(Graphics g) { - Point labelLoc = labelLocation(g); - - g.setColor(getForeground()); - g.fillRect(0,0,size().width,size().height); - g.setColor(getBackground()); - g.drawString(label, labelLoc.x, labelLoc.y); - } - protected String paramString() { - return super.paramString() + ",text=" + label; - } - private Point labelLocation(Graphics g) { - Dimension size = size(); - FontMetrics fm = g.getFontMetrics(); - - int x = (size.width/2) - (fm.stringWidth(label)/2); - int y = (size.height/2) + (fm.getAscent()/2) - - fm.getLeading(); - return new Point(x,y); - } -} diff --git a/java/gjt/Makefile b/java/gjt/Makefile deleted file mode 100644 index ef6e80748a7..00000000000 --- a/java/gjt/Makefile +++ /dev/null @@ -1,67 +0,0 @@ -# Makefile - -.SUFFIXES: .java .class - -JACE_WRAPPER = .. -CLASSDIR = $(JACE_WRAPPER)/classes -DOCDIR = $(JACE_WRAPPER)/doc - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: - javac -d ${JACE_WRAPPER}/classes $(files) - -clean: - rm -rf *~ - -realclean: clean - rm -rf $(JACE_WRAPPER)/classes/gjt - -files = Assert.java \ - Border.java \ - BulletinLayout.java \ - CardPanel.java \ - ChoiceCardPanel.java \ - ColumnLayout.java \ - ComponentScroller.java \ - DialogClient.java \ - DrawingPanel.java \ - DrawnRectangle.java \ - EtchedBorder.java \ - EtchedRectangle.java \ - Etching.java \ - ExclusiveImageButtonPanel.java \ - FontDialog.java \ - GJTDialog.java \ - IconCardPanel.java \ - ImageButton.java \ - ImageButtonController.java \ - ImageButtonEvent.java \ - ImageButtonPanel.java \ - ImageButtonPanelController.java \ - ImageCanvas.java \ - ImageScroller.java \ - LabelCanvas.java \ - MessageDialog.java \ - MouseController.java \ - Orientation.java \ - ProgressDialog.java \ - QuestionDialog.java \ - RadioImageButtonPanelController.java \ - RowLayout.java \ - Scroller.java \ - ScrollerLayout.java \ - SelectionEvent.java \ - Separator.java \ - SpringyImageButtonController.java \ - StateButton.java \ - StateButtonController.java \ - StickyImageButtonController.java \ - Stopwatch.java \ - StopwatchClient.java \ - ThreeDBorder.java \ - ThreeDBorderStyle.java \ - ThreeDRectangle.java \ - Toolbar.java \ - Util.java \ - YesNoDialog.java diff --git a/java/gjt/MessageDialog.java b/java/gjt/MessageDialog.java deleted file mode 100644 index 4b00bc7033f..00000000000 --- a/java/gjt/MessageDialog.java +++ /dev/null @@ -1,77 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A dialog that displays a message and comes equipped with an - * Ok button with which the dialog is dismissed.<p> - * - * Note that there is only one MessageDialog, that gets - * reused. Clients must call getMessageDialog() in order to - * access the one and only MessageDialog.<p> - * - * <em>Note: The 1.0.2 version of the AWT seems to have - * introduced a bug that causes pack() to work incorrectly - * under Win95.</em> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see GJTDialog - * @see gjt.test.MessageDialogTest - * @see gjt.test.DialogTest - */ -public class MessageDialog extends GJTDialog { - static private MessageDialog _theMessageDialog; - - private Button okButton; - private String message; - private ButtonPanel buttonPanel = new ButtonPanel(); - - static public MessageDialog getMessageDialog(Frame frame, - DialogClient client, - String title, - String message) { - if(_theMessageDialog == null) - _theMessageDialog = new MessageDialog(frame, - client, - title, - message); - else { - _theMessageDialog.setClient (client); - _theMessageDialog.setTitle (title); - _theMessageDialog.setMessage(message); - } - return _theMessageDialog; - } - private MessageDialog(Frame frame, DialogClient client, - String title, String message) { - super(frame, title, client, true); - okButton = buttonPanel.add("Ok"); - - setLayout(new BorderLayout()); - add("Center", new MessagePanel(message)); - add("South", buttonPanel); - pack(); - } - public void show() { - okButton.requestFocus(); - super.show(); - } - public boolean action(Event event, Object what) { - hide(); - client.dialogDismissed(this); - return true; - } - private void setMessage(String message) { - this.message = message; - } -} - -class MessagePanel extends Panel { - public MessagePanel(String message) { - add("Center", new Label(message, Label.CENTER)); - } - public Insets insets() { - return new Insets(10,10,10,10); - } -} diff --git a/java/gjt/MouseController.java b/java/gjt/MouseController.java deleted file mode 100644 index f044adee5ba..00000000000 --- a/java/gjt/MouseController.java +++ /dev/null @@ -1,32 +0,0 @@ -package gjt; - -import java.awt.Event; - -/** - * An interface for handling mouse events.<p> - * - * Components delegate handling of mouse events to a - * MouseController derivation.<p> - * - * For instance:<p> - *<pre> - * mouseDown(Event event, int x, int y) { - * return controller.mouseDown(event,x,y); - * } - *</pre> - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ImageButton - * @see ImageButtonController - * @see SpringyImageButtonController - * @see StickyImageButtonController - */ -public interface MouseController { - public boolean mouseEnter(Event event, int x, int y); - public boolean mouseExit (Event event, int x, int y); - - public boolean mouseMove (Event event, int x, int y); - public boolean mouseDown (Event event, int x, int y); - public boolean mouseUp (Event event, int x, int y); - public boolean mouseDrag (Event event, int x, int y); -} diff --git a/java/gjt/Orientation.java b/java/gjt/Orientation.java deleted file mode 100644 index f83b27451da..00000000000 --- a/java/gjt/Orientation.java +++ /dev/null @@ -1,87 +0,0 @@ -package gjt; - -/** - * Constants for orientations (and alignments).<p> - * - * This class may not be instantiated. - * - * @version 1.0, Apr 11 1996 - * @author David Geary - */ -public class Orientation { - public static final Orientation BAD = new Orientation(); - public static final Orientation NORTH = new Orientation(); - public static final Orientation SOUTH = new Orientation(); - public static final Orientation EAST = new Orientation(); - public static final Orientation WEST = new Orientation(); - public static final Orientation CENTER = new Orientation(); - public static final Orientation TOP = new Orientation(); - public static final Orientation LEFT = new Orientation(); - public static final Orientation RIGHT = new Orientation(); - public static final Orientation BOTTOM = new Orientation(); - - public static final Orientation HORIZONTAL = - new Orientation(); - public static final Orientation VERTICAL = - new Orientation(); - - static public Orientation fromString(String s) { - Orientation o = BAD; - - if(s.equals("NORTH") || s.equals("north")) o = NORTH; - else if(s.equals("SOUTH") || s.equals("south")) - o = SOUTH; - else if(s.equals("EAST") || s.equals("east")) - o = EAST; - else if(s.equals("WEST") || s.equals("west")) - o = WEST; - else if(s.equals("CENTER") || s.equals("center")) - o = CENTER; - else if(s.equals("TOP") || s.equals("top")) - o = TOP; - else if(s.equals("LEFT") || s.equals("left")) - o = LEFT; - else if(s.equals("RIGHT") || s.equals("right")) - o = RIGHT; - else if(s.equals("BOTTOM") || s.equals("bottom")) - o = BOTTOM; - else if(s.equals("VERTICAL") || s.equals("vertical")) - o = VERTICAL; - else if(s.equals("HORIZONTAL") || - s.equals("horizontal")) - o = HORIZONTAL; - - return o; - } - public String toString() { - String s = new String(); - - if(this == Orientation.NORTH) - s = getClass().getName() + "=NORTH"; - else if(this == Orientation.SOUTH) - s = getClass().getName() + "=SOUTH"; - else if(this == Orientation.EAST) - s = getClass().getName() + "=EAST"; - else if(this == Orientation.WEST) - s = getClass().getName() + "=WEST"; - else if(this == Orientation.CENTER) - s = getClass().getName() + "=CENTER"; - else if(this == Orientation.TOP) - s = getClass().getName() + "=TOP"; - else if(this == Orientation.LEFT) - s = getClass().getName() + "=LEFT"; - else if(this == Orientation.RIGHT) - s = getClass().getName() + "=RIGHT"; - else if(this == Orientation.BOTTOM) - s = getClass().getName() + "=BOTTOM"; - else if(this == Orientation.HORIZONTAL) - s = getClass().getName() + "=HORIZONTAL"; - else if(this == Orientation.VERTICAL) - s = getClass().getName() + "=VERTICAL"; - else if(this == Orientation.BAD) - s = getClass().getName() + "=BAD"; - - return s; - } - private Orientation() { } // Defeat instantiation -} diff --git a/java/gjt/ProgressDialog.java b/java/gjt/ProgressDialog.java deleted file mode 100644 index de7d4be1674..00000000000 --- a/java/gjt/ProgressDialog.java +++ /dev/null @@ -1,67 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A dialog that uses a bargauge to indicate progress made on a - * task that presumably takes some time to complete. - * - * ProgressDialog implements the singleton pattern: clients - * may only access the one and only ProgressDialog through the - * static getProgressDialog() method.<p> - * - * <em>Note: The 1.0.2 version of the AWT has introduced a - * bug that breaks the ProgressDialog under Motif - the - * bargauge does not function. This worked fine in 1.0.1.<em> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see GJTDialog - * @see Bargauge - * @see gjt.test.DialogTest - */ -public class ProgressDialog extends GJTDialog { - static private ProgressDialog _theProgressDialog; - static private int _preferredWidth = 400; - static private int _preferredHeight = 75; - static private Color _color; - static private boolean _dialogUp; - - private Bargauge bargauge; - - static public ProgressDialog getProgressDialog( - Frame frame, - String title, - Color color){ - if(_theProgressDialog == null) - _theProgressDialog = new ProgressDialog(frame, - title, - color); - else { - _theProgressDialog.setTitle (title); - _theProgressDialog.reset (); - } - return _theProgressDialog; - } - private ProgressDialog(Frame frame, - String title, - Color color) { - super(frame, title, null, true); - setLayout(new BorderLayout()); - add("Center", bargauge = new Bargauge(color)); - pack(); - } - public void setPercentComplete(double percent) { - bargauge.setFillPercent(percent); - bargauge.fill(); - - if(percent == 100) - hide(); - } - public void reset() { - bargauge.setFillPercent(0); - } - public Dimension preferredSize() { - return new Dimension(_preferredWidth, _preferredHeight); - } -} diff --git a/java/gjt/QuestionDialog.java b/java/gjt/QuestionDialog.java deleted file mode 100644 index 042b491e178..00000000000 --- a/java/gjt/QuestionDialog.java +++ /dev/null @@ -1,130 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A dialog that presents a prompt and a TextField into which - * a reply may be entered. Comes complete with an Ok button - * and a Cancel button, whose uses will be left to the - * imagination.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see GJTDialog - * @see gjt.test.DialogTest - */ -public class QuestionDialog extends GJTDialog { - static private int _defaultTextFieldSize = 20; - private Button okButton; - private Button cancelButton; - private String question; - private TextField textField; - private boolean wasCancelled; - private ButtonPanel buttonPanel = new ButtonPanel(); - - public QuestionDialog(Frame frame, DialogClient client, - String title, String question, - String initialResponse) { - this(frame, client, title, question, initialResponse, - _defaultTextFieldSize); - } - public QuestionDialog(Frame frame, DialogClient client, - String title, String question) { - this(frame, client, title, - question, null, _defaultTextFieldSize); - } - public QuestionDialog(Frame frame, DialogClient client, - String title, String question, - int textFieldSize) { - this(frame, client, title, - question, null, textFieldSize); - } - public QuestionDialog(Frame frame, DialogClient client, - String title, String question, - String initialResponse, - int textFieldSize) { - super(frame, title, client, true); - - QuestionPanel questionPanel; - - okButton = buttonPanel.add("Ok"); - cancelButton = buttonPanel.add("Cancel"); - - setLayout(new BorderLayout()); - add("North", questionPanel = - new QuestionPanel(this, question, - initialResponse, textFieldSize)); - add("South", buttonPanel); - textField = questionPanel.getTextField(); - pack(); - } - public boolean action(Event event, Object what) { - if(event.target == cancelButton) wasCancelled = true; - else wasCancelled = false; - - hide(); - dispose(); - client.dialogDismissed(this); - return true; - } - public void show() { - textField.requestFocus(); - super.show(); - } - public void returnInTextField() { - okButton.requestFocus(); - } - public TextField getTextField() { - return textField; - } - public String getAnswer() { - return textField.getText(); - } - public boolean wasCancelled() { - return wasCancelled; - } - private void setQuestion(String question) { - this.question = question; - } -} - -class QuestionPanel extends Panel { - private TextField field; - private QuestionDialog dialog; - - public QuestionPanel(QuestionDialog dialog, - String question) { - this(dialog, question, null, 0); - } - public QuestionPanel(QuestionDialog dialog, String question, - int columns) { - this(dialog, question, null, columns); - } - public QuestionPanel(QuestionDialog dialog, String question, - String initialResponse, int cols) { - this.dialog = dialog; - setLayout(new RowLayout()); - add(new Label(question)); - - if(initialResponse != null) { - if(cols != 0) - add(field=new TextField(initialResponse, cols)); - else - add(field=new TextField(initialResponse)); - } - else { - if(cols != 0) add(field = new TextField(cols)); - else add(field = new TextField()); - } - } - public TextField getTextField() { - return field; - } - public boolean action(Event event, Object what) { - dialog.returnInTextField(); - return false; - } - public Insets insets() { - return new Insets(10,10,10,10); - } -} diff --git a/java/gjt/RadioImageButtonPanelController.java b/java/gjt/RadioImageButtonPanelController.java deleted file mode 100644 index 8dc34d25bff..00000000000 --- a/java/gjt/RadioImageButtonPanelController.java +++ /dev/null @@ -1,45 +0,0 @@ -package gjt; - -import java.awt.Event; - -/** - * A controller for an ImageButtonPanel that ensures that only - * one ImageButton in its associated ImageButtonPanel is - * selected at a time.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ImageButtonPanelController - * @see ImageButton - * @see ImageButtonPanel - * @see gjt.test.ToolbarTest - */ -class RadioImageButtonPanelController - extends ImageButtonPanelController { - ImageButton down; - - public RadioImageButtonPanelController( - ImageButtonPanel panel) { - super(panel); - } - public boolean mouseDown(Event event, int x, int y) { - ImageButton button; - - if(event.target instanceof ImageButton) { - button = (ImageButton)event.target; - if(down == button) return false; - - if(down != null) - down.paintRaised(); - - down = button; - } - return false; - } - public boolean mouseUp(Event event, int x, int y) { - return false; - } - public boolean mouseDrag(Event event, int x, int y) { - return false; - } -} diff --git a/java/gjt/RowLayout.java b/java/gjt/RowLayout.java deleted file mode 100644 index eecd074c34f..00000000000 --- a/java/gjt/RowLayout.java +++ /dev/null @@ -1,153 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * RowLayout lays out components in a row. At construction - * time, both horizontal orientation and vertical orientation - * may be specified, along with the gap to use between - * components.<p> - * - * Horizontal orientation must be one of the following: - * <dl> - * <dd> LEFT - * <dd> CENTER - * <dd> RIGHT - * </dl> - * - * Vertical orientation must be one of the following: - * <dl> - * <dd> TOP - * <dd> CENTER - * <dd> BOTTOM - * </dl> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ColumnLayout - * @see Orientation - */ -public class RowLayout implements LayoutManager { - static private int _defaultGap = 5; - - private int gap; - private Orientation verticalOrientation; - private Orientation horizontalOrientation; - - public RowLayout() { - this(Orientation.CENTER, - Orientation.CENTER, _defaultGap); - } - public RowLayout(int gap) { - this(Orientation.CENTER, Orientation.CENTER, gap); - } - public RowLayout(Orientation horizontalOrient, - Orientation verticalOrient) { - this(horizontalOrient, verticalOrient, _defaultGap); - } - public RowLayout(Orientation horizontalOrient, - Orientation verticalOrient, int gap) { - Assert.notFalse(gap >= 0); - Assert.notFalse( - horizontalOrient == Orientation.LEFT || - horizontalOrient == Orientation.CENTER || - horizontalOrient == Orientation.RIGHT); - Assert.notFalse( - verticalOrient == Orientation.TOP || - verticalOrient == Orientation.CENTER || - verticalOrient == Orientation.BOTTOM); - - this.gap = gap; - this.verticalOrientation = verticalOrient; - this.horizontalOrientation = horizontalOrient; - } - - public void addLayoutComponent(String name, Component comp) { - } - public void removeLayoutComponent(Component comp) { - } - - public Dimension preferredLayoutSize(Container target) { - Insets insets = target.insets(); - Dimension dim = new Dimension(0,0); - int ncomponents = target.countComponents(); - Component comp; - Dimension d; - - for (int i = 0 ; i < ncomponents ; i++) { - comp = target.getComponent(i); - - if(comp.isVisible()) { - d = comp.preferredSize(); - - dim.width += d.width; - dim.height = Math.max(d.height, dim.height); - - if(i > 0) dim.width += gap; - } - } - dim.width += insets.left + insets.right; - dim.height += insets.top + insets.bottom; - - return dim; - } - public Dimension minimumLayoutSize(Container target) { - Insets insets = target.insets(); - Dimension dim = new Dimension(0,0); - int ncomponents = target.countComponents(); - Component comp; - Dimension d; - - for (int i = 0 ; i < ncomponents ; i++) { - comp = target.getComponent(i); - - if(comp.isVisible()) { - d = comp.minimumSize(); - - dim.width += d.width; - dim.height = Math.max(d.height, dim.height); - - if(i > 0) dim.width += gap; - } - } - dim.width += insets.left + insets.right; - dim.height += insets.top + insets.bottom; - - return dim; - } - public void layoutContainer(Container target) { - Insets insets = target.insets(); - int ncomponents = target.countComponents(); - int top = 0; - int left = insets.left; - Dimension tps = target.preferredSize(); - Dimension targetSize = target.size(); - Component comp; - Dimension ps; - - if(horizontalOrientation == Orientation.CENTER) - left = left + (targetSize.width/2) - (tps.width/2); - if(horizontalOrientation == Orientation.RIGHT) - left = left + targetSize.width - tps.width; - - for (int i = 0 ; i < ncomponents ; i++) { - comp = target.getComponent(i); - - if(comp.isVisible()) { - ps = comp.preferredSize(); - - if(verticalOrientation == Orientation.CENTER) - top = (targetSize.height/2) - (ps.height/2); - else if(verticalOrientation == Orientation.TOP) - top = insets.top; - else if( - verticalOrientation == Orientation.BOTTOM) - top = targetSize.height - - ps.height - insets.bottom; - - comp.reshape(left,top,ps.width,ps.height); - left += ps.width + gap; - } - } - } -} diff --git a/java/gjt/Scroller.java b/java/gjt/Scroller.java deleted file mode 100644 index 61d6e5f55e5..00000000000 --- a/java/gjt/Scroller.java +++ /dev/null @@ -1,154 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * Each Scroller contains a Panel (viewport) and two Scrollbars - * (horizontal and vertical). Works in conjunction with a - * ScrollerLayout, that lays out the viewport and two - * scrollbars.<p> - * - * Subclasses must override:<p> - * <dl> - * <dd> abstract public void scrollTo(int x, int y) - * <dd> abstract public Dimension getScrollAreaSize() - * </dl> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ComponentScroller - * @see ImageScroller - * @see ScrollerLayout - * @see gjt.test.ComponentScrollerTest - * @see gjt.test.ImageScrollerTest - */ -public abstract class Scroller extends Panel { - protected Panel viewport; - protected Scrollbar hbar, vbar; - - abstract public void scrollTo(int x, int y); - abstract public Dimension getScrollAreaSize(); - - public Scroller() { - setLayout(new ScrollerLayout(this)); - add("Scroll", viewport = new Panel()); - add("East", vbar = new Scrollbar(Scrollbar.VERTICAL)); - add("South",hbar = new Scrollbar(Scrollbar.HORIZONTAL)); - } - public Scrollbar getHorizontalScrollbar() {return hbar; } - public Scrollbar getVerticalScrollbar () {return vbar; } - public Panel getViewport () {return viewport;} - - public boolean handleEvent(Event event) { - boolean handledEvent; - - switch(event.id) { - case Event.SCROLL_LINE_UP: scrollLineUp(event); - break; - case Event.SCROLL_LINE_DOWN: scrollLineDown(event); - break; - case Event.SCROLL_PAGE_UP: scrollPageUp (event); - break; - case Event.SCROLL_PAGE_DOWN: scrollPageDown(event); - break; - case Event.SCROLL_ABSOLUTE: scrollAbsolute(event); - break; - } - handledEvent = event.id == Event.SCROLL_LINE_UP || - event.id == Event.SCROLL_LINE_DOWN || - event.id == Event.SCROLL_PAGE_UP || - event.id == Event.SCROLL_PAGE_DOWN || - event.id == Event.SCROLL_ABSOLUTE; - - if(handledEvent) return true; - else return super.handleEvent(event); - } - public void paint (Graphics g) { scroll(); } - public void update(Graphics g) { paint(g); } - - public void manageScrollbars() { - manageHorizontalScrollbar(); - manageVerticalScrollbar (); - } - protected void manageHorizontalScrollbar() { - Dimension size = size(); - Dimension scrollAreaSize = getScrollAreaSize(); - - if(vbar.isVisible()) - size.width -= vbar.size().width; - - if(scrollAreaSize.width > size.width) { - if( ! hbar.isVisible()) - hbar.show(); - } - else if(hbar.isVisible()) { - hbar.hide(); - hbar.setValue(0); - repaint(); - } - } - protected void manageVerticalScrollbar() { - Dimension size = size(); - Dimension scrollAreaSize = getScrollAreaSize(); - - if(hbar.isVisible()) - size.height -= hbar.size().height; - - if(scrollAreaSize.height > size.height) { - if( ! vbar.isVisible()) - vbar.show(); - } - else if(vbar.isVisible()) { - vbar.hide(); - vbar.setValue(0); - repaint(); - } - } - public void setScrollbarValues() { - if(hbar.isVisible()) setHorizontalScrollbarValues(); - if(vbar.isVisible()) setVerticalScrollbarValues(); - } - protected void setHorizontalScrollbarValues() { - Dimension vsize = viewport.size(); - Dimension scrollAreaSize = getScrollAreaSize(); - int max = scrollAreaSize.width - vsize.width; - - hbar.setValues(hbar.getValue(), // value - vsize.width, // amt visible/page - 0, // minimum - max); // maximum - - setHorizontalLineAndPageIncrements(); - } - protected void setVerticalScrollbarValues() { - Dimension vsize = viewport.size(); - Dimension scrollAreaSize = getScrollAreaSize(); - int max = scrollAreaSize.height - vsize.height; - - vbar.setValues(vbar.getValue(), // value - vsize.height, // amt visible/page - 0, // minimum - max); // maximum - - setVerticalLineAndPageIncrements(); - } - protected void scrollLineUp (Event event) { scroll(); } - protected void scrollLineDown(Event event) { scroll(); } - protected void scrollPageUp (Event event) { scroll(); } - protected void scrollPageDown(Event event) { scroll(); } - protected void scrollAbsolute(Event event) { scroll(); } - - protected void setHorizontalLineAndPageIncrements() { - Dimension size = getScrollAreaSize(); - hbar.setLineIncrement(size.width/10); - hbar.setPageIncrement(size.width/5); - } - protected void setVerticalLineAndPageIncrements() { - Dimension size = getScrollAreaSize(); - vbar.setLineIncrement(size.height/10); - vbar.setPageIncrement(size.height/5); - } - protected void scroll() { - scrollTo(hbar.getValue(), vbar.getValue()); - } -} diff --git a/java/gjt/ScrollerLayout.java b/java/gjt/ScrollerLayout.java deleted file mode 100644 index 21012fd5688..00000000000 --- a/java/gjt/ScrollerLayout.java +++ /dev/null @@ -1,160 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * Layout manager for a Scroller.<p> - * - * Lays out 3 Components: a horizontal scrollbar, a vertical - * scrollbar and a viewport (Panel).<p> - * - * Valid names/Component pairs that can be added via - * addLayoutComponent(String, Component):<p> - * <dl> - * <dd> "East" Scrollbar (vertical) - * <dd> "West" Scrollbar (vertical) - * <dd> "North" Scrollbar (horizontal) - * <dd> "South" Scrollbar (horizontal) - * <dd> "Scroll" Panel (viewport) - * </dl> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see Scroller - */ -public class ScrollerLayout implements LayoutManager { - private Scroller scroller; - private Scrollbar hbar, vbar; - private String hbarPosition, vbarPosition; - private Component viewport; - private int top, bottom, right, left; - - public ScrollerLayout(Scroller scroller) { - this.scroller = scroller; - } - - public void addLayoutComponent(String name, - Component comp) { - Assert.notFalse(comp != null); - - if(comp instanceof Scrollbar) { - Scrollbar sbar = (Scrollbar)comp; - - if(sbar.getOrientation() == Scrollbar.VERTICAL) { - Assert.notFalse("East".equals(name) == true || - "West".equals(name) == true); - vbar = sbar; - vbarPosition = name; - } - else { - Assert.notFalse("North".equals(name) == true || - "South".equals(name) == true); - hbar = sbar; - hbarPosition = name; - } - } - else { - Assert.notFalse("Scroll".equals(name) == true); - viewport = comp; - } - } - public void removeLayoutComponent(Component comp) { - if(comp == vbar) vbar = null; - if(comp == hbar) hbar = null; - if(comp == viewport) viewport = null; - } - public Dimension preferredLayoutSize(Container parent) { - Dimension dim = new Dimension(0,0); - - if(vbar != null && vbar.isVisible()) { - Dimension d = vbar.preferredSize(); - dim.width += d.width; - dim.height = d.height; - } - if(hbar != null && hbar.isVisible()) { - Dimension d = hbar.preferredSize(); - dim.width += d.width; - dim.height = Math.max(d.height, dim.height); - } - if(viewport != null && viewport.isVisible()) { - Dimension d = viewport.preferredSize(); - dim.width += d.width; - dim.height = Math.max(d.height, dim.height); - } - return dim; - } - public Dimension minimumLayoutSize(Container parent) { - Dimension dim = new Dimension(0,0); - - if(vbar != null && vbar.isVisible()) { - Dimension d = vbar.minimumSize(); - dim.width += d.width; - dim.height = d.height; - } - if(hbar != null && hbar.isVisible()) { - Dimension d = hbar.minimumSize(); - dim.width += d.width; - dim.height = Math.max(d.height, dim.height); - } - if(viewport != null && viewport.isVisible()) { - Dimension d = viewport.minimumSize(); - dim.width += d.width; - dim.height = Math.max(d.height, dim.height); - } - return dim; - } - public void layoutContainer(Container target) { - Insets insets = target.insets(); - Dimension targetSize = target.size(); - - top = insets.top; - bottom = targetSize.height - insets.bottom; - left = insets.left; - right = targetSize.width - insets.right; - - scroller.manageScrollbars(); - - reshapeHorizontalScrollbar(); - reshapeVerticalScrollbar (); - reshapeViewport (); - - scroller.setScrollbarValues(); - } - private void reshapeHorizontalScrollbar() { - if(hbar != null && hbar.isVisible()) { - if("North".equals(hbarPosition)) { - Dimension d = hbar.preferredSize(); - hbar.reshape(left, top, right - left, d.height); - top += d.height; - } - else { // South - Dimension d = hbar.preferredSize(); - hbar.reshape(left, bottom - d.height, - right - left,d.height); - bottom -= d.height; - } - } - } - private void reshapeVerticalScrollbar() { - if(hbar != null && vbar.isVisible()) { - if("East".equals(vbarPosition)) { - Dimension d = vbar.preferredSize(); - vbar.reshape(right - d.width, top, - d.width, bottom - top); - right -= d.width; - } - else { // West - Dimension d = vbar.preferredSize(); - vbar.reshape(left, top, - d.width, bottom - top); - left += d.width; - } - } - } - private void reshapeViewport() { - if(viewport != null && viewport.isVisible()) { - viewport.reshape(left, top, - right - left, bottom - top); - } - } -} diff --git a/java/gjt/SelectionEvent.java b/java/gjt/SelectionEvent.java deleted file mode 100644 index 4bcab59cd0a..00000000000 --- a/java/gjt/SelectionEvent.java +++ /dev/null @@ -1,82 +0,0 @@ -package gjt; - -import java.awt.Event; - -/** - * An extension of java.awt.Event, specifically designed for - * selection events.<p> - * - * SelectionEvents are constructed with arguments:<p> - * <dl> - * <dd> The AWT event that triggered the image button event - * <dd> The id of the event. - * </dl> - * - * An SelectionEvent's id (the constructor's 3rd argument), - * must be one of the following:<p> - * <dl> - * <dd> SelectionEvent.SELECT - * <dd> SelectionEvent.DESELECT - * </dl> - * - * SelectionEvent has only a constructor and a paramString() - * method. Containers that contain objects which are capable - * of generating SelectionEvents should check the events - * like so: - * - * <pre> - * // handleEvent(Event) method of a container that - * // contain objects that generate SelectionEvents - * - * public boolean handleEvent(Event event) { - * if(event instanceof SelectionEvent) { - * SelectionEvent sevent = - * (SelectionEvent)event; - * - * if(sevent.isSelected()) { - * // do something for selection - * } - * else { - * // do something for deselection - * } - * } - * } - * </pre> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see LabelCanvas - * @see ImageButtonEvent - * @see gjt.test.LabelCanvasTest - */ -public class SelectionEvent extends Event { - public static final int SELECT = 1; - public static final int DESELECT = 2; - - private int eventType; - - public SelectionEvent(Object target, - Event event, - int type) { - super(target, event.when, event.id, event.x, event.y, - event.key, event.modifiers, event.arg); - - Assert.notFalse(type == SELECT || type == DESELECT); - - eventType = type; - id = -1; - } - public boolean isSelected() { - return eventType == SELECT; - } - protected String paramString() { - String typeString = new String(); - - if(eventType == SelectionEvent.SELECT) - typeString = "SELECT"; - else if(eventType == SelectionEvent.DESELECT) - typeString = "DESELECT"; - - return super.paramString() + typeString; - } -} diff --git a/java/gjt/Separator.java b/java/gjt/Separator.java deleted file mode 100644 index 6bd610e1ad9..00000000000 --- a/java/gjt/Separator.java +++ /dev/null @@ -1,90 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A separator that is drawn either vertically or horizontally - * depending upon how it is laid out. Can be drawn either - * etched-in or etched-out, with varying thicknesses. Both - * thickness and etching are settable at construction time - * only.<p> - * - * Default thickness is 2 pixels and default etching is - * Etching.IN. Note that thicknesses greater than 4 loose the - * etching effect.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see Etching - * @see gjt.test.SeparatorTest - */ -public class Separator extends Canvas { - static private Etching _defaultEtching = Etching.IN; - static private int _defaultThickness = 2; - - private Etching etching; - private int thickness; - - public Separator() { - this(_defaultThickness, _defaultEtching); - } - public Separator(int thickness) { - this(thickness, _defaultEtching); - } - public Separator(Etching etching) { - this(_defaultThickness, etching); - } - public Separator(int thickness, Etching etching) { - this.etching = etching; - this.thickness = thickness; - resize(thickness, thickness); - } - public Dimension minimumSize() { - return preferredSize(); - } - public Dimension preferredSize() { - return new Dimension(thickness, thickness); - } - public void paint(Graphics g) { - Dimension size = size(); - Color brighter = getBackground().brighter().brighter(); - Color darker = getBackground().darker().darker(); - - if(etching == Etching.IN) { - if(size.width > size.height) - paintHorizontal(g, size, darker, brighter); - else - paintVertical(g, size, darker, brighter); - } - else { - if(size.width > size.height) - paintHorizontal(g, size, brighter, darker); - else - paintVertical(g, size, brighter, darker); - } - } - public String paramString() { - Dimension size = size(); - Orientation orient = size.width > size.height ? - Orientation.HORIZONTAL : - Orientation.VERTICAL; - return super.paramString() + "thickness=" + - thickness + "," + etching + "," + orient; - } - private void paintHorizontal(Graphics g, Dimension size, - Color top, Color bottom) { - g.setColor(top); - g.fillRect(0, (size.height/2) - (thickness/2), - size.width, thickness/2); - g.setColor(bottom); - g.fillRect(0, size.height/2, size.width, thickness/2); - } - private void paintVertical(Graphics g, Dimension size, - Color left, Color right) { - g.setColor(left); - g.fillRect((size.width/2) - (thickness/2), - 0, thickness/2, size.height); - g.setColor(right); - g.fillRect(size.width/2, 0, thickness/2, size.height); - } -} diff --git a/java/gjt/SpringyImageButtonController.java b/java/gjt/SpringyImageButtonController.java deleted file mode 100644 index 3559e040459..00000000000 --- a/java/gjt/SpringyImageButtonController.java +++ /dev/null @@ -1,54 +0,0 @@ -package gjt; - -import java.awt.Event; -import java.awt.Graphics; - -/** - * An ImageButtonController that reacts to mouseDown/mouseUp - * events exactly as a java.awt.Button does.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ImageButton - * @see ImageButtonController - * @see StickyImageButtonController - */ -public class SpringyImageButtonController - extends ImageButtonController { - public SpringyImageButtonController(ImageButton ib) { - super(ib); - } - public boolean mouseDown(Event event, int x, int y) { - if(event.modifiers == 0) { - getButton().paintInset(); - armButton(event); - } - return false; - } - public boolean mouseUp(Event event, int x, int y) { - if(event.modifiers == 0) { - if(getButton().isRaised() == false) { - getButton().paintRaised(); - activateButton(event); - } - } - return false; - } - public boolean mouseDrag(Event event, int x, int y) { - if(event.modifiers == 0) { - if(getButton().isInside(x,y)) { - if(getButton().isRaised()) { - getButton().paintInset(); - armButton(event); - } - } - else { - if(getButton().isRaised() == false) { - getButton().paintRaised(); - disarmButton(event); - } - } - } - return false; - } -} diff --git a/java/gjt/StateButton.java b/java/gjt/StateButton.java deleted file mode 100644 index 6de20a76f98..00000000000 --- a/java/gjt/StateButton.java +++ /dev/null @@ -1,45 +0,0 @@ -package gjt; - -import java.awt.Image; - -/** - * An ImageButton that cycles through a series of images. The - * image advances to the next image in the series every time - * the button is activated.<p> - * - * Note that the cycling is actually performed by the buttons' - * controller - a StateButtonController.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ImageButton - * @see StateButtonController - * @see gjt.test.StateButtonTest - */ -public class StateButton extends ImageButton { - private Image[] images; - private int state = 0; - private int numStates; - - public StateButton(Image[] images) { - super(images[0]); - - this.images = images; - numStates = images.length; - setController(new StateButtonController(this)); - waitForImages(); - } - public Image nextImage() { - if(state + 1 < numStates) state++; - else state = 0; - - return images[state]; - } - public int state() { - return state; - } - private void waitForImages() { - for(int i=0; i < images.length; ++i) - Util.waitForImage(this, images[i]); - } -} diff --git a/java/gjt/StateButtonController.java b/java/gjt/StateButtonController.java deleted file mode 100644 index d6fc83830a6..00000000000 --- a/java/gjt/StateButtonController.java +++ /dev/null @@ -1,27 +0,0 @@ -package gjt; - -import java.awt.Event; - -/** - * A controller for a StateButton, that cycles through a - * series of images which reside in the StateButton class. - * Each time a mouse up is detected in the StateButton, the - * buttons image is set to the next image in the array. - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see StateButton - * @see SpringyImageButtonController - * @see gjt.test.StateButtonTest - */ -class StateButtonController extends SpringyImageButtonController { - public StateButtonController(StateButton button) { - super(button); - } - public boolean mouseUp(Event event, int x, int y) { - StateButton button = (StateButton)getButton(); - button.setImage(button.nextImage()); - activateButton(event); - return super.mouseUp(event, x, y); - } -} diff --git a/java/gjt/StickyImageButtonController.java b/java/gjt/StickyImageButtonController.java deleted file mode 100644 index c459e5cdae1..00000000000 --- a/java/gjt/StickyImageButtonController.java +++ /dev/null @@ -1,87 +0,0 @@ -package gjt; - -import java.awt.Event; -import java.awt.Graphics; - -/** - * An ImageButtonController that causes its associated - * ImageButton to "stick" when activated. If the ImageButton - * is raised it depresses<b>[1]</b> upon a mouse down and stays - * down upon a subsequent mouse up event. The same "sticky" - * behaviour occurs when a depressed ImageButton encounters a - * mouse down followed by a subsequent mouse up.<p> - * - * Note that false is returned from mouse event handlers; - * therefore mouse events will be propagated to the - * ImageButton's container. While this is not always - * desirable, it was deemed a better default than swallowing - * the event here. Subclasses may, of course, modify this - * behavior.<p> - * - * <b>[1]</b> No psychiatric consultation is necessary.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ImageButton - * @see ImageButtonController - * @see SpringyImageButtonController - */ -public class StickyImageButtonController - extends ImageButtonController { - private boolean buttonUpOnLastMouseDown = true; - - public StickyImageButtonController(ImageButton ib) { - super(ib); - } - public boolean mouseDown(Event event, int x, int y) { - ImageButton button = getButton(); - - if(event.modifiers == 0) { - if(button.isRaised()) button.paintInset(); - else button.paintRaised(); - - buttonUpOnLastMouseDown = getButton().isRaised(); - armButton(event); - } - return false; - } - public boolean mouseUp(Event event, int x, int y) { - activateButton(event); - return false; - } - public boolean mouseDrag(Event event, int x, int y) { - ImageButton button = getButton(); - - if(event.modifiers == 0) { - if(button.isInside(x,y)) { - if(buttonUpOnLastMouseDown) { - if(button.isRaised() == false) { - button.paintRaised(); - armButton(event); - } - } - else { - if(button.isRaised()) { - button.paintInset(); - armButton(event); - } - } - } - else { - if(buttonUpOnLastMouseDown) { - if(button.isRaised()) { - button.paintInset(); - disarmButton(event); - } - } - else { - if(button.isRaised() == false) { - button.paintRaised(); - disarmButton(event); - } - } - } - } - return false; - } -} diff --git a/java/gjt/Stopwatch.java b/java/gjt/Stopwatch.java deleted file mode 100644 index fc8963e88a1..00000000000 --- a/java/gjt/Stopwatch.java +++ /dev/null @@ -1,94 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A Thread that acts as a stopwatch.<p> - * - * Stopwatch starts running when it is constructed, and may be - * reset by the reset() method. getHour(), getMinute(), - * getSecond(), and getMillisecond() are used to get the - * elapsed time since construction, or since the last reset.<p> - * - * toString() returns the elapsed time in the form of - * HH:MM:SS:mm, where HH == hours, MM == minutes, SS == seconds - * and mm == milliseconds.<p> - * - * Each Stopwatch may have a StopwatchClient associated with it. - * If the StopwatchClient is non-null, the StopwatchClients' - * tick() method is invoked every 50 milliseconds.<p> - * - * @version 1.0, Apr 21 1996 - * @author David Geary - * @see StopwatchClient - * @see gjt.animation.Sequence - * @see gjt.animation.Sprite - */ -public class Stopwatch extends Thread { - private StopwatchClient client; - private long start, now, elapsed; - private long hour, minute, second, millisecond; - - public Stopwatch() { - this(null); - } - public Stopwatch(StopwatchClient client) { - start = System.currentTimeMillis(); - this.client = client; - } - public void update() { - now = System.currentTimeMillis(); - elapsed = now - start; - hour = minute = second = millisecond = 0; - - second = elapsed / 1000; - millisecond = elapsed % 1000; - millisecond = (millisecond == 0) ? 0 : millisecond/10; - - if(second > 59) { - minute = second / 60; - second = second - (minute*60); - } - if(minute > 59) { - hour = minute / 60; - minute = minute - (hour*60); - } - } - public String toString() { - update(); - return new String(stringValueOf(hour) + ":" + - stringValueOf(minute) + ":" + - stringValueOf(second) + ":" + - stringValueOf(millisecond)); - } - public long getHour () { return hour; } - public long getMinute () { return minute; } - public long getSecond () { return second; } - public long getMillisecond () { return millisecond; } - - public long elapsedTime() { - update(); - return elapsed; - } - public void reset() { - start = System.currentTimeMillis(); - } - public void run() { - while(true) { - try { - Thread.currentThread().sleep(50, 0); - update(); - if(client != null) - client.tick(); - } - catch(InterruptedException e) { - Assert.notFalse(false); - } - } - } - private String stringValueOf(long l) { - if(l < 10) return "0" + String.valueOf(l); - else return String.valueOf(l); - - } -} diff --git a/java/gjt/StopwatchClient.java b/java/gjt/StopwatchClient.java deleted file mode 100644 index c2eb5fb0460..00000000000 --- a/java/gjt/StopwatchClient.java +++ /dev/null @@ -1,14 +0,0 @@ -package gjt; - -/** - * Client of a Stopwatch. Stopwatches that have non-null - * clients, call their clients' tick() method every 50 - * milliseconds.<p> - * - * @version 1.0, Apr 21 1996 - * @author David Geary - * @see Stopwatch - */ -public interface StopwatchClient { - public void tick(); -} diff --git a/java/gjt/ThreeDBorder.java b/java/gjt/ThreeDBorder.java deleted file mode 100644 index 0441fdf3052..00000000000 --- a/java/gjt/ThreeDBorder.java +++ /dev/null @@ -1,53 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * Extension of Border that draws a 3D border. - * - * Drawn raised by default, drawing style used by paint() is - * controlled by raise() and inset(). Note that raise() and - * inset() do not result in anything being painted, but only set - * the state for the next call to paint(). To set the state and - * paint in one operation, use paintRaised() and paintInset(). - * <p> - * - * The current state of the border may be obtained by calling - * isRaised().<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see Border - * @see EtchedRectangle - * @see gjt.test.BorderTest - */ -public class ThreeDBorder extends Border { - public ThreeDBorder(Component borderMe) { - this(borderMe, _defaultThickness, _defaultGap); - } - public ThreeDBorder(Component borderMe, - int borderThickness) { - this(borderMe, borderThickness, _defaultGap); - } - public ThreeDBorder(Component borderMe, - int borderThickness, int gap) { - super(borderMe, borderThickness, gap); - } - public void inset() { ((ThreeDRectangle)border()).inset(); } - public void raise() { ((ThreeDRectangle)border()).raise(); } - - public void paintRaised() { - ((ThreeDRectangle)border()).paintRaised(); - } - public void paintInset() { - ((ThreeDRectangle)border()).paintInset (); - } - public boolean isRaised() { - return ((ThreeDRectangle)border()).isRaised(); - } - protected DrawnRectangle border() { - if(border == null) - border = new ThreeDRectangle(this, thickness); - return border; - } -} diff --git a/java/gjt/ThreeDBorderStyle.java b/java/gjt/ThreeDBorderStyle.java deleted file mode 100644 index b0e1b7d8ab8..00000000000 --- a/java/gjt/ThreeDBorderStyle.java +++ /dev/null @@ -1,24 +0,0 @@ -package gjt; - -/** - * Constants for 3D border styles. - * - * This class may not be instantiated. - * - * @version 1.0, Apr 11 1996 - * @author David Geary - */ -public class ThreeDBorderStyle { - public static final ThreeDBorderStyle RAISED = - new ThreeDBorderStyle(); - public static final ThreeDBorderStyle INSET = - new ThreeDBorderStyle(); - - public String toString() { - if(this == ThreeDBorderStyle.RAISED) - return getClass().getName() + "=RAISED"; - else - return getClass().getName() + "=INSET"; - } - private ThreeDBorderStyle() { } // defeat instantiation -} diff --git a/java/gjt/ThreeDRectangle.java b/java/gjt/ThreeDRectangle.java deleted file mode 100644 index 647129190c5..00000000000 --- a/java/gjt/ThreeDRectangle.java +++ /dev/null @@ -1,105 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A DrawnRectangle which draws in 3D.<p> - * - * Drawn raised by default, drawing style used by paint() is - * controlled by raise() and inset(). Note that raise() and - * inset() do not result in anything being painted, but only set - * the state for the next call to paint(). To set the state and - * paint in one operation, use paintRaised() and paintInset(). - * <p> - * - * The current state of the rectangle may be obtained by - * calling isRaised().<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see DrawnRectangle - * @see EtchedRectangle - * @see gjt.test.DrawnRectangleTest - */ -public class ThreeDRectangle extends DrawnRectangle { - protected static ThreeDBorderStyle - _defaultState = ThreeDBorderStyle.RAISED; - - private ThreeDBorderStyle state; - - public ThreeDRectangle(Component drawInto) { - this(drawInto, _defaultState, - _defaultThickness, 0, 0, 0, 0); - } - public ThreeDRectangle(Component drawInto, int thickness) { - this(drawInto, _defaultState, thickness, 0, 0, 0, 0); - } - public ThreeDRectangle(Component drawInto, - int x, int y, int w, int h) { - this(drawInto, - _defaultState, _defaultThickness, x, y, w, h); - } - public ThreeDRectangle(Component drawInto, int thickness, - int x, int y, - int w, int h) { - this(drawInto, _defaultState, thickness, x, y, w, h); - } - public ThreeDRectangle(Component drawInto, - ThreeDBorderStyle state, - int thickness, int x, int y, - int w, int h) { - super(drawInto, thickness, x, y, w, h); - this.state = state; - } - public void paint() { - if(state == ThreeDBorderStyle.RAISED) paintRaised(); - else paintInset (); - } - public void raise() { state = ThreeDBorderStyle.RAISED; } - public void inset() { state = ThreeDBorderStyle.INSET; } - - public boolean isRaised() { - return state == ThreeDBorderStyle.RAISED; - } - public String paramString() { - return super.paramString() + "," + state; - } - public void paintRaised() { - Graphics g = drawInto.getGraphics(); - - if(g != null) { - raise (); - drawTopLeftLines (g, brighter()); - drawBottomRightLines(g, getLineColor()); - } - } - public void paintInset() { - Graphics g = drawInto.getGraphics(); - - if(g != null) { - inset (); - drawTopLeftLines (g, getLineColor()); - drawBottomRightLines(g, brighter()); - } - } - private void drawTopLeftLines(Graphics g, Color color) { - int thick = getThickness(); - g.setColor(color); - - for(int i=0; i < thick; ++i) { - g.drawLine(x+i, y+i, x + width-(i+1), y+i); - g.drawLine(x+i, y+i+1, x+i, y + height-(i+1)); - } - } - private void drawBottomRightLines(Graphics g, Color color) { - int thick = getThickness(); - g.setColor(color); - - for(int i=1; i <= thick; ++i) { - g.drawLine(x+i-1, y + height-i, - x + width-i, y + height-i); - g.drawLine(x + width-i, y+i-1, - x + width-i, y + height-i); - } - } -} diff --git a/java/gjt/Toolbar.java b/java/gjt/Toolbar.java deleted file mode 100644 index 4d6ebddc217..00000000000 --- a/java/gjt/Toolbar.java +++ /dev/null @@ -1,58 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * A toolbar containing image buttons which are laid out to the - * north of (horizontal) separator.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ImageButton - * @see ImageButtonPanel - * @see gjt.test.ToolbarTest - */ -public class Toolbar extends Panel { - static private int _defaultGap = 0; - static private int _defaultLeftInset = 0; - - private ToolbarButtonPanel buttonPanel; - - public Toolbar() { - this(_defaultLeftInset, _defaultGap); - } - public Toolbar(int leftInset, int gap) { - buttonPanel = new ToolbarButtonPanel(leftInset, gap); - - setLayout(new BorderLayout()); - add ("North", buttonPanel); - add ("South", new Separator()); - } - public ImageButton add(Image image) { - return buttonPanel.add(image); - } - public void add(ImageButton button) { - buttonPanel.add(button); - } - public void addSpacer(int sizeInPixels) { - Assert.notFalse(sizeInPixels > 0); - buttonPanel.addSpacer(sizeInPixels); - } -} - -class ToolbarButtonPanel extends ImageButtonPanel { - private int leftInset; - - public ToolbarButtonPanel(int leftInset, int gap) { - super(Orientation.HORIZONTAL, - Orientation.LEFT, - Orientation.CENTER, - gap); - - this.leftInset = leftInset; - setController(null); - } - public Insets insets() { - return new Insets(5,leftInset,5,5); - } -} diff --git a/java/gjt/Util.java b/java/gjt/Util.java deleted file mode 100644 index 0970a6fd488..00000000000 --- a/java/gjt/Util.java +++ /dev/null @@ -1,69 +0,0 @@ -package gjt; - -import java.applet.Applet; -import java.awt.*; - -/** - * A handy collection of methods for getting a component's - * frame, getting a component's applet, waiting for a - * component's image, and wallpapering a components background. - * <p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - */ -public class Util { - public static Frame getFrame(Component component) { - Component c = component; - - if(c instanceof Frame) - return (Frame)c; - - while((c = c.getParent()) != null) { - if(c instanceof Frame) - return (Frame)c; - } - return null; - } - public static Applet getApplet(Component component) { - Component c = component; - - if(c instanceof Applet) - return (Applet)c; - - while((c = c.getParent()) != null) { - if(c instanceof Applet) - return (Applet)c; - } - return null; - } - public static void waitForImage(Component component, - Image image) { - MediaTracker tracker = new MediaTracker(component); - try { - tracker.addImage(image, 0); - tracker.waitForID(0); - } - catch(InterruptedException e) { Assert.notNull(null); } - } - public static void wallPaper(Component component, - Graphics g, - Image image) { - Dimension compsize = component.size(); - Util.waitForImage(component, image); - - int patchW = image.getWidth(component); - int patchH = image.getHeight(component); - - Assert.notFalse(patchW != -1 && patchH != -1); - - for(int r=0; r < compsize.width; r += patchW) { - for(int c=0; c < compsize.height; c += patchH) - g.drawImage(image, r, c, component); - } - } - public static void setCursor(int cursor, - Component component) { - getFrame(component).setCursor(cursor); - } -} diff --git a/java/gjt/YesNoDialog.java b/java/gjt/YesNoDialog.java deleted file mode 100644 index 2db64ea6e4b..00000000000 --- a/java/gjt/YesNoDialog.java +++ /dev/null @@ -1,80 +0,0 @@ -package gjt; - -import java.awt.*; - -/** - * Similar in fuction to the MessageDialog, YesNoDialog poses - * a question, that is answered by selection of either a Yes - * button or a No button.<p> - * - * Note that the YesNoDialog is a singleton - meaning there is - * only one YesNoDialog in existence per applet. Clients - * may obtain the YesNoDialog by invoking getYesNoDialog().<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see GJTDialog - * @see MessageDialog - * @see gjt.test.DialogTest - */ -public class YesNoDialog extends GJTDialog { - static private YesNoDialog _theYesNoDialog; - private Button yesButton; - private Button noButton; - private String message; - private boolean answer = false; - private ButtonPanel buttonPanel = new ButtonPanel(); - - static public YesNoDialog getYesNoDialog( Frame frame, - DialogClient client, - String title, - String message) { - if(_theYesNoDialog == null) - _theYesNoDialog = new YesNoDialog(frame,client, - title,message); - else { - _theYesNoDialog.setClient (client); - _theYesNoDialog.setTitle (title); - _theYesNoDialog.setMessage(message); - } - return _theYesNoDialog; - } - private YesNoDialog(Frame frame, DialogClient client, - String title, String message) { - super(frame, title, client, true); - yesButton = buttonPanel.add("Yes"); - noButton = buttonPanel.add("No"); - - setLayout(new BorderLayout()); - add("Center", new YesNoPanel(message)); - add("South", buttonPanel); - pack(); - } - public void show() { - yesButton.requestFocus(); - super.show(); - } - public boolean answeredYes() { - return answer; - } - public boolean action(Event event, Object what) { - if(event.target == yesButton) answer = true; - else answer = false; - - hide(); - client.dialogDismissed(this); - return true; - } - private void setMessage(String message) { - this.message = message; - } -} - -class YesNoPanel extends Panel { - public YesNoPanel(String question) { - add("Center", new Label(question, Label.CENTER)); - } - public Insets insets() { - return new Insets(10,10,10,10); - } -} diff --git a/java/gjt/animation/CollisionArena.java b/java/gjt/animation/CollisionArena.java deleted file mode 100644 index defb1a6d86b..00000000000 --- a/java/gjt/animation/CollisionArena.java +++ /dev/null @@ -1,39 +0,0 @@ -package gjt.animation; - -import java.awt.Dimension; -import java.awt.Insets; -import java.util.Vector; -import gjt.Orientation; - -/** - * A CollisionArena is defined as an arena in which collisions - * may take place.<p> - * - * CollisionArenas must be able to report their size and - * insets, and return a Vector of the Sprites contained in the - * arena.<p> - * - * CollisionArenas must also implement two methods for handling - * sprite and edge collisions, respectively. - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see Playfield - * @see CollisionDetector - * @see EdgeCollisionDetector - * @see SpriteCollisionDetector - * @see gjt.test.SimpleAnimationTest - * @see gjt.test.BumpAnimationTest - * @see gjt.test.TwoDrinkersAnimationTest - */ -public interface CollisionArena { - abstract public Vector getSprites(); - abstract public Dimension getSize (); - abstract public Insets getInsets (); - - abstract public void spriteCollision(Sprite sprite, - Sprite other); - - abstract public void edgeCollision(Sprite sprite, - Orientation orient); -} diff --git a/java/gjt/animation/CollisionDetector.java b/java/gjt/animation/CollisionDetector.java deleted file mode 100644 index ff05f16c6d3..00000000000 --- a/java/gjt/animation/CollisionDetector.java +++ /dev/null @@ -1,24 +0,0 @@ -package gjt.animation; - -/** - * Collision detectors detect collisions that take place within - * a CollisionArena. - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see CollisionArena - * @see EdgeCollisionDetector - * @see SpriteCollisionDetector - * @see gjt.test.SimpleAnimationTest - * @see gjt.test.BumpAnimationTest - * @see gjt.test.TwoDrinkersAnimationTest - */ -abstract public class CollisionDetector { - protected CollisionArena arena; - - abstract public void detectCollisions(); - - public CollisionDetector(CollisionArena arena) { - this.arena = arena; - } -} diff --git a/java/gjt/animation/EdgeCollisionDetector.java b/java/gjt/animation/EdgeCollisionDetector.java deleted file mode 100644 index 8624b7c2f28..00000000000 --- a/java/gjt/animation/EdgeCollisionDetector.java +++ /dev/null @@ -1,53 +0,0 @@ -package gjt.animation; - -import java.awt.*; -import java.util.Enumeration; -import java.util.Vector; -import gjt.Orientation; - -/** - * A CollisionDetector that detects collisions between Sprites - * and the edges of the CollisionArena in which they reside.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see CollisionDetector - * @see Sprite - * @see gjt.test.SimpleAnimationTest - * @see gjt.test.BumpAnimationTest - * @see gjt.test.TwoDrinkersAnimationTest - */ -public class EdgeCollisionDetector extends CollisionDetector { - public EdgeCollisionDetector(CollisionArena arena) { - super(arena); - } - public void detectCollisions() { - Enumeration sprites = arena.getSprites().elements(); - Dimension arenaSize = arena.getSize(); - Insets arenaInsets = arena.getInsets(); - Sprite sprite; - - while(sprites.hasMoreElements()) { - sprite = (Sprite)sprites.nextElement(); - - Point nl = sprite.nextLocation (); - Point mv = sprite.getMoveVector(); - int nextRightEdge = nl.x + sprite.width(); - int nextBottomEdge = nl.y + sprite.height(); - int arenaBottomEdge = arenaSize.height - - arenaInsets.bottom; - int arenaRightEdge = arenaSize.width - - arenaInsets.right; - - if(nextRightEdge > arenaRightEdge) - arena.edgeCollision(sprite, Orientation.LEFT); - else if(nl.x < arenaInsets.left) - arena.edgeCollision(sprite, Orientation.RIGHT); - - if(nextBottomEdge > arenaBottomEdge) - arena.edgeCollision(sprite, Orientation.BOTTOM); - else if(nl.y < arenaInsets.top) - arena.edgeCollision(sprite, Orientation.TOP); - } - } -} diff --git a/java/gjt/animation/Playfield.java b/java/gjt/animation/Playfield.java deleted file mode 100644 index 386c0fb24c4..00000000000 --- a/java/gjt/animation/Playfield.java +++ /dev/null @@ -1,140 +0,0 @@ -package gjt.animation; - -import java.awt.*; -import java.util.Enumeration; -import java.util.Vector; -import gjt.Util; - -/** - * A surface upon which Sprites are animated. Playfields are - * responsible for animating the sprites.<p> - * - * Each Playfield comes complete with two collision detectors: - * an edge collision detector and a sprite collision detector. - * - * Playfield is an abstract class: extensions must implement - * the following methods: - * <dl> - * <dd> void paintBackground(Graphics) - * <dd> void void spriteCollision(Sprite sprite, Sprite other) - * <dd> void void edgeCollision (Sprite sprite, Sprite other) - * </dl> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see CollisionArena - * @see Sprite - * @see SpriteCollisionDetector - * @see EdgeCollisionDetector - * @see gjt.test.SimpleAnimationTest - * @see gjt.test.BumpAnimationTest - * @see gjt.test.TwoDrinkersAnimationTest - */ -public abstract class Playfield extends Canvas - implements Runnable, - CollisionArena { - protected Vector sprites = new Vector(); - private boolean running = false; - private Insets insets = new Insets(0,0,0,0); - - private Thread animationThread; - private Image bgoffscreen, - workplaceBuffer; - private Dimension offscreenSize; - private EdgeCollisionDetector edgeCollisionDetector; - private SpriteCollisionDetector spriteCollisionDetector; - - abstract public void paintBackground(Graphics g); - - public Playfield() { - edgeCollisionDetector = - new EdgeCollisionDetector(this); - spriteCollisionDetector = - new SpriteCollisionDetector(this); - } - public void stop () { running = false; } - public boolean running () { return running; } - public Dimension getSize () { return size(); } - public Insets getInsets () { return insets; } - public Vector getSprites() { return sprites; } - - public void addSprite(Sprite sprite) { - sprites.addElement(sprite); - } - public void setInsets(Insets insets) { - this.insets = insets; - } - public void start() { - animationThread = new Thread(this); - running = true; - animationThread.start(); - } - public void paint(Graphics g) { - if(needNewOffscreenBuffer()) { - workplaceBuffer = createOffscreenImage(size()); - bgoffscreen = createOffscreenImage(size()); - paintBackground(bgoffscreen.getGraphics()); - } - g.drawImage(bgoffscreen, 0, 0, this); - paintSprites(); - } - public void reshape(int x, int y, int w, int h) { - super.reshape(x,y,w,h); - repaint(); - } - public void run() { - while(running == true) { - edgeCollisionDetector.detectCollisions (); - spriteCollisionDetector.detectCollisions(); - - animateSprites(); - Thread.currentThread().yield(); - } - animationThread = null; - } - private boolean needNewOffscreenBuffer() { - return (workplaceBuffer == null || - bgoffscreen == null || - size().width != offscreenSize.width || - size().height != offscreenSize.height); - } - private Image createOffscreenImage(Dimension size) { - Image image = createImage(size.width, size.height); - Util.waitForImage(this, image); - offscreenSize = size; - return image; - } - protected void animateSprites() { - Sprite nextSprite; - Enumeration e = sprites.elements(); - - while(e.hasMoreElements()) { - nextSprite = (Sprite)e.nextElement(); - nextSprite.animate(); - } - } - protected void paintSprites() { - Sprite nextSprite; - Enumeration e = sprites.elements(); - - while(e.hasMoreElements()) { - nextSprite = (Sprite)e.nextElement(); - paintSprite(nextSprite); - } - } - protected void paintSprite(Sprite sprite) { - Graphics g = getGraphics(); - Graphics wpg = workplaceBuffer.getGraphics(); - Rectangle clip = sprite.clipRect(); - - wpg.clipRect(clip.x, clip.y, clip.width, clip.height); - wpg.drawImage(bgoffscreen, 0, 0, this); - sprite.paint(wpg); - - g.clipRect (clip.x, clip.y, clip.width, clip.height); - g.drawImage(workplaceBuffer, 0, 0, this); - - g.dispose(); - wpg.dispose(); - } -} diff --git a/java/gjt/animation/Sequence.java b/java/gjt/animation/Sequence.java deleted file mode 100644 index 7b777ecd0d8..00000000000 --- a/java/gjt/animation/Sequence.java +++ /dev/null @@ -1,119 +0,0 @@ -package gjt.animation; - -import java.util.Vector; -import java.awt.*; -import java.awt.image.ImageObserver; -import gjt.Util; -import gjt.Stopwatch; - -/** - * A sequence of images used in an animation. Each sequence - * keeps track of the number of cycles the sequence is to run, - * and reports whether or not the cycles have been completed - * via the boolean animationOver() method. - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see Sprite - * @see Playfield - * @see gjt.test.SimpleAnimationTest - * @see gjt.test.BumpAnimationTest - * @see gjt.test.TwoDrinkersAnimationTest - */ -public class Sequence { - private static long infiniteCycle = -1; - - private Vector cells = new Vector(); - private Point lastPaintLocation = new Point(0,0); - private Stopwatch cellAdvanceTimer = new Stopwatch(); - private Image currentImage, lastImagePainted; - private long cellAdvanceInterval = 0, - currentCycle = 0, - cyclesPerAnimation = 0; - - public Sequence() { } - - public Sequence(Component component, Image[] images) { - for(int i=0; i < images.length; ++i) { - addImage(component, images[i]); - } - cyclesPerAnimation = infiniteCycle; - } - public void start () { cellAdvanceTimer.start(); } - public Image getLastImage () { return lastImagePainted; } - public Point getLastLocation() { return lastPaintLocation; } - public int getNumImages () { return cells.size(); } - - public long getCurrentCycle() { return currentCycle; } - public void setCurrentCycle(long c) { currentCycle = c; } - - public long getCyclesPerAnimation() { - return currentCycle; - } - public void setCyclesPerAnimation(long cyclesPerAnimation) { - this.cyclesPerAnimation = cyclesPerAnimation; - } - public Image getFirstImage() { - return (Image)cells.firstElement(); - } - public Image getCurrentImage() { - return currentImage; - } - public int getCurrentImagePosition() { - return cells.indexOf(currentImage); - } - public Image getNextImage() { - int index = cells.indexOf(currentImage); - Image image; - - if(index == cells.size() - 1) - image = (Image)cells.elementAt(0); - else - image = (Image)cells.elementAt(index + 1); - - return image; - } - public void setAdvanceInterval(long interval) { - cellAdvanceInterval = interval; - } - public void addImage(Component component, Image image) { - if(currentImage == null) - currentImage = image; - - Util.waitForImage(component, image); - cells.addElement(image); - } - public void removeImage(Image image) { - cells.removeElement(image); - } - public boolean needsRepainting(Point point) { - return (lastPaintLocation.x != point.x || - lastPaintLocation.y != point.y || - lastImagePainted != currentImage); - } - public void paint(Graphics g, int x, int y, - ImageObserver observer) { - g.drawImage(currentImage, x, y, observer); - lastPaintLocation.x = x; - lastPaintLocation.y = y; - lastImagePainted = currentImage; - } - public boolean isAtLastImage() { - return getCurrentImagePosition() == (cells.size() - 1); - } - public boolean timeToAdvanceCell() { - return - cellAdvanceTimer.elapsedTime() > cellAdvanceInterval; - } - public boolean animationOver() { - return (cyclesPerAnimation != infiniteCycle) && - (currentCycle >= cyclesPerAnimation); - } - public void advance() { - if(isAtLastImage()) - ++currentCycle; - - currentImage = getNextImage(); - cellAdvanceTimer.reset(); - } -} diff --git a/java/gjt/animation/Sprite.java b/java/gjt/animation/Sprite.java deleted file mode 100644 index e7840b7615b..00000000000 --- a/java/gjt/animation/Sprite.java +++ /dev/null @@ -1,191 +0,0 @@ -package gjt.animation; - -import java.awt.*; -import java.util.Vector; -import gjt.Assert; -import gjt.Stopwatch; -import gjt.Util; - -/** - * A sequence of images which are animated and moved about on - * a Playfield.<p> - * - * Each Sprite is constructed with a reference to it's - * Playfield, a Sequence, and a beginning position for it's - * upper left hand corner.<p> - * - * A Sprite's animation is controlled by invoking the following - * methods: - *<dl> - *<dd> setMoveVector(Point) - *<dd> setMoveInterval(long) - *<dd> setImageChangeInterval(long) - *<dd> setMainSequence(Sequence) - *<dd> setSequence(Sequence) - *</dl> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see Sequence - * @see Playfield - * @see SpriteCollisionDetector - * @see gjt.test.SimpleAnimationTest - * @see gjt.test.BumpAnimationTest - * @see gjt.test.TwoDrinkersAnimationTest - */ -public class Sprite { - private Playfield field; - private Sequence currentSequence, mainSequence; - private Stopwatch moveTimer = new Stopwatch(); - - private Point ulhc = new Point(0,0); - private Point start = new Point(0,0); - private Point moveVector = new Point(1,1); - - private Rectangle clip = new Rectangle(0,0); - private Rectangle curBounds, lastBounds; - - private int width, height; - private long moveInterval = 0; - - public Sprite(Playfield field, - Sequence sequence, - Point ulhc) { - Assert.notNull(field); - Assert.notNull(sequence); - Assert.notNull(ulhc); - - this.field = field; - this.ulhc = ulhc; - start.x = ulhc.x; - start.y = ulhc.y; - - setSequence(sequence); - setMainSequence(sequence); - - initializeBounds(); - moveTimer.start(); - currentSequence.start(); - } - public Playfield getPlayfield() { return field; } - public Rectangle clipRect () { return clip; } - public Rectangle curBounds () { return curBounds; } - - public int width () { return width; } - public int height () { return height; } - public void reverseX () { moveVector.x = 0-moveVector.x; } - public void reverseY () { moveVector.y = 0-moveVector.y; } - public void reverse () { reverseX(); reverseY(); } - public Point start () { return start; } - - public void setMoveVector (Point p) { moveVector = p; } - public Point getMoveVector() { return moveVector; } - - public void play(Sequence sequence, long cycles) { - setSequence(sequence); - sequence.setCyclesPerAnimation(cycles); - sequence.setCurrentCycle(0); - } - public void animate() { - if(currentSequence.animationOver()) - currentSequence = mainSequence; - - if(timeToChangeImage()) currentSequence.advance(); - if(timeToMove()) move(); - if(needsRepainting()) field.paintSprite(this); - } - public void setMainSequence(Sequence sequence) { - mainSequence = sequence; - } - public Sequence getMainSequence() { - return mainSequence; - } - public void setSequence(Sequence sequence) { - currentSequence = sequence; - - if(curBounds != null) - updateBounds(); - } - public Sequence getSequence() { - return currentSequence; - } - public boolean intersects(Sprite otherSprite) { - return curBounds().intersects(otherSprite.curBounds()); - } - public boolean willIntersect(Sprite otherSprite) { - return - nextBounds().intersects(otherSprite.nextBounds()); - } - public boolean timeToMove() { - return moveTimer.elapsedTime() > moveInterval; - } - public boolean timeToChangeImage() { - return currentSequence.timeToAdvanceCell(); - } - public void moveTo(Point p) { - ulhc = p; - moveTimer.reset(); - } - public boolean needsRepainting() { - return currentSequence.needsRepainting(ulhc); - } - public void setMoveInterval(long interval) { - moveInterval = interval; - } - public void setImageChangeInterval(long interval) { - currentSequence.setAdvanceInterval(interval); - } - public void move() { - ulhc.x += moveVector.x; - ulhc.y += moveVector.y; - updateBounds(); - moveTimer.reset(); - } - public Point location() { - return ulhc; - } - public Point nextLocation() { - return new Point(ulhc.x + moveVector.x, - ulhc.y + moveVector.y); - } - public Rectangle nextBounds() { - Image nextImage = currentSequence.getNextImage(); - Point nextLoc = nextLocation(); - - return new Rectangle( - nextLoc.x, nextLoc.y, width, height); - } - public void paint(Graphics g) { - currentSequence.paint(g, ulhc.x, ulhc.y, field); - } - private void initializeBounds() { - Image curImage = currentSequence.getCurrentImage(); - - width = curImage.getWidth (field); - height = curImage.getHeight(field); - - curBounds = - new Rectangle(ulhc.x, ulhc.y, width, height); - - lastBounds = new Rectangle(curBounds.x, - curBounds.y, - curBounds.width, - curBounds.height); - - clip = lastBounds.union(curBounds); - } - private void updateBounds() { - Image curImage = currentSequence.getCurrentImage(); - - lastBounds.width = curBounds.width; - lastBounds.height = curBounds.height; - - curBounds.width = width = curImage.getWidth(field); - curBounds.height = height = curImage.getHeight(field); - - lastBounds.move(curBounds.x, curBounds.y); - curBounds.move (ulhc.x, ulhc.y); - - clip = lastBounds.union(curBounds); - } -} diff --git a/java/gjt/animation/SpriteCollisionDetector.java b/java/gjt/animation/SpriteCollisionDetector.java deleted file mode 100644 index 2ef37d79208..00000000000 --- a/java/gjt/animation/SpriteCollisionDetector.java +++ /dev/null @@ -1,45 +0,0 @@ -package gjt.animation; - -import java.awt.*; -import java.util.Enumeration; -import java.util.Vector; -import gjt.Orientation; - -/** - * A CollisionDetector that detects collisions between Sprites - * residing in a CollisionArena.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see CollisionArena - * @see CollisionDetector - * @see Sprite - * @see gjt.test.SimpleAnimationTest - * @see gjt.test.BumpAnimationTest - * @see gjt.test.TwoDrinkersAnimationTest - */ -public class SpriteCollisionDetector extends CollisionDetector { - public SpriteCollisionDetector(CollisionArena arena) { - super(arena); - } - public void detectCollisions() { - Enumeration sprites = arena.getSprites().elements(); - Sprite sprite; - - while(sprites.hasMoreElements()) { - sprite = (Sprite)sprites.nextElement(); - - Enumeration otherSprites = - arena.getSprites().elements(); - Sprite otherSprite; - - while(otherSprites.hasMoreElements()) { - otherSprite=(Sprite)otherSprites.nextElement(); - - if(otherSprite != sprite) - if(sprite.willIntersect(otherSprite)) - arena.spriteCollision(sprite,otherSprite); - } - } - } -} diff --git a/java/gjt/image/BleachImageFilter.java b/java/gjt/image/BleachImageFilter.java deleted file mode 100644 index f698a218284..00000000000 --- a/java/gjt/image/BleachImageFilter.java +++ /dev/null @@ -1,53 +0,0 @@ -package gjt.image; - -import java.awt.image.*; -import gjt.Assert; - -/** - * A derivation of RGBImageFilter that bleaches an image.<p> - * - * Extent of the bleaching effect is controlled by the only - * constructor argument: an integer representing the percentage - * of bleaching. The percentage of bleaching may also be - * controlled after instantiation by invoking the - * void percent(int) method.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see RGBImageFilter - */ -public class BleachImageFilter extends RGBImageFilter { - private int percent; - - public BleachImageFilter(int percent) { - Assert.notFalse(percent >= 0 && percent <= 100); - this.percent = percent; - canFilterIndexColorModel = true; - } - public int percent() { return percent; } - public void percent(int percent) { percent = percent; } - - public int filterRGB(int x, int y, int rgb) { - DirectColorModel cm = - (DirectColorModel)ColorModel.getRGBdefault(); - - int alpha = cm.getAlpha(rgb); - int red = cm.getRed (rgb); - int green = cm.getGreen(rgb); - int blue = cm.getBlue (rgb); - double percentMultiplier = (double)percent/100; - - red = Math.min((int) - (red + (red * percentMultiplier)), 255); - green = Math.min((int) - (green + (green * percentMultiplier)), 255); - blue = Math.min((int) - (blue + (blue * percentMultiplier)), 255); - - alpha = alpha << 24; - red = red << 16; - green = green << 8; - - return alpha | red | green | blue; - } -} diff --git a/java/gjt/image/DissolveFilter.java b/java/gjt/image/DissolveFilter.java deleted file mode 100644 index 027455b39b6..00000000000 --- a/java/gjt/image/DissolveFilter.java +++ /dev/null @@ -1,48 +0,0 @@ -package gjt.image; - -import java.awt.image.*; -import gjt.Assert; - -/** - * A derivation of RGBImageFilter that partially or wholly - * dissolves an image.<p> - * - * Extent of dissolving is set by the setOpacity(int) method, - * which is passed an integer between 0 and 255 (inclusive). - * The integer represents the alpha value to be applied to - * every color in the image.<p> - * - * An alpha value of 255 signifies an opaque color, while an - * alpha value of 0 signifies a translucent color.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see RGBImageFilter - */ -public class DissolveFilter extends RGBImageFilter { - private int opacity; - - public DissolveFilter() { - this(0); - } - public DissolveFilter(int opacity) { - canFilterIndexColorModel = true; - setOpacity(opacity); - } - public void setOpacity(int opacity) { - Assert.notFalse(opacity >= 0 && opacity <= 255); - this.opacity = opacity; - } - public int filterRGB(int x, int y, int rgb) { - DirectColorModel cm = - (DirectColorModel)ColorModel.getRGBdefault(); - int alpha = cm.getAlpha(rgb); - int red = cm.getRed (rgb); - int green = cm.getGreen(rgb); - int blue = cm.getBlue (rgb); - - alpha = opacity; - - return alpha << 24 | red << 16 | green << 8 | blue; - } -} diff --git a/java/gjt/image/ImageDissolver.java b/java/gjt/image/ImageDissolver.java deleted file mode 100644 index 5d0e6a2daf6..00000000000 --- a/java/gjt/image/ImageDissolver.java +++ /dev/null @@ -1,132 +0,0 @@ -package gjt.image; - -import java.awt.*; -import java.awt.image.*; -import gjt.Util; - -/** - * Given an image, an ImageDissolver produces an array of - * images of varying opacity that are used in the fadeIn() - * and fadeOut() methods for fading the image in and out - * respectively.<p> - * - * As a convenience, ImageDissolver has a static method: - * Image[] createImages() that creates the array of images - * mentioned above, in case clients would like to create their - * own array of images instead of using an ImageDissolver - * directly.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see ThreeDBorder - * @see ImageButtonController - * @see SpringyImageButtonController - * @see StickyImageButtonController - * @see BleachImageFilter - * @see gjt.test.ImageButtonTest - */ -public class ImageDissolver { - private static int _defaultNumImages = 10, - _defaultPause = 50; - Component comp; - int numImages, pauseInterval; - Image image, offscreen; - Image[] dissolvedImages; - - static public Image[] createImages(Image image, - int numImages, - Component component) { - Image images[] = new Image[numImages]; - MediaTracker tracker = new MediaTracker(component); - - DissolveFilter filter; - FilteredImageSource fis; - - for(int i=0; i < numImages; ++i) { - filter = new DissolveFilter((255/(numImages-1))*i); - fis = new FilteredImageSource(image.getSource(), - filter); - - images[i] = component.createImage(fis); - tracker.addImage(images[i], i); - } - try { tracker.waitForAll(); } - catch(InterruptedException e) { } - - return images; - } - - public ImageDissolver(Component comp, Image image) { - this(comp, image, _defaultNumImages, _defaultPause); - } - public ImageDissolver(Component comp, Image im, - int numImages, int pause) { - this.image = im; - this.comp = comp; - this.numImages = numImages; - dissolvedImages = new Image[numImages]; - pauseInterval = pause; - - Util.waitForImage(comp, im); - dissolvedImages = createImages(image, numImages, comp); - } - public void fadeIn(int x, int y) { - if(offscreen == null) - offscreen = comp.createImage(image.getWidth(comp), - image.getHeight(comp)); - - Graphics offg = offscreen.getGraphics(); - Graphics compg = comp.getGraphics(); - - if(offg != null && compg != null) { - clearComponent(compg, x, y); - for(int i=0; i < numImages; ++i) { - blitImage(compg, offg, x, y, i); - pause (); - } - blitOpaqueImage(compg, offg, x, y); - } - } - public void fadeOut(int x, int y) { - if(offscreen == null) - offscreen = comp.createImage(image.getWidth(comp), - image.getHeight(comp)); - - Graphics offg = offscreen.getGraphics(); - Graphics compg = comp.getGraphics(); - - if(offg != null && compg != null) { - blitOpaqueImage(compg, offg, x, y); - for(int i=numImages-1; i >= 0; --i) { - clearOffscreen(); - blitImage (compg, offg, x, y, i); - pause (); - } - } - } - private void blitImage(Graphics compg, Graphics offg, - int x, int y, int index) { - offg.drawImage (dissolvedImages[index], 0, 0, comp); - compg.drawImage(offscreen, x, y, comp); - } - private void blitOpaqueImage(Graphics compg, Graphics offg, - int x, int y) { - offg.drawImage(image, 0, 0, comp); - compg.drawImage(offscreen, x, y, comp); - } - private void clearComponent(Graphics compg, int x, int y) { - clearOffscreen(); - compg.drawImage(offscreen, x, y, comp); - } - private void clearOffscreen() { - Graphics offg = offscreen.getGraphics(); - - offg.setColor(comp.getBackground()); - offg.fillRect(0, 0, - image.getWidth(comp), image.getHeight(comp)); - } - private void pause() { - try { Thread.currentThread().sleep(pauseInterval); } - catch(InterruptedException e) { } - } -} diff --git a/java/gjt/rubberband/Rubberband.java b/java/gjt/rubberband/Rubberband.java deleted file mode 100644 index be4b1b6ac05..00000000000 --- a/java/gjt/rubberband/Rubberband.java +++ /dev/null @@ -1,100 +0,0 @@ -package gjt.rubberband; - -import java.awt.*; - -/** - * A abstract base class for rubberbands.<p> - * - * Rubberbands do their rubberbanding inside of a Component, - * which must be specified at construction time.<p> - * - * Subclasses are responsible for implementing - * <em>void drawLast(Graphics g)</em> and - * <em>void drawNext(Graphics g)</em>. - * - * drawLast() draws the appropriate geometric shape at the last - * rubberband location, while drawNext() draws the appropriate - * geometric shape at the next rubberband location. All of the - * underlying support for rubberbanding is taken care of here, - * including handling XOR mode setting; extensions of Rubberband - * need not concern themselves with anything but drawing the - * last and next geometric shapes.<p> - * - * @version 1.00, 12/27/95 - * @author David Geary - * @see RubberbandLine - * @see RubberbandRectangle - * @see RubberbandEllipse - * @see gjt.test.RubberbandTest - */ -abstract public class Rubberband { - protected Point anchor = new Point(0,0); - protected Point stretched = new Point(0,0); - protected Point last = new Point(0,0); - protected Point end = new Point(0,0); - - private Component component; - private boolean firstStretch = true; - - abstract public void drawLast(Graphics g); - abstract public void drawNext(Graphics g); - - public Rubberband(Component component) { - this.component = component; - } - public Point getAnchor () { return anchor; } - public Point getStretched() { return stretched; } - public Point getLast () { return last; } - public Point getEnd () { return end; } - - public void anchor(Point p) { - firstStretch = true; - anchor.x = p.x; - anchor.y = p.y; - - stretched.x = last.x = anchor.x; - stretched.y = last.y = anchor.y; - } - public void stretch(Point p) { - last.x = stretched.x; - last.y = stretched.y; - stretched.x = p.x; - stretched.y = p.y; - - Graphics g = component.getGraphics(); - if(g != null) { - g.setXORMode(component.getBackground()); - - if(firstStretch == true) firstStretch = false; - else drawLast(g); - - drawNext(g); - } - } - public void end(Point p) { - last.x = end.x = p.x; - last.y = end.y = p.y; - - Graphics g = component.getGraphics(); - if(g != null) { - g.setXORMode(component.getBackground()); - drawLast(g); - } - } - public Rectangle bounds() { - return new Rectangle(stretched.x < anchor.x ? - stretched.x : anchor.x, - stretched.y < anchor.y ? - stretched.y : anchor.y, - Math.abs(stretched.x - anchor.x), - Math.abs(stretched.y - anchor.y)); - } - - public Rectangle lastBounds() { - return new Rectangle( - last.x < anchor.x ? last.x : anchor.x, - last.y < anchor.y ? last.y : anchor.y, - Math.abs(last.x - anchor.x), - Math.abs(last.y - anchor.y)); - } -} diff --git a/java/gjt/rubberband/RubberbandEllipse.java b/java/gjt/rubberband/RubberbandEllipse.java deleted file mode 100644 index 50ddb0cdd6b..00000000000 --- a/java/gjt/rubberband/RubberbandEllipse.java +++ /dev/null @@ -1,32 +0,0 @@ -package gjt.rubberband; - -import java.awt.Component; -import java.awt.Graphics; -import java.awt.Rectangle; - -/** - * A Rubberband that does ellipses. - * - * @version 1.00, 12/27/95 - * @author David Geary - * @see Rubberband - * @see gjt.test.RubberbandTest - */ -public class RubberbandEllipse extends Rubberband { - private final int startAngle = 0; - private final int endAngle = 360; - - public RubberbandEllipse(Component component) { - super(component); - } - public void drawLast(Graphics graphics) { - Rectangle r = lastBounds(); - graphics.drawArc(r.x, r.y, - r.width, r.height, startAngle, endAngle); - } - public void drawNext(Graphics graphics) { - Rectangle r = bounds(); - graphics.drawArc(r.x, r.y, - r.width, r.height, startAngle, endAngle); - } -} diff --git a/java/gjt/rubberband/RubberbandLine.java b/java/gjt/rubberband/RubberbandLine.java deleted file mode 100644 index 95daafa32a6..00000000000 --- a/java/gjt/rubberband/RubberbandLine.java +++ /dev/null @@ -1,25 +0,0 @@ -package gjt.rubberband; - -import java.awt.Component; -import java.awt.Graphics; - -/** - * A Rubberband that does lines. - * - * @version 1.0, 12/27/95 - * @author David Geary - * @see Rubberband - * @see gjt.test.RubberbandTest - */ -public class RubberbandLine extends Rubberband { - public RubberbandLine(Component component) { - super(component); - } - public void drawLast(Graphics graphics) { - graphics.drawLine(anchor.x, anchor.y, last.x, last.y); - } - public void drawNext(Graphics graphics) { - graphics.drawLine(anchor.x, anchor.y, - stretched.x, stretched.y); - } -} diff --git a/java/gjt/rubberband/RubberbandPanel.java b/java/gjt/rubberband/RubberbandPanel.java deleted file mode 100644 index e4c25f4efb5..00000000000 --- a/java/gjt/rubberband/RubberbandPanel.java +++ /dev/null @@ -1,38 +0,0 @@ -package gjt.rubberband; - -import java.awt.*; - -/** - * An extension of Panel which is fitted with a Rubberband. - * Handling of mouse events is automatically handled for - * rubberbanding.<p> - * - * Clients may set or get the Rubberband at any time.<p> - * - * @version 1.0, Dec 27 1995 - * @author David Geary - * @see Rubberband - * @see gjt.test.RubberbandTest - */ -public class RubberbandPanel extends Panel { - private Rubberband rubberband; - - public void setRubberband(Rubberband rubberband) { - this.rubberband = rubberband; - } - public Rubberband getRubberband() { - return rubberband; - } - public boolean mouseDown(Event event, int x, int y) { - rubberband.anchor(new Point(x,y)); - return false; - } - public boolean mouseDrag(Event event, int x, int y) { - rubberband.stretch(new Point(x,y)); - return false; - } - public boolean mouseUp(Event event, int x, int y) { - rubberband.end(new Point(x,y)); - return false; - } -} diff --git a/java/gjt/rubberband/RubberbandRectangle.java b/java/gjt/rubberband/RubberbandRectangle.java deleted file mode 100644 index bfcb1bfc32c..00000000000 --- a/java/gjt/rubberband/RubberbandRectangle.java +++ /dev/null @@ -1,29 +0,0 @@ -package gjt.rubberband; - -import java.awt.Component; -import java.awt.Graphics; -import java.awt.Rectangle; - -/** - * A Rubberband that does rectangles. - * - * @version 1.00, 12/27/95 - * @author David Geary - * @see Rubberband - * @see gjt.test.RubberbandTest - */ -public class RubberbandRectangle extends Rubberband { - public RubberbandRectangle(Component component) { - super(component); - } - public void drawLast(Graphics graphics) { - Rectangle rect = lastBounds(); - graphics.drawRect(rect.x, rect.y, - rect.width, rect.height); - } - public void drawNext(Graphics graphics) { - Rectangle rect = bounds(); - graphics.drawRect(rect.x, rect.y, - rect.width, rect.height); - } -} diff --git a/java/gjt/test/AttributesPanel.java b/java/gjt/test/AttributesPanel.java deleted file mode 100644 index 535a12edaeb..00000000000 --- a/java/gjt/test/AttributesPanel.java +++ /dev/null @@ -1,78 +0,0 @@ -package gjt.test; - -import java.applet.Applet; -import java.awt.*; -import gjt.*; - -class AttributesPanel extends Panel { - private Applet applet; - private Box iconbox, labelbox, checkboxbox; - private Panel panelInLabelbox = new Panel(); - private Panel panelInCheckboxbox = new Panel(); - private ExclusiveImageButtonPanel panelInIconbox; - - public AttributesPanel(Applet applet) { - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints gbc = new GridBagConstraints(); - - this.applet = applet; - panelInIconbox = new ExclusiveImageButtonPanel( - Orientation.HORIZONTAL); - - populateIconPanel (); - populateLabelPanel (); - populateCheckboxPanel(); - - iconbox = new Box(panelInIconbox, - "Meaningless Images"); - labelbox = new Box(panelInLabelbox, "Labels"); - checkboxbox = new Box(panelInCheckboxbox, "Fruits"); - iconbox.etchedOut(); - - setLayout(gbl); - gbc.anchor = GridBagConstraints.NORTH; - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbc.weighty = 0.50; - gbl.setConstraints(iconbox, gbc); - add(iconbox); - gbl.setConstraints(labelbox, gbc); - add(labelbox); - - gbc.anchor = GridBagConstraints.SOUTH; - gbc.weighty = 0; - gbl.setConstraints(panelInCheckboxbox, gbc); - add(checkboxbox); - } - private void populateIconPanel() { - Image ballot, film, ticket; - - ballot = applet.getImage(applet.getCodeBase(), - "gifs/ballot_box.gif"); - ticket = applet.getImage(applet.getCodeBase(), - "gifs/movie_ticket.gif"); - film = applet.getImage(applet.getCodeBase(), - "gifs/filmstrip.gif"); - - panelInIconbox.add(ballot); - panelInIconbox.add(ticket); - panelInIconbox.add(film); - } - private void populateLabelPanel() { - panelInLabelbox.add(new Label("Label One")); - panelInLabelbox.add(new Label("Label Two")); - panelInLabelbox.add(new Label("Label Three")); - panelInLabelbox.add(new Label("Label Four")); - panelInLabelbox.add(new Label("Label Five")); - } - private void populateCheckboxPanel() { - CheckboxGroup group = new CheckboxGroup(); - - panelInCheckboxbox.setLayout(new GridLayout(3,0)); - panelInCheckboxbox.add(new Checkbox("apples", - group, false)); - panelInCheckboxbox.add(new Checkbox("oranges", - group, false)); - panelInCheckboxbox.add(new Checkbox("pears", - group, true)); - } -} diff --git a/java/gjt/test/BargaugeTest.java b/java/gjt/test/BargaugeTest.java deleted file mode 100644 index 47733d6b0bf..00000000000 --- a/java/gjt/test/BargaugeTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package gjt.test; - -import java.awt.*; -import java.applet.*; -import gjt.Bargauge; - -/** - * An array of either horizontal or vertical animated bargauges. - * The orientation of the bargauges is controlled by a parameter - * passed into the applet.<p> - * - * <em> - * Warning: An AWT bug causes this test to be a gluttenous - * consumer of resources (especially under Win95). A mouse down - * will halt the animation thread along with its consumption of - * resources.<p> - * </em> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.Bargauge - */ -public class BargaugeTest extends UnitTest { - private Bargauge[] gauges = new Bargauge[10]; - private Thread animatorThread; - private boolean running; - - public String title() { - return "Bargauge Test"; - } - public Panel centerPanel() { - return new BargaugeTestPanel( - gauges, getParameter("orientation")); - } - public boolean mouseDown(Event event, int x, int y) { - if(running == true) { - animatorThread.suspend(); - running = false; - } - else { - animatorThread.resume (); - running = true; - } - return true; - } - public void start() { - super.start(); - animatorThread = new BargaugeAnimator(gauges); - animatorThread.start(); - running = true; - } - public void stop() { - super.stop(); - animatorThread.suspend(); - running = false; - } -} - -class BargaugeTestPanel extends Panel { - public BargaugeTestPanel(Bargauge[] gauges, String orient) { - Panel bargaugePanel = new Panel(); - - setLayout(new BorderLayout()); - add("North", - new Label("Mouse Down Starts/Stops",Label.CENTER)); - add("Center", bargaugePanel); - - bargaugePanel.add(new BargaugeGridPanel(gauges,orient)); - } -} - -class BargaugeGridPanel extends Panel { - private Dimension preferredSize = new Dimension(200, 250); - - public BargaugeGridPanel(Bargauge[] gauges, String orient) { - Bargauge nextGauge; - Color color = Color.gray; - - if("horizontal".equals(orient)) - setLayout(new GridLayout(gauges.length,0,5,5)); - else - setLayout(new GridLayout(0,gauges.length,5,5)); - - for(int i=0; i < gauges.length; ++i) { - switch(i) { - case 1: color = Color.darkGray; break; - case 2: color = Color.blue; break; - case 3: color = Color.magenta; break; - case 4: color = Color.yellow; break; - case 5: color = Color.green; break; - case 6: color = Color.cyan; break; - case 7: color = Color.orange; break; - case 8: color = Color.pink; break; - case 9: color = Color.red; break; - case 10: color = Color.yellow; break; - } - nextGauge = new Bargauge(color); - gauges[i] = nextGauge; - add(nextGauge); - } - } - public Dimension preferredSize() { return preferredSize; } - public Dimension minimumSize () { return preferredSize; } -} - -class BargaugeAnimator extends Thread { - private Bargauge[] gauges; - private boolean firstAnimation = true; - - public BargaugeAnimator(Bargauge[] gauges) { - this.gauges = gauges; - } - public void run() { - int count = gauges.length; - - while(true) { - try { Thread.currentThread().sleep(500,0); } - catch(InterruptedException e) { } - for(int i=0; i < count; ++i) { - gauges[i].setFillPercent(Math.random() * 100); - gauges[i].fill(); - - if(firstAnimation) - System.out.println(gauges[i].toString()); - } - firstAnimation = false; - } - } -} diff --git a/java/gjt/test/BleachImageFilterTest.java b/java/gjt/test/BleachImageFilterTest.java deleted file mode 100644 index 08fda725a08..00000000000 --- a/java/gjt/test/BleachImageFilterTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package gjt.test; - -import java.applet.Applet; -import java.awt.*; -import java.awt.image.FilteredImageSource; - -import gjt.Util; -import gjt.image.BleachImageFilter; - -/** - * Initially displays an unbleached image. Subsequent mouse - * clicks in the canvas containing the image toggle between - * a bleached version of the image and an unbleached version.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.image.BleachImageFilter - */ -public class BleachImageFilterTest extends UnitTest { - public String title() { - return "BleachImageFilter Test " + - "(Click below to Bleach/Unbleach Picture)"; - } - public Panel centerPanel() { - return new BleachImageFilterTestPanel(this); - } -} - -class BleachImageFilterTestPanel extends Panel { - BleachImageFilterTestCanvas canvas; - - public BleachImageFilterTestPanel(Applet applet) { - add(canvas = new BleachImageFilterTestCanvas(applet)); - } - public boolean mouseDown(Event event, int x, int y) { - canvas.toggleBleaching(); - canvas.repaint(); - return true; - } -} - -class BleachImageFilterTestCanvas extends Canvas { - private Image im; - private Image bleached; - private boolean showingBleached = false; - - public BleachImageFilterTestCanvas(Applet applet) { - int bp; - String bleachPercent = - applet.getParameter("bleachPercent"); - - if(bleachPercent != null) - bp = new Integer(bleachPercent).intValue(); - else - bp = 50; - - im = applet.getImage(applet.getCodeBase(), - "gifs/saint.gif"); - Util.waitForImage(this, im); - - FilteredImageSource source = - new FilteredImageSource(im.getSource(), - new BleachImageFilter(bp)); - - bleached = createImage(source); - Util.waitForImage(this, bleached); - - showImageSize(); - } - public Dimension preferredSize() { - return new Dimension(im.getWidth(this), - im.getHeight(this)); - } - public void paint(Graphics g) { - if(showingBleached) g.drawImage(bleached,0,0,this); - else g.drawImage(im, 0,0,this); - } - public void toggleBleaching() { - showingBleached = showingBleached ? false : true; - } - private void showImageSize() { - System.out.print ("Image width=" + im.getWidth(this)); - System.out.println(" height=" + im.getHeight(this)); - } -} diff --git a/java/gjt/test/BorderTest.java b/java/gjt/test/BorderTest.java deleted file mode 100644 index 450b5ffc7ea..00000000000 --- a/java/gjt/test/BorderTest.java +++ /dev/null @@ -1,202 +0,0 @@ -package gjt.test; - -import java.applet.Applet; -import java.awt.*; -import gjt.Border; -import gjt.Box; -import gjt.EtchedBorder; -import gjt.ImageButton; -import gjt.ThreeDBorder; - -/** - * Creates 10 bordered Components: - * <dl> - * <dd> A Canvas (click in canvas to depress/raise the border). - * <dd> A Label with an etched out border. - * <dd> A TextField with an inset 3D border. - * <dd> A CheckBox with a default border. - * <dd> A List with a raised 3D border. - * <dd> A Choice with an etched in border. - * <dd> A Box with a raised 3D border. - * <dd> An ImageButton with a thick, red border. - * <dd> An AWT Button with a cyan border. - * <dd> A TextArea with a blue default-width border. - * </dl> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.Border - * @see gjt.ThreeDBorder - * @see gjt.EtchedBorder - */ -public class BorderTest extends UnitTest { - public String title() { - return "Border Test"; - } - public Panel centerPanel() { - return new BorderTestPanel(this); - } -} - -class BorderTestPanel extends Panel { - TextField tf = new TextField( - "Inset TextField: border 5 pixels, gap 5 pixels "); - ThreeDBorder threeDBorder; - EtchedBorder etchedLabel; - Border border; - - public BorderTestPanel(Applet applet) { - setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10)); - - add(new BorderedCanvas()); - add(etchedLabel = - new EtchedBorder(new Label("Etched Label"))); - add(threeDBorder = new ThreeDBorder(tf, 5, 5)); - add(new Border(new Checkbox("Check Me Out"))); - add(makeThreeDBorderedList ()); - add(makeEtchedBorderedChoice ()); - add(makeThreeDBorderedCheckboxes()); - add(makeBorderedImageButton (applet)); - add(makeBorderedAWTButton ()); - add(makeBorderedTextArea ()); - - threeDBorder.inset(); - etchedLabel.etchedOut(); - } - private Border makeThreeDBorderedList() { - List list = new List(10, true); - - list.addItem("One"); - list.addItem("Two"); - list.addItem("Three"); - list.addItem("Four"); - list.addItem("Five"); - list.addItem("Six"); - list.addItem("Seven"); - list.addItem("Eight"); - list.addItem("Nine"); - list.addItem("Ten"); - list.addItem("Eleven"); - list.addItem("Twelve"); - list.addItem("Thirteen"); - list.addItem("Fourteen"); - list.addItem("Fiveteen"); - list.addItem("Sixteen"); - list.addItem("Seventeen"); - list.addItem("Eightteen"); - list.addItem("Nineteen"); - list.addItem("Twenty"); - - return new ThreeDBorder(list); - } - private Border makeEtchedBorderedChoice() { - Choice choice = new Choice(); - - choice.addItem("Toadies"); - choice.addItem("SilverChair"); - choice.addItem("Rug Burns"); - choice.addItem("Cracker"); - choice.addItem("Seven Mary Three"); - choice.addItem("Dishwalla"); - choice.addItem("Blues Traveler"); - choice.addItem("BottleRockets"); - choice.addItem("SpaceHog"); - - return new EtchedBorder(choice); - } - private Border makeBorderedImageButton(Applet applet) { - Image snail; - Border border; - - snail = applet.getImage(applet.getCodeBase(), - "gifs/snail.gif"); - border = new Border(new ImageButton(snail), 10); - border.setLineColor(Color.red); - - return border; - } - private Border makeBorderedAWTButton() { - Button button; - Border cyanBorder, blackBorder; - - button = new Button("Button Inside Two Borders"); - cyanBorder = new Border(button, 7); - cyanBorder.setLineColor(Color.cyan); - - blackBorder = new Border(cyanBorder); - - return blackBorder; - } - private Border makeThreeDBorderedCheckboxes() { - Panel panel = new Panel(); - Box box = new Box(panel, "Options"); - CheckboxGroup group = new CheckboxGroup(); - - panel.setLayout(new GridLayout(3,0)); - panel.add(new Checkbox("bordered", group, false)); - panel.add(new Checkbox("transparent", group, false)); - panel.add(new Checkbox("continuous", group, true)); - - return new ThreeDBorder(box, 4); - } - private Border makeBorderedTextArea() { - Border border; - - border = new Border( - new TextArea("Blue Bordered TextArea", 5, 30)); - border.setLineColor(Color.blue); - - return border; - } -} - -class BorderedCanvas extends ThreeDBorder { - public BorderedCanvas() { - super(new TestCanvas()); - } - public boolean mouseDown(Event event, int x, int y) { - if(isRaised()) paintInset (); - else paintRaised(); - return true; - } -} - -class TestCanvas extends Canvas { - private boolean centeredShowing = false; - private String centered = new String ("Red Centered Text"); - - public void paint(Graphics g) { - String canvas = "Canvas"; - String click = "Click Me"; - Dimension size = size(); - FontMetrics fm = g.getFontMetrics(); - - g.drawString(canvas, (size.width/2) - - (fm.stringWidth(canvas)/2), - fm.getHeight() - fm.getDescent()); - - g.drawString(click, (size.width/2) - - (fm.stringWidth(click)/2), - size.height - fm.getHeight() + - fm.getAscent()); - - if(centeredShowing == true) { - g.setColor(Color.red); - g.drawString(centered, - size.width/2-(fm.stringWidth(centered)/2), - size.height/2 - (fm.getHeight()/2) + - fm.getAscent()); - } - } - public Dimension preferredSize() { - FontMetrics fm = getGraphics().getFontMetrics(); - return new Dimension(fm.stringWidth(centered)+10, 100); - } - public boolean mouseUp(Event event, int x, int y) { - if(centeredShowing == false) centeredShowing = true; - else centeredShowing = false; - repaint(); - return true; - } -} diff --git a/java/gjt/test/BoxTest.java b/java/gjt/test/BoxTest.java deleted file mode 100644 index 24e3de9213e..00000000000 --- a/java/gjt/test/BoxTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package gjt.test; - -import java.applet.Applet; -import java.awt.*; -import gjt.Box; -import gjt.ExclusiveImageButtonPanel; -import gjt.Orientation; - -/** - * Three Boxes, each of which surrounds either: ImageButtons, - * Labels or Checkboxes. The Box surrounding the ImageButtons - * is etched out, while the other two Boxes are etched in.<p> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.ImageButton - * @see gjt.Box - */ -public class BoxTest extends UnitTest { - public String title() { - return "Box Test"; - } - public Panel centerPanel() { - return new BoxTestPanel(this); - } -} - -class BoxTestPanel extends Panel { - private Applet applet; - private Box iconbox, labelbox, checkboxbox; - private Panel panelInLabelbox = new Panel(); - private Panel panelInCheckboxbox = new Panel(); - private ExclusiveImageButtonPanel panelInIconbox; - - public BoxTestPanel(Applet applet) { - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints gbc = new GridBagConstraints(); - - this.applet = applet; - panelInIconbox = new ExclusiveImageButtonPanel( - Orientation.HORIZONTAL); - - populateIconPanel (); - populateLabelPanel (); - populateCheckboxPanel(); - - iconbox = new Box(panelInIconbox, - "Meaningless Images"); - labelbox = new Box(panelInLabelbox, "Labels"); - checkboxbox = new Box(panelInCheckboxbox, "Fruits"); - iconbox.etchedOut(); - - setLayout(gbl); - gbc.anchor = GridBagConstraints.NORTH; - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbc.weighty = 0.50; - gbl.setConstraints(iconbox, gbc); - add(iconbox); - gbl.setConstraints(labelbox, gbc); - add(labelbox); - - gbc.anchor = GridBagConstraints.SOUTH; - gbc.weighty = 0; - gbl.setConstraints(checkboxbox, gbc); - add(checkboxbox); - } - private void populateIconPanel() { - Image ballot, film, ticket; - - ballot = applet.getImage(applet.getCodeBase(), - "gifs/ballot_box.gif"); - ticket = applet.getImage(applet.getCodeBase(), - "gifs/movie_ticket.gif"); - film = applet.getImage(applet.getCodeBase(), - "gifs/filmstrip.gif"); - - panelInIconbox.add(ballot); - panelInIconbox.add(ticket); - panelInIconbox.add(film); - } - private void populateLabelPanel() { - panelInLabelbox.add(new Label("Label One")); - panelInLabelbox.add(new Label("Label Two")); - panelInLabelbox.add(new Label("Label Three")); - panelInLabelbox.add(new Label("Label Four")); - panelInLabelbox.add(new Label("Label Five")); - } - private void populateCheckboxPanel() { - CheckboxGroup group = new CheckboxGroup(); - - panelInCheckboxbox.setLayout(new GridLayout(3,0)); - panelInCheckboxbox.add(new Checkbox("apples", - group, false)); - panelInCheckboxbox.add(new Checkbox("oranges", - group, false)); - panelInCheckboxbox.add(new Checkbox("pears", - group, true)); - } -} diff --git a/java/gjt/test/BumpAnimationTest.java b/java/gjt/test/BumpAnimationTest.java deleted file mode 100644 index 81b6fb5ce8e..00000000000 --- a/java/gjt/test/BumpAnimationTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package gjt.test; - -import java.net.URL; -import java.applet.Applet; -import java.awt.*; - -import gjt.Util; -import gjt.Orientation; -import gjt.animation.*; - -/** - * A simple animation playfield with one sprite that bounces - * off the boundaries of the playfield.<p> - * - * When the sprite bounces off the left wall, it plays a - * bump sequence once; when it bounces off the right wall - * it plays the bump sequence twice.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see gjt.animation.Playfield - * @see gjt.animation.Sprite - */ -public class BumpAnimationTest extends UnitTest { - public String title() { - return "Bump Animation - Mouse Down Starts/Stops"; - } - public Panel centerPanel() { - return new BumpAnimationTestPanel(this); - } -} - -class BumpAnimationTestPanel extends Panel { - public BumpAnimationTestPanel(Applet applet) { - setLayout(new BorderLayout()); - add("Center", new BumpPlayfield(applet)); - } -} - -class BumpPlayfield extends Playfield { - private Applet applet; - private URL cb; - private Sprite javaDrinker; - private Sequence spinSequence, bumpSequence; - - public BumpPlayfield(Applet applet) { - this.applet = applet; - cb = applet.getCodeBase(); - makeSequencesAndSprites(); - } - public void paintBackground(Graphics g) { - Image bg = applet.getImage(cb, "gifs/background.gif"); - Util.wallPaper(this, g, bg); - } - public boolean mouseDown(Event event, int x, int y) { - if(running() == true) stop (); - else start(); - return true; - } - public void spriteCollision(Sprite sprite, Sprite sprite2) { - // Nothing to do: only 1 sprite! - } - public void edgeCollision(Sprite sprite, - Orientation orientation) { - if(orientation == Orientation.RIGHT || - orientation == Orientation.LEFT) { - if(sprite.getSequence() != bumpSequence) { - sprite.reverseX(); - - if(orientation == Orientation.RIGHT) - sprite.play(bumpSequence, 1); - else - sprite.play(bumpSequence, 2); - } - } - else - sprite.reverseY(); - } - private void makeSequencesAndSprites() { - String file; - Point startLoc = new Point(10, 10); - Image[] spinImages = new Image[19]; - Image[] bumpImages = new Image[6]; - - for(int i=0; i < spinImages.length; ++i) { - file = "gifs/spin"; - - if(i < 10) file += "0" + i + ".gif"; - else file += i + ".gif"; - - spinImages[i] = applet.getImage(cb, file); - } - for(int i=0; i < bumpImages.length; ++i) { - file = "gifs/bump0" + i + ".gif"; - bumpImages[i] = applet.getImage(cb, file); - } - spinSequence = new Sequence(this, spinImages); - bumpSequence = new Sequence(this, bumpImages); - javaDrinker = new Sprite(this, spinSequence, startLoc); - - spinSequence.setAdvanceInterval(100); - bumpSequence.setAdvanceInterval(200); - - javaDrinker.setMoveVector(new Point(2,2)); - addSprite(javaDrinker); - } -} diff --git a/java/gjt/test/ChoiceCardPanelTest.java b/java/gjt/test/ChoiceCardPanelTest.java deleted file mode 100644 index 4ec27ac8945..00000000000 --- a/java/gjt/test/ChoiceCardPanelTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package gjt.test; - -import java.applet.Applet; -import java.awt.*; -import gjt.ChoiceCardPanel; - -/** - * A ChoiceCardPanel that controls three Panels.<p> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.ChoiceCardPanel - */ -public class ChoiceCardPanelTest extends UnitTest { - public String title() { return "Choice CardPanel Test"; } - public Panel centerPanel() { - return new ChoiceCardPanelTestPanel(this); - } -} - -class ChoiceCardPanelTestPanel extends Panel { - private ChoiceCardPanel mvp = new ChoiceCardPanel(); - - public ChoiceCardPanelTestPanel(Applet applet) { - setLayout(new BorderLayout()); - - mvp.addChoice("Attributes", - new AttributesPanel(applet)); - mvp.addChoice("Connections", new ConnectionsPanel()); - mvp.addChoice("Oracle", new OccupationOracle()); - add("Center", mvp); - } -} diff --git a/java/gjt/test/ColumnLayoutTest.java b/java/gjt/test/ColumnLayoutTest.java deleted file mode 100644 index fcef2151a25..00000000000 --- a/java/gjt/test/ColumnLayoutTest.java +++ /dev/null @@ -1,126 +0,0 @@ -package gjt.test; - -import java.applet.Applet; -import java.net.URL; -import java.awt.*; -import gjt.*; - -/** - * Lays out 3 image buttons, and provides controls for setting - * orientations and gaps on the fly.<p> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.ImageButton - * @see gjt.Box - */ -public class ColumnLayoutTest extends UnitTest { - public String title() { - return "ColumnLayout Test"; - } - public Panel centerPanel() { - ColumnButtonPanel buttonPanel; - Panel panel = new Panel(); - - buttonPanel = new ColumnButtonPanel(this); - - panel.setLayout(new BorderLayout()); - panel.add("Center", buttonPanel); - panel.add("North", new Box(new ColumnPicker(buttonPanel), - "Column Layout Settings")); - return panel; - } -} - -class ColumnButtonPanel extends Panel implements DialogClient { - private ImageButton one, two, three; - private Panel panel = new Panel(); - private TenPixelBorder border = new TenPixelBorder(panel); - - public ColumnButtonPanel(Applet applet) { - URL cb = applet.getCodeBase(); - - one = new ImageButton(applet.getImage(cb, - "gifs/one.gif")); - two = new ImageButton(applet.getImage(cb, - "gifs/two.gif")); - three = new ImageButton(applet.getImage(cb, - "gifs/three.gif")); - - panel.setLayout(new ColumnLayout(0)); - panel.add(one); - panel.add(two); - panel.add(three); - - setLayout(new BorderLayout()); - add ("Center", border); - } - public void updateOrientations(Orientation horient, - Orientation vorient, - int gap) { - panel.setLayout(new ColumnLayout(horient, vorient, gap)); - border.validate(); - } - public void dialogDismissed(Dialog d) { } -} - -class ColumnPicker extends Panel { - private Label horientLabel = new Label("Horizontal:"); - private Label vorientLabel = new Label("Vertical:"); - private Label gapLabel = new Label("Gap:"); - - private Choice hchoice = new Choice(); - private Choice vchoice = new Choice(); - private Choice gapChoice = new Choice(); - - private ColumnButtonPanel buttonPanel; - - public ColumnPicker(ColumnButtonPanel buttonPanel) { - Panel orientations = new Panel(); - Panel gap = new Panel(); - - this.buttonPanel = buttonPanel; - hchoice.addItem("left"); - hchoice.addItem("center"); - hchoice.addItem("right"); - hchoice.select(1); - - vchoice.addItem("top"); - vchoice.addItem("center"); - vchoice.addItem("bottom"); - vchoice.select(1); - - gapChoice.addItem("0"); - gapChoice.addItem("5"); - gapChoice.addItem("10"); - gapChoice.addItem("15"); - gapChoice.addItem("20"); - - orientations.add(horientLabel); - orientations.add(hchoice); - orientations.add(vorientLabel); - orientations.add(vchoice); - - gap.add(gapLabel); - gap.add(gapChoice); - - add(new Box(orientations, "Orientations")); - add(new Box(gap, "Gap")); - } - public boolean action(Event event, Object what) { - String horient, vorient; - int gap; - - horient = hchoice.getSelectedItem(); - vorient = vchoice.getSelectedItem(); - gap = - (new Integer(gapChoice.getSelectedItem())).intValue(); - - buttonPanel.updateOrientations( - Orientation.fromString(horient), - Orientation.fromString(vorient), gap); - - return true; - } -} diff --git a/java/gjt/test/ComponentScrollerTest.java b/java/gjt/test/ComponentScrollerTest.java deleted file mode 100644 index 4f0e4a2ec70..00000000000 --- a/java/gjt/test/ComponentScrollerTest.java +++ /dev/null @@ -1,205 +0,0 @@ -package gjt.test; - -import java.awt.*; -import java.util.Vector; -import java.applet.Applet; -import java.net.URL; - -import gjt.Border; -import gjt.ButtonPanel; -import gjt.ColumnLayout; -import gjt.ComponentScroller; -import gjt.EtchedBorder; -import gjt.ImageButton; -import gjt.RowLayout; -import gjt.Separator; -import gjt.StickyImageButtonController; - -/** - * A phony image store, where you can purchase images.<p> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see Border - * @see ButtonPanel - * @see ImageButton - * @see Separator - * @see StickyImageButtonController - * @see ComponentScroller - */ -public class ComponentScrollerTest extends UnitTest { - public String title() { - return "ComponentScroller Test"; - } - public Panel centerPanel() { - return new ComponentScrollerTestPanel(this); - } -} - -class ComponentScrollerTestPanel extends Panel { - private ComponentScroller scroller; - private Panel purchasePanel; - private ImageButtonRow nextRow; - private String[][] imageNames = { - { "gifs/ballot_box.gif", "gifs/filmstrip.gif", - "gifs/fly.gif", "gifs/eagle.gif", - "gifs/bullet_hole.gif" }, - { "gifs/mad_hacker.gif", "gifs/tricycle.gif", - "gifs/light_bulb1.gif", "gifs/scissors.gif", - "gifs/palette.gif" }, - { "gifs/frog.gif", "gifs/gear.gif", - "gifs/wrench.gif", "gifs/www.gif", - "gifs/Dining.gif" }, - { "gifs/ant.gif", "gifs/abomb.gif", - "gifs/basketball.gif", "gifs/soccer.gif", - "gifs/skelly.gif" }, - }; - public ComponentScrollerTestPanel(Applet applet) { - URL base = applet.getCodeBase(); - Image nextImage; - Border border, blackBorder; - - purchasePanel = new Panel(); - purchasePanel.setLayout(new ColumnLayout()); - - for(int r=0; r < imageNames.length; ++r) { - nextRow = new ImageButtonRow(); - nextRow.setLayout(new RowLayout()); - - for(int c=0; c < imageNames[r].length; ++c) { - nextImage = applet.getImage(base, - imageNames[r][c]); - nextRow.add(nextImage); - } - purchasePanel.add(nextRow); - } - purchasePanel.add(new ButtonPurchaseForm()); - - scroller = new ComponentScroller(); - border = new Border(purchasePanel, 3, 2); - blackBorder = new Border(border, 1, 0); - - border.setLineColor(Color.gray); - blackBorder.setLineColor(Color.black); - scroller.setComponent(blackBorder); - - setLayout(new BorderLayout()); - add("Center", scroller); - } -} - -class ButtonPurchaseForm extends Panel { - TextField nameField = new TextField(25); - TextField addressField = new TextField(25); - TextField cityField = new TextField(15); - TextField stateField = new TextField(2); - - Choice paymentChoice = new Choice(); - - Button paymentButton = new Button("Purchase"); - Button cancelButton = new Button("Cancel"); - - public ButtonPurchaseForm() { - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints gbc = new GridBagConstraints(); - - Separator sep = new Separator(); - Label title = - new Label("Purchase A Fine Image Today"); - Label name = new Label("Name:"); - Label address = new Label("Address:"); - Label payment = new Label("Purchase Method:"); - Label phone = new Label("Phone:"); - Label city = new Label("City:"); - Label state = new Label("State:"); - - setLayout(gbl); - - paymentChoice.addItem("Visa"); - paymentChoice.addItem("MasterCard"); - paymentChoice.addItem("COD"); - - title.setFont(new Font("Times-Roman", - Font.BOLD + Font.ITALIC, - 16)); - gbc.anchor = GridBagConstraints.NORTH; - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbl.setConstraints(title, gbc); - add(title); - - gbc.anchor = GridBagConstraints.NORTH; - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.insets = new Insets(0,0,10,0); - gbl.setConstraints(sep, gbc); - add(sep); - - gbc.anchor = GridBagConstraints.WEST; - gbc.gridwidth = 1; - gbc.insets = new Insets(0,0,0,10); - gbl.setConstraints(name, gbc); - add(name); - - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbl.setConstraints(nameField, gbc); - add(nameField); - - gbc.gridwidth = 1; - gbl.setConstraints(address, gbc); - add(address); - - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbc.fill = GridBagConstraints.HORIZONTAL; - gbl.setConstraints(addressField, gbc); - add(addressField); - - gbc.gridwidth = 1; - gbl.setConstraints(city, gbc); - add(city); - - gbl.setConstraints(cityField, gbc); - add(cityField); - - gbl.setConstraints(state, gbc); - add(state); - - gbl.setConstraints(stateField, gbc); - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbl.setConstraints(stateField, gbc); - add(stateField); - - gbc.gridwidth = 1; - gbl.setConstraints(payment, gbc); - gbc.insets = new Insets(5,0,5,0); - add(payment); - - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbc.fill = GridBagConstraints.NONE; - gbl.setConstraints(paymentChoice, gbc); - add(paymentChoice); - - ButtonPanel buttonPanel = new ButtonPanel(); - - buttonPanel.add(paymentButton); - buttonPanel.add(cancelButton); - - gbc.anchor = GridBagConstraints.SOUTH; - gbc.insets = new Insets(5,0,0,0); - gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.gridwidth = 4; - gbl.setConstraints(buttonPanel, gbc); - add(buttonPanel); - } -} -class ImageButtonRow extends Panel { - public ImageButtonRow() { - setLayout(new RowLayout()); - } - public void add(Image image) { - ImageButton button = new ImageButton(image); - add(button); - button.setController( - new StickyImageButtonController(button)); - } -} diff --git a/java/gjt/test/ConnectionsPanel.java b/java/gjt/test/ConnectionsPanel.java deleted file mode 100644 index 7790d0709b1..00000000000 --- a/java/gjt/test/ConnectionsPanel.java +++ /dev/null @@ -1,9 +0,0 @@ -package gjt.test; - -import java.awt.*; - -class ConnectionsPanel extends Panel { - public ConnectionsPanel() { - add(new Label("Connections")); - } -} diff --git a/java/gjt/test/DialogTest.java b/java/gjt/test/DialogTest.java deleted file mode 100644 index f92069b7c49..00000000000 --- a/java/gjt/test/DialogTest.java +++ /dev/null @@ -1,140 +0,0 @@ -package gjt.test; - -import java.awt.*; -import java.applet.Applet; - -import gjt.Util; -import gjt.DialogClient; -import gjt.MessageDialog; -import gjt.ProgressDialog; -import gjt.QuestionDialog; -import gjt.YesNoDialog; - -/** - * Tests 4 gjt custom dialogs: - * <dl> - * <dd> MessageDialog (a dialog which displays a message) - * <dd> QuestionDialog (a dialog which asks a question) - * <dd> YesNoDialog (a dialog with yes/no buttons) - * <dd> ProgressDialog (a dialog which records progress of task) - * </dl> - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.DialogClient - * @see gjt.MessageDialog - * @see gjt.ProgressDialog; - * @see gjt.QuestionDialog; - * @see gjt.YesNoDialog; - */ -public class DialogTest extends UnitTest { - public String title() { - return "Graphic Java Toolkit Dialog Test"; - } - public Panel centerPanel() { - return new DialogLauncher(); - } -} - -class DialogLauncher extends Panel implements DialogClient { - private MessageDialog messageDialog; - private QuestionDialog questionDialog; - private YesNoDialog yesNoDialog; - private ProgressDialog progressDialog; - - private Button messageDialogButton, questionDialogButton, - yesNoDialogButton, progressDialogButton; - - public DialogLauncher() { - setLayout(new GridLayout(0,1)); - - add(messageDialogButton = - new Button("Message Dialog")); - - add(questionDialogButton = - new Button("Question Dialog")); - - add(yesNoDialogButton = - new Button("YesNo Dialog")); - - add(progressDialogButton = - new Button("Progress Dialog")); - } - public boolean action(Event event, Object what) { - if(event.target == messageDialogButton) { - messageDialog = MessageDialog.getMessageDialog( - Util.getFrame(this), this, - "Example Message Dialog", - "This is an example of a message dialog."); - - messageDialog.show(); - } - else if(event.target == questionDialogButton) { - questionDialog = - new QuestionDialog(Util.getFrame(this), this, - "Example Question Dialog", - "Name: ", "Gumby", 45); - questionDialog.show(); - } - else if(event.target == yesNoDialogButton) { - yesNoDialog = - YesNoDialog.getYesNoDialog(Util.getFrame(this), - this, - "Example YesNo Dialog", - "Another cup of Java?"); - yesNoDialog.show(); - } - else if(event.target == progressDialogButton) { - progressDialog = - ProgressDialog.getProgressDialog( - Util.getFrame(this), - "Example Progress Dialog", - Color.blue); - - progressDialog.show(); - - ProgressThread thread = - new ProgressThread(progressDialog); - thread.start(); - } - - return true; - } - public void dialogDismissed(Dialog d) { - if(d == messageDialog) { - System.out.println("MessageDialog Down"); - } - if(d == questionDialog) { - if(questionDialog.wasCancelled()) - System.out.println("CANCELLED"); - else - System.out.println( - "Name: " + - questionDialog.getTextField().getText()); - } - if(d == yesNoDialog) { - if(yesNoDialog.answeredYes()) - System.out.println("YES"); - else - System.out.println("NO"); - } - } -} - -class ProgressThread extends Thread { - private ProgressDialog dialog; - private double percentComplete = 0; - - public ProgressThread(ProgressDialog dialog) { - this.dialog = dialog; - } - public void run() { - while(percentComplete <= 100) { - try { Thread.currentThread().sleep(500); } - catch(InterruptedException e) { } - - dialog.setPercentComplete(percentComplete); - percentComplete += 10; - } - } -} diff --git a/java/gjt/test/DrawnRectangleTest.java b/java/gjt/test/DrawnRectangleTest.java deleted file mode 100644 index 19e3c195f7c..00000000000 --- a/java/gjt/test/DrawnRectangleTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package gjt.test; - -import java.awt.*; -import gjt.DrawnRectangle; -import gjt.EtchedRectangle; -import gjt.ThreeDRectangle; - -/** - * 9 DrawnRectangles (some of which are EtchedRectangles - * and ThreeDRectangles) with varying characteristics such - * as line widths and colors.<p> - * - * A mouse down (any mouse button) in any of the rectangles - * causes information about the rectangle to be printed to - * System.out. (Output will go to Java Console in Netscape).<p> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.DrawnRectangle - * @see gjt.EtchedRectangle - * @see gjt.ThreeDRectangle - */ -public class DrawnRectangleTest extends UnitTest { - public String title() { - return "Drawn Rectangle Test"; - } - public Panel centerPanel() { - return new DrawnRectangleTestPanel(); - } -} - -class DrawnRectangleTestPanel extends Panel { - private DrawnRectangle drawnFilledOrange, - drawnFilledBlue, drawnBlue; - private EtchedRectangle etchedOut, - etchedIn, etchedFilledCyan; - private ThreeDRectangle thinRaised, - thinInset, thickRaised, thickInset; - - public DrawnRectangleTestPanel() { - drawnFilledOrange = - new DrawnRectangle (this, 10, 10, 100, 100); - drawnFilledBlue = - new DrawnRectangle (this, 135, 135, 100, 100); - drawnBlue = - new DrawnRectangle (this, 505, 135, 100, 100); - etchedFilledCyan = - new EtchedRectangle(this, 10, 135, 100, 100); - - etchedIn = new EtchedRectangle(this, 385, 10, 100, 100); - etchedOut= new EtchedRectangle(this, 505, 10, 100, 100); - - thinRaised = - new ThreeDRectangle(this, 135, 10, 100, 100); - thinInset = - new ThreeDRectangle(this, 260, 10, 100, 100); - thickRaised = - new ThreeDRectangle(this, 385, 135, 100, 100); - thickInset = - new ThreeDRectangle(this, 260, 135, 100, 100); - - drawnFilledOrange.setLineColor(Color.black); - - drawnFilledBlue.setLineColor(Color.yellow); - drawnFilledBlue.setThickness(3); - - drawnBlue.setLineColor(Color.blue); - drawnBlue.setThickness(5); - - thickRaised.setThickness(5); - thickInset.setThickness (5); - } - public Dimension preferredSize() { - return new Dimension(610, 270); - } - public void paint(Graphics g) { - drawnFilledOrange.paint(); - drawnFilledOrange.fill (Color.orange); - - drawnFilledBlue.paint (); - drawnFilledBlue.fill (Color.blue); - - drawnBlue.paint (); - - etchedIn.paintEtchedIn (); - etchedOut.paintEtchedOut(); - - etchedFilledCyan.paintEtchedIn(); - etchedFilledCyan.fill(Color.cyan); - - thinRaised.paintRaised (); - thinInset.paintInset (); - - thickRaised.paintRaised (); - - thickInset.paintInset (); - thickInset.fill (Color.red); - } - public boolean mouseDown(Event event, int x, int y) { - if(drawnFilledOrange.inside(x,y)) - show(drawnFilledOrange); - - if(drawnFilledBlue.inside(x,y)) show(drawnFilledBlue); - if(drawnBlue.inside(x,y)) show(drawnBlue); - if(etchedIn.inside(x,y)) show(etchedIn); - if(etchedOut.inside(x,y)) show(etchedOut); - if(etchedFilledCyan.inside(x,y)) show(etchedFilledCyan); - if(thinRaised.inside(x,y)) show(thinRaised); - if(thickRaised.inside(x,y)) show(thickRaised); - if(thinInset.inside(x,y)) show(thinInset); - if(thickInset.inside(x,y)) show(thickInset); - - return true; - } - private void show(DrawnRectangle drawnRectangle) { - System.out.println(drawnRectangle); - } -} diff --git a/java/gjt/test/FontDialogTest.java b/java/gjt/test/FontDialogTest.java deleted file mode 100644 index d0b535c27f9..00000000000 --- a/java/gjt/test/FontDialogTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package gjt.test; - -import java.awt.*; - -import gjt.FontDialog; -import gjt.DialogClient; -import gjt.Util; - -/** - * Activating the button causes the FontDialog to be displayed. - * Selecting a font from the FontDialog causes the button to - * use the selected font.<p> - * - * This unit test overrides FontDialog to reset the labels - * displayed in the buttons, and to reset the list of font - * sizes displayed. See FontDialog for a discussion of the - * overridden methods.<p> - * - *<em>Note: The FontDialog takes forever to come up in - * Netscape.</em> - * - * @version 1.0, Apr 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.Util - * @see gjt.FontDialog - * @see gjt.DialogClient - */ -class LotsOfSizesFontDialog extends FontDialog { - private static String _defaultSizes[] = - { "8", "10", "12", "14", "16", - "18", "20", "22", "24", - "26", "28", "30", "32", "34", - "36", "38", "40", "42", "44", - "46", "48", "50", "52", "54", - "56", "58", "60", "62", "64", - "66", "68", "70", "72", "74", - "76", "78", "80", "82", "84", - "86", "88", "90", "92", "94", - "96", "98", "100" }; - - public LotsOfSizesFontDialog(Frame frame, - DialogClient client, - Font font) { - super(frame, client, font, true); - } - public String getPreviewButtonLabel() { - return "Preview Selected Font"; - } - public String getOkButtonLabel () { - return "I'll Take It"; - } - public String getCancelButtonLabel () { - return "Nevermind"; - } - public String[] getFontSizes () { - return _defaultSizes; - } -} - -public class FontDialogTest extends UnitTest { - public String title() { return "Font Dialog Test"; } - public Panel centerPanel() { - return new FontDialogTestPanel(); - } -} - -class FontDialogTestPanel extends Panel - implements DialogClient { - private Button fontButton; - - public FontDialogTestPanel() { - setLayout(new BorderLayout()); - add("Center", fontButton = new Button("Fonts ...")); - } - public boolean handleEvent(Event event) { - if(event.id == Event.ACTION_EVENT) { - LotsOfSizesFontDialog d; - d = new LotsOfSizesFontDialog(Util.getFrame(this), - this, - fontButton.getFont()); - d.show(); - } - return true; - } - public void dialogDismissed(Dialog d) { - FontDialog fontDialog = (FontDialog)d; - Font fontSelected = fontDialog.getFontSelected(); - - if(fontSelected != null) - fontButton.setFont(fontSelected); - - fontButton.requestFocus(); - } -} diff --git a/java/gjt/test/IconCardPanelTest.java b/java/gjt/test/IconCardPanelTest.java deleted file mode 100644 index 33a65e1939c..00000000000 --- a/java/gjt/test/IconCardPanelTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package gjt.test; - -import java.applet.Applet; -import java.awt.*; -import java.net.URL; -import gjt.IconCardPanel; - -/** - * A gjt.IconCardPanel that controls 3 Panels.<p> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.IconCardPanel - */ -public class IconCardPanelTest extends UnitTest { - public String title() { return "IconCardPanel Test"; } - public Panel centerPanel() { - return new CardPanelTestPanel(this); - } -} -class CardPanelTestPanel extends Panel { - IconCardPanel mvp = new IconCardPanel(); - - public CardPanelTestPanel(Applet applet) { - URL cb = applet.getCodeBase(); - - setLayout(new BorderLayout()); - - Image folks = applet.getImage(cb,"gifs/cell_phone.gif"); - Image pencil = applet.getImage(cb,"gifs/clipboard.gif"); - Image library = - applet.getImage(cb, "gifs/mad_hacker.gif"); - - mvp.addImageButton(folks, - "Attributes", - new AttributesPanel(applet)); - mvp.addImageButton(pencil, - "Connections", - new ConnectionsPanel()); - mvp.addImageButton(library, - "Oracle", - new OccupationOracle()); - - add("Center", mvp); - } -} diff --git a/java/gjt/test/ImageButtonTest.java b/java/gjt/test/ImageButtonTest.java deleted file mode 100644 index 52df6efeba0..00000000000 --- a/java/gjt/test/ImageButtonTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package gjt.test; - -import java.applet.Applet; -import java.awt.*; -import gjt.Box; -import gjt.ImageButton; -import gjt.ImageButtonEvent; -import gjt.SpringyImageButtonController; -import gjt.StickyImageButtonController; - -/** - * 2 ImageButtons, one springy and the other sticky, both - * crabby.<p> - * - * Both ImageButtons come with an awt.Button that is used to - * enable/disable the ImageButton it's associated with.<p> - * - * ImageButtonEvents, along with mouse enter and mouse exit - * events for the two image buttons are printed out.<p> - * - * @version 1.0, Apr 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.ImageButton - * @see gjt.ImageButtonEvent - * @see gjt.SpringyImageButtonController - * @see gjt.StickyImageButtonController - */ -public class ImageButtonTest extends UnitTest { - public String title() { - return "ImageButton Test"; - } - public Panel centerPanel() { - return new ImageButtonTestPanel(this); - } -} - -class ImageButtonTestPanel extends Panel { - private ImageButton springyButton; - private Button springyButtonEnabler; - private ImageButton stickyButton; - private Button stickyButtonEnabler; - - public ImageButtonTestPanel(Applet applet) { - Image image; - Box springyBox, stickyBox; - GridBagLayout gbl = new GridBagLayout(); - GridBagConstraints gbc = new GridBagConstraints(); - - image = - applet.getImage(applet.getCodeBase(), "gifs/crab.gif"); - - springyButton = new ImageButton(image); - springyButtonEnabler = new Button ("Disable"); - stickyButton = new ImageButton(image); - stickyButtonEnabler = new Button ("Disable"); - - stickyButton.setController( - new StickyImageButtonController(stickyButton)); - - setLayout(gbl); - - gbc.anchor = GridBagConstraints.NORTH; - springyBox = new Box(springyButton, "Springy"); - gbc.insets = new Insets(10,0,0,0); - gbl.setConstraints(springyBox, gbc); add(springyBox); - - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbc.insets = new Insets(45,10,0,0); - gbl.setConstraints(springyButtonEnabler, gbc); - add(springyButtonEnabler); - - gbc.anchor = GridBagConstraints.NORTH; - gbc.gridwidth = 1; - stickyBox = new Box(stickyButton, "Sticky"); - gbc.insets = new Insets(10,0,0,0); - gbc.weighty = 1.0; - gbl.setConstraints(stickyBox, gbc); add(stickyBox); - - gbc.gridwidth = GridBagConstraints.REMAINDER; - gbc.insets = new Insets(45,10,0,0); - gbl.setConstraints(stickyButtonEnabler, gbc); - add(stickyButtonEnabler); - } - public boolean action(Event event, Object what) { - Button button = (Button)event.target; - String label = (String)what; - - if(button == stickyButtonEnabler) { - if(label.equals("Disable")) stickyButton.disable(); - else stickyButton.enable(); - } - else { - if(label.equals("Disable")) springyButton.disable(); - else springyButton.enable(); - } - if(label.equals("Disable")) button.setLabel("Enable"); - else button.setLabel("Disable"); - - return true; - } - public boolean handleEvent(Event event) { - boolean eventHandled = false; - - if(event instanceof ImageButtonEvent) { - System.out.println("ImageButton " + event); - eventHandled = true; - } - if(event.id == Event.MOUSE_ENTER) { - if(event.target == stickyButton) - System.out.println("Sticky Button Entered"); - - else if(event.target == springyButton) - System.out.println("Springy Button Entered"); - - eventHandled = true; - } - if(event.id == Event.MOUSE_EXIT) { - if(event.target == stickyButton) - System.out.println("Sticky Button Exited"); - - else if(event.target == springyButton) - System.out.println("Springy Button Exited"); - - eventHandled = true; - } - if(eventHandled) return true; - else return super.handleEvent(event); - } -} diff --git a/java/gjt/test/ImageDissolverTest.java b/java/gjt/test/ImageDissolverTest.java deleted file mode 100644 index c157408d2af..00000000000 --- a/java/gjt/test/ImageDissolverTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package gjt.test; - -import java.applet.Applet; -import java.awt.*; -import java.awt.image.FilteredImageSource; - -import gjt.Util; -import gjt.image.ImageDissolver; - -/** - * Initially displays an image. Subsequent mouse clicks in the - * canvas containing the image cause the image to fade in or - * fade out, depending upon it's current state.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.image.DissolveFilter - * @see gjt.image.ImageDissolver - */ -public class ImageDissolverTest extends UnitTest { - public String title() { - return "ImageDissolver Test " + - "(Click Below to Fade Picture In/Out)"; - } - public Panel centerPanel() { - return new ImageDissolverTestPanel(this); - } -} - -class ImageDissolverTestPanel extends Panel { - ImageDissolverTestCanvas canvas; - - public ImageDissolverTestPanel(Applet applet) { - add(canvas = new ImageDissolverTestCanvas(applet)); - } - public boolean mouseDown(Event event, int x, int y) { - canvas.doFade(); - return true; - } -} - -class ImageDissolverTestCanvas extends Canvas { - private boolean isFaded = false; - private Image image; - private ImageDissolver dissolver; - - public ImageDissolverTestCanvas(Applet applet) { - image = - applet.getImage(applet.getCodeBase(),"gifs/saint.gif"); - - Util.waitForImage(this, image); - dissolver = new ImageDissolver(this, image); - } - public void paint(Graphics g) { - if( ! isFaded) - g.drawImage(image, 0, 0, this); - } - public Dimension preferredSize() { - return new Dimension(image.getWidth(this), - image.getHeight(this)); - } - public void doFade() { - if(isFaded) dissolver.fadeIn (0,0); - else dissolver.fadeOut(0,0); - - isFaded = isFaded ? false : true; - } -} diff --git a/java/gjt/test/ImageScrollerTest.java b/java/gjt/test/ImageScrollerTest.java deleted file mode 100644 index 0476682eb6d..00000000000 --- a/java/gjt/test/ImageScrollerTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package gjt.test; - -import java.awt.*; -import java.applet.Applet; -import java.net.URL; - -import gjt.ImageScroller; -import gjt.Util; - -/** - * Four images are loaded; subsequent mouse clicks cycle - * through the images, that are displayed in an ImageScroller. - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.Scroller - * @see gjt.ImageScroller - */ -public class ImageScrollerTest extends UnitTest { - public String title() { - return "ImageScroller Test"; - } - public Panel centerPanel() { - return new ImageScrollerTestPanel(this); - } -} - -class ImageScrollerTestPanel extends Panel { - private Image[] images = new Image[4]; - private int imageIndex = 0; - private ImageScroller scroller; - - public ImageScrollerTestPanel(Applet applet) { - URL cb = applet.getCodeBase(); - - images[0]=applet.getImage(cb,"gifs/ashleyAndRoy.gif"); - images[1]=applet.getImage(cb,"gifs/ashleyAndSabre.gif"); - images[2]=applet.getImage(cb,"gifs/anjinAndMariko.gif"); - images[3]=applet.getImage(cb,"gifs/ashleyAndAnjin.gif"); - - setLayout(new BorderLayout()); - add("Center", scroller = new ImageScroller(images[0])); - } - public boolean mouseUp(Event event, int x, int y) { - if(imageIndex == images.length-1) imageIndex = 0; - else imageIndex++; - - Util.setCursor(Frame.WAIT_CURSOR, this); - scroller.resetImage(images[imageIndex]); - Util.setCursor(Frame.DEFAULT_CURSOR, this); - - return true; - } -} diff --git a/java/gjt/test/LabelCanvasTest.java b/java/gjt/test/LabelCanvasTest.java deleted file mode 100644 index cb4c0a857ae..00000000000 --- a/java/gjt/test/LabelCanvasTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package gjt.test; -import java.applet.Applet; -import java.awt.Event; -import java.awt.Panel; -import java.awt.Insets; -import java.awt.Graphics; -import gjt.LabelCanvas; -import gjt.SelectionEvent; -import gjt.Util; - -/** - * Four LabelCanvases, each with different insets. The leftmost - * LabelCanvas has standard insets (2 all around), while the - * other three were constructed as follows: - * <pre> - * insetFive.setInsets (new Insets(5,5,5,5)); - * insetTen.setInsets (new Insets(10,10,10,10)); - * insetFifteen.setInsets(new Insets(15,15,15,15)); - * </pre><p> - * - * LabelCanvases generate SelectionEvents, that we watch - * for in our handleEvent() method, and print out.<p> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.LabelCanvas - */ -public class LabelCanvasTest extends UnitTest { - public String title() { return "LabelCanvas Test"; } - public Panel centerPanel() { - return new LabelCanvasTestPanel(this); - } -} - -class LabelCanvasTestPanel extends Panel { - Applet applet; - public LabelCanvasTestPanel(Applet applet) { - this.applet = applet; - LabelCanvas standard = - new LabelCanvas("Standard Insets"); - LabelCanvas insetFive = - new LabelCanvas("Insets = Five"); - LabelCanvas insetTen = - new LabelCanvas("Insets = Ten"); - LabelCanvas insetFifteen = - new LabelCanvas("Insets = Fifteen"); - - insetFive.setInsets (new Insets(5,5,5,5)); - insetTen.setInsets (new Insets(10,10,10,10)); - insetFifteen.setInsets(new Insets(15,15,15,15)); - - add(standard); - add(insetFive); - add(insetTen); - add(insetFifteen); - } - public boolean handleEvent(Event event) { - if(event instanceof SelectionEvent) { - SelectionEvent sevent = (SelectionEvent)event; - LabelCanvas canvas = (LabelCanvas)event.target; - - if(sevent.isSelected()) - System.out.println("LabelCanvas " + - canvas.getLabel() + - " selected"); - else - System.out.println("LabelCanvas " + - canvas.getLabel() + - " deselected"); - return true; - } - return super.handleEvent(event); - } -} diff --git a/java/gjt/test/MessageDialogTest.java b/java/gjt/test/MessageDialogTest.java deleted file mode 100644 index 6efddd08cb4..00000000000 --- a/java/gjt/test/MessageDialogTest.java +++ /dev/null @@ -1,50 +0,0 @@ - -package gjt.test; - -import java.awt.*; -import java.applet.Applet; - -import gjt.MessageDialog; -import gjt.DialogClient; -import gjt.Util; - -/** - * Simple unit test that exercises gjt.MessageDialog. This - * unit test serves to illustrate the use of gjt.DialogClient. - * For a unit test which covers all of the gjt dialogs, - * see gjt.test.DialogTest. - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.DialogClient - * @see gjt.MessageDialog - */ -public class MessageDialogTest extends UnitTest { - public String title() { - return "Message Dialog Test"; - } - public Panel centerPanel() { - return new MessageDialogLauncher(); - } -} - -class MessageDialogLauncher extends Panel - implements DialogClient { - private MessageDialog messageDialog; - - public MessageDialogLauncher() { - add(new Button("Show Message Dialog")); - } - public boolean action(Event event, Object what) { - messageDialog = MessageDialog.getMessageDialog( - Util.getFrame(this), this, - "Example Message Dialog", - "This is an example of a message dialog."); - messageDialog.show(); - return true; - } - public void dialogDismissed(Dialog d) { - System.out.println("MessageDialog Down"); - } -} diff --git a/java/gjt/test/OccupationOracle.java b/java/gjt/test/OccupationOracle.java deleted file mode 100644 index a34c2ad2064..00000000000 --- a/java/gjt/test/OccupationOracle.java +++ /dev/null @@ -1,334 +0,0 @@ -package gjt.test; - -import java.applet.Applet; -import java.awt.*; - -// The OccupationOracle class makes a guess at a person's occupation -// within an engineering organization based on a few "key" traits. -// Invalid entries in numeric fields result in an "Unknown" occupation. -// This applet uses the awt.GridBagLayout class to structure the -// occupation form. The awt.GridBagLayout class allows fields to -// be placed in rows and columns within a form. Each component -// is given a "display area" based on the constraints in effect -// when it is added to the layout. - -// Author: Jerry Jackson (thanks, sifu) - -public class OccupationOracle extends Panel { - - // Construct the form. Create each component of the form and - // add it to the layout. Initialize the occupation to "Unknown". - - public OccupationOracle() { - - // Use the GridBagLayout layout to construct rows and - // columns. - - GridBagLayout gridbag = new GridBagLayout(); - - // Create a new set of constraints to use when adding - // a component to the layout. The constraint values - // in effect when a component is added to the layout - // are cloned and stored in conjunction with the component - // by the layout. - - GridBagConstraints constraints = new GridBagConstraints(); - - // Set the font for the form. - - //setFont(new Font("TimesRoman", Font.BOLD, 12)); - - // Associate the GridBagLayout object with the applet. - - setLayout(gridbag); - - // The "anchor" constraint determines how a component - // is justified within its display area. - - constraints.anchor = GridBagConstraints.WEST; - - // Determines how much space should be given to this component. - // if left at 0.0, all components clump up in the middle as the - // padding is applied to the outside. - - constraints.weightx = 1.0; - - // Create a name label and text field. - - makeNameField(); - - // Setting the "gridwidth" constraint to 1 will - // cause the component to take up the minimum - // horizontal space in its row. - - constraints.gridwidth = 1; - - // "addFormComponent" will associate the current constraints - // with a component and add the component to the form. - - addFormComponent(gridbag, nameLabel, constraints); - - // Setting the "gridwidth" constraint to REMAINDER will - // cause the component to fill up the remainder of its row. - // i.e. it will be the last entry in the row. - - constraints.gridwidth = GridBagConstraints.REMAINDER; - - // The "fill" constraint tells what to do if the item is in - // a area larger than it is. In this case we want to fill - // any extra horizontal space. - - constraints.fill = GridBagConstraints.HORIZONTAL; - - addFormComponent(gridbag, nameField, constraints); - - // Create and add an age label and text field. - - makeAgeField(); - - constraints.gridwidth = 1; - constraints.fill = GridBagConstraints.NONE; - constraints.weightx = 0.0; - addFormComponent(gridbag, ageLabel, constraints); - constraints.gridwidth = GridBagConstraints.REMAINDER; - constraints.weightx = 1.0; - addFormComponent(gridbag, ageField, constraints); - - // Create and add a world view label and a single checkbox - // for a true/false value. - - makeWorldViewField(); - - constraints.gridwidth = 1; - constraints.weightx = 0.0; - addFormComponent(gridbag, worldViewLabel, constraints); - constraints.gridwidth = GridBagConstraints.REMAINDER; - constraints.weightx = 1.0; - addFormComponent(gridbag, worldViewField, constraints); - - - // Create and add a coffee consumption label and text field. - - makeCoffeeField(); - - constraints.gridwidth = 1; - constraints.weightx = 0.0; - addFormComponent(gridbag, coffeeLabel, constraints); - constraints.gridwidth = GridBagConstraints.REMAINDER; - constraints.weightx = 1.0; - addFormComponent(gridbag, coffeeField, constraints); - - - // Create and add a fashion sense label and a checkbox - // group that has three mutually exclusive values. - - makeFashionField(); - - constraints.gridwidth = GridBagConstraints.REMAINDER; - constraints.weightx = 0.0; - constraints.weighty = 0.0; - addFormComponent(gridbag, fashionLabel, constraints); - - // The three checkboxes that represent fashion sense. - - addFormComponent(gridbag, low, constraints); - addFormComponent(gridbag, medium, constraints); - addFormComponent(gridbag, high, constraints); - - // The Occupation field is output only. - - makeOccupationField(); - - constraints.gridwidth = 1; - constraints.weightx = 0.0; - constraints.weighty = 1.0; - constraints.fill = GridBagConstraints.NONE; - addFormComponent(gridbag, occupationLabel, constraints); - constraints.fill = GridBagConstraints.HORIZONTAL; - constraints.gridwidth = GridBagConstraints.REMAINDER; - constraints.weightx = 1.0; - addFormComponent(gridbag, occupationField, constraints); - - // Display the initial "Unknown" occupation. - - recalculateOccupation(); - - resize(400, 250); - } - - // The paint() method for this applet just calls the paintComponents() - // method which is defined by the Container class. It causes all - // the components visible within the Container to get painted. - - public void paint(Graphics g) { - paintComponents(g); - } - - // When any action occurs within the form we do the same thing: - // recalculate the person's occupation. - - public boolean action(Event event, Object arg) { - recalculateOccupation(); - return true; - } - - // A helper function that associates constraints with a component - // and adds it to the form. - - private void addFormComponent(GridBagLayout grid, Component comp, - GridBagConstraints c) { - grid.setConstraints(comp, c); - add(comp); - } - - - // recalculateOccupation() fetches the values of each component - // and computes an occupation based on some truly stupid heuristics. - - private void recalculateOccupation() { - - // If we don't have a name yet we might incorrectly categorize - // the CEO! - - if (nameField.getText() == "") { - occupationField.setText("Unknown"); - } - - // Fetch other important values that we'll use in our - // calculations. - - int age; - int coffeeConsumption; - boolean binaryView = worldViewField.getState(); - - - // Try to fetch integer values for age and coffeeConsumption. - // If the values in the fields can't be parsed as integers, - // set the occupation to "Unknown". - - try { - age = Integer.parseInt(ageField.getText()); - coffeeConsumption = Integer.parseInt(coffeeField.getText()); - } catch (Exception e) { - occupationField.setText("Unknown"); - return; - } - - // Check for the CEO. - - String name = nameField.getText(); - - if (name.endsWith("II") || - name.endsWith("III") || - name.endsWith("IV")) { - - if (age < 35 || coffeeConsumption < 4) { - occupationField.setText("Junior Executive"); - } else { - occupationField.setText("CEO"); - } - - return; - } - - // Fashion sense is a critical piece of information. - // The getCurrent() method of CheckboxGroup returns whichever - // Checkbox in the group is currently selected. Only one - // can be selected at a time. - - Checkbox fashionValue = fashionGroup.getCurrent(); - - if (fashionValue == low || fashionValue == medium) { - - // There are two kinds of people in the world: those who - // divide people into two kinds and those who don't. - - if (binaryView && coffeeConsumption >= 4) { - occupationField.setText("Engineer"); - - } else if ((age > 40 && binaryView) || - (age < 40 && coffeeConsumption >= 4)) { - occupationField.setText("Engineering Manager"); - - } else { - occupationField.setText("Product Manager"); - } - - } else { - - // High fashion sense. Not an engineer! - - if (binaryView || coffeeConsumption >= 4) { - occupationField.setText("Vice President"); - - } else { - occupationField.setText("Product Marketing"); - } - } - } - - // Helper functions to create form components. - - private void makeNameField() { - nameLabel = new Label("Name: "); - nameField = new TextField(40); - } - - private void makeAgeField() { - ageLabel = new Label("Age: "); - ageField = new TextField(3); - } - - private void makeOccupationField() { - occupationLabel = new Label("Occupation: "); - occupationField = new TextField(40); - } - - private void makeWorldViewField() { - worldViewLabel = new Label("Binary World View: "); - worldViewField = new Checkbox(); - } - - private void makeCoffeeField() { - coffeeLabel = new Label("Coffee consumption: "); - coffeeField = new TextField(3); - } - - private void makeFashionField() { - fashionLabel = new Label("Fashion sense:"); - - fashionGroup = new CheckboxGroup(); - low = new Checkbox("Low ", fashionGroup, false); - medium = new Checkbox("Medium", fashionGroup, true); - high = new Checkbox("High ", fashionGroup, false); - } - - // Text fields. - - private TextField nameField; - private TextField ageField; - private TextField coffeeField; - private TextField occupationField; - - // Labels. - - private Label nameLabel; - private Label ageLabel; - private Label coffeeLabel; - private Label fashionLabel; - private Label worldViewLabel; - private Label occupationLabel; - - // Checkboxes. - - private Checkbox worldViewField; - private Checkbox low; - private Checkbox medium; - private Checkbox high; - - // The fashion sense checkbox group. - - private CheckboxGroup fashionGroup; -} - - diff --git a/java/gjt/test/RowLayoutTest.java b/java/gjt/test/RowLayoutTest.java deleted file mode 100644 index eb7b419ca17..00000000000 --- a/java/gjt/test/RowLayoutTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package gjt.test; - -import java.applet.Applet; -import java.net.URL; -import java.awt.*; -import gjt.*; - -/** - * Lays out 3 image buttons, and provides controls for setting - * orientations and gaps on the fly.<p> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.ImageButton - * @see gjt.Box - */ -public class RowLayoutTest extends UnitTest { - public String title() { - return "RowLayout Test"; - } - public Panel centerPanel() { - RowButtonPanel buttonPanel = new RowButtonPanel(this); - Panel panel = new Panel(); - - panel.setLayout(new BorderLayout()); - panel.add("Center", buttonPanel); - panel.add("North", new Box(new RowPicker(buttonPanel), - "Row Layout Settings")); - return panel; - } -} - -class RowButtonPanel extends Panel implements DialogClient { - private ImageButton one, two, three; - private Panel panel = new Panel(); - private TenPixelBorder border = new TenPixelBorder(panel); - - public RowButtonPanel(Applet applet) { - URL cb = applet.getCodeBase(); - - one = new ImageButton(applet.getImage(cb, - "gifs/one.gif")); - two = new ImageButton(applet.getImage(cb, - "gifs/two.gif")); - three = new ImageButton(applet.getImage(cb, - "gifs/three.gif")); - - panel.setLayout(new RowLayout(0)); - panel.add(one); - panel.add(two); - panel.add(three); - - setLayout(new BorderLayout()); - add ("Center", border); - } - public void updateOrientations(Orientation horient, - Orientation vorient, - int gap) { - panel.setLayout(new RowLayout(horient, vorient, gap)); - border.validate(); - } - public void dialogDismissed(Dialog d) { } -} - -class RowPicker extends Panel { - private Label horientLabel = new Label("Horizontal:"); - private Label vorientLabel = new Label("Vertical:"); - private Label gapLabel = new Label("Gap:"); - - private Choice hchoice = new Choice(); - private Choice vchoice = new Choice(); - private Choice gapChoice = new Choice(); - - private RowButtonPanel buttonPanel; - - public RowPicker(RowButtonPanel buttonPanel) { - Panel orientations = new Panel(); - Panel gap = new Panel(); - - this.buttonPanel = buttonPanel; - hchoice.addItem("left"); - hchoice.addItem("center"); - hchoice.addItem("right"); - hchoice.select(1); - - vchoice.addItem("top"); - vchoice.addItem("center"); - vchoice.addItem("bottom"); - vchoice.select(1); - - gapChoice.addItem("0"); - gapChoice.addItem("5"); - gapChoice.addItem("10"); - gapChoice.addItem("15"); - gapChoice.addItem("20"); - - orientations.add(horientLabel); - orientations.add(hchoice); - orientations.add(vorientLabel); - orientations.add(vchoice); - - gap.add(gapLabel); - gap.add(gapChoice); - - add(new Box(orientations, "Orientations")); - add(new Box(gap, "Gap")); - } - public boolean action(Event event, Object what) { - String horient, vorient; - int gap; - - horient = hchoice.getSelectedItem(); - vorient = vchoice.getSelectedItem(); - gap = - (new Integer(gapChoice.getSelectedItem())).intValue(); - - buttonPanel.updateOrientations( - Orientation.fromString(horient), - Orientation.fromString(vorient), gap); - - return true; - } -} diff --git a/java/gjt/test/RubberbandTest.java b/java/gjt/test/RubberbandTest.java deleted file mode 100644 index ae256fb2c3a..00000000000 --- a/java/gjt/test/RubberbandTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package gjt.test; - -import java.awt.*; -import gjt.DrawingPanel; -import gjt.Separator; -import gjt.RowLayout; -import gjt.rubberband.*; - -/** - * A simple drawing applet that demonstrates the utility of - * the gjt.rubberband package.<p> - * - * Note that this unit test also serves as the unit test for - * gjt.DrawingPanel.<p> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.DrawingPanel - * @see gjt.rubberband.Rubberband - * @see gjt.rubberband.RubberbandLine - * @see gjt.rubberband.RubberbandRectangle - * @see gjt.rubberband.RubberbandEllipse - * @see gjt.rubberband.RubberbandPanel - */ -public class RubberbandTest extends UnitTest { - public String title() { - return "Rubberband Test"; - } - public Panel centerPanel() { - return new RubberbandTestPanel(); - } -} - -class RubberbandTestPanel extends Panel { - private DrawingPanel drawingPanel; - private ChoicePanel choicePanel; - - public RubberbandTestPanel() { - drawingPanel = new DrawingPanel(); - choicePanel = new ChoicePanel(drawingPanel); - - setLayout(new BorderLayout()); - add("North", choicePanel); - add("Center", drawingPanel); - } -} - -class ChoicePanel extends Panel { - private DrawingPanel drawingPanel; - private Color color; - private Checkbox fillCheckbox = new Checkbox(); - - public ChoicePanel(DrawingPanel drawingPanel) { - Panel choicePanel = new Panel(); - Choice geometricChoice = new Choice(); - Choice colorChoice = new Choice(); - - this.drawingPanel = drawingPanel; - - geometricChoice.addItem("Lines"); - geometricChoice.addItem("Rectangles"); - geometricChoice.addItem("Ellipses"); - - colorChoice.addItem("Black"); - colorChoice.addItem("Red"); - colorChoice.addItem("Blue"); - colorChoice.addItem("Gray"); - colorChoice.addItem("White"); - - choicePanel.setLayout(new RowLayout(10)); - choicePanel.add(new Label("Shape:")); - choicePanel.add(geometricChoice); - choicePanel.add(new Label("Color:")); - choicePanel.add(colorChoice); - choicePanel.add(new Label("Fill:")); - choicePanel.add(fillCheckbox); - - setLayout(new BorderLayout()); - add("Center", choicePanel); - add("South", new Separator()); - } - public boolean action(Event event, Object what) { - if(event.target instanceof Checkbox) { - drawingPanel.setFill(fillCheckbox.getState()); - } - else if(event.target instanceof Choice) { - if(((String)what).equals("Lines")) { - fillCheckbox.setState(false); - drawingPanel.drawLines(); - } - else if(((String)what).equals("Rectangles")) { - System.out.println("Rectangles"); - drawingPanel.drawRectangles(); - } - else if(((String)what).equals("Ellipses")) - drawingPanel.drawEllipses (); - else if(((String)what).equals("Black")) - drawingPanel.setColor(Color.black); - else if(((String)what).equals("Red")) - drawingPanel.setColor(Color.red); - else if(((String)what).equals("Blue")) - drawingPanel.setColor(Color.blue); - else if(((String)what).equals("Gray")) - drawingPanel.setColor(Color.gray); - else if(((String)what).equals("White")) - drawingPanel.setColor(Color.white); - } - return true; - } - public Insets insets() { return new Insets(5,0,5,0); } -} diff --git a/java/gjt/test/SeparatorTest.java b/java/gjt/test/SeparatorTest.java deleted file mode 100644 index 3dd80173ea3..00000000000 --- a/java/gjt/test/SeparatorTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package gjt.test; - -import java.awt.*; -import gjt.Etching; -import gjt.Separator; - -/** - * Two Separators, one horizontal and the other vertical, the - * former etched in, and the latter etched out are laid out with - * an adorning Label for each.<p> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.UnitTest - * @see gjt.Separator - */ -public class SeparatorTest extends UnitTest { - public String title () { return "Separator Test"; } - public Panel centerPanel() { - return new SeparatorTestPanel(); - } -} - -class SeparatorTestPanel extends Panel { - public SeparatorTestPanel() { - setLayout(new BorderLayout()); - add("North", new SeparatorTestNorthPanel ()); - add("Center", new SeparatorTestCenterPanel()); - } -} - -class SeparatorTestNorthPanel extends Panel { - Separator separator = new Separator(); - - public SeparatorTestNorthPanel() { - setLayout(new BorderLayout()); - add("North", new Label("North Of Etched-In Separator")); - add("South", separator); - } -} - -class SeparatorTestCenterPanel extends Panel { - Separator separator = new Separator(Etching.OUT); - - public SeparatorTestCenterPanel() { - GridBagConstraints gbc = new GridBagConstraints(); - GridBagLayout gbl = new GridBagLayout(); - Label label = new Label("West Of Etched-Out Separator"); - - setLayout(gbl); - gbc.anchor = GridBagConstraints.WEST; - gbc.insets = new Insets(0,0,0,10); - gbl.setConstraints(label, gbc); - add(label); - - gbc.insets = new Insets(0,0,0,0); - gbc.weightx = 1.0; - gbc.weighty = 1.0; - gbc.fill = GridBagConstraints.VERTICAL; - gbl.setConstraints(separator, gbc); - add(separator); - - } -} diff --git a/java/gjt/test/SimpleAnimationTest.java b/java/gjt/test/SimpleAnimationTest.java deleted file mode 100644 index faf0c7c611c..00000000000 --- a/java/gjt/test/SimpleAnimationTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package gjt.test; - -import java.net.URL; -import java.applet.Applet; -import java.awt.*; - -import gjt.Util; -import gjt.Orientation; -import gjt.animation.*; - -/** - * An animation playfield containing a lone sprite that bounces - * off the boundaries of the playfield.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see gjt.test.AnimationTest - * @see gjt.animation.Playfield - * @see gjt.animation.Sprite - */ -public class SimpleAnimationTest extends UnitTest { - public String title() { - return "Simple Animation - Mouse Down Starts/Stops"; - } - public Panel centerPanel() { - return new SimpleAnimationTestPanel(this); - } -} - -class SimpleAnimationTestPanel extends Panel { - public SimpleAnimationTestPanel(Applet applet) { - setLayout(new BorderLayout()); - add("Center", new SimplePlayfield(applet)); - } -} - -class SimplePlayfield extends Playfield { - private Applet applet; - private URL cb; - private Sprite javaDrinker; - private Sequence spinSequence; - - public SimplePlayfield(Applet applet) { - this.applet = applet; - cb = applet.getCodeBase(); - makeSequencesAndSprites(); - } - public void paintBackground(Graphics g) { - Image bg = applet.getImage(cb, "gifs/background.gif"); - Util.wallPaper(this, g, bg); - } - public boolean mouseDown(Event event, int x, int y) { - if(running() == true) stop (); - else start(); - return true; - } - public void spriteCollision(Sprite sprite, Sprite sprite2) { - // Nothing to do: only 1 sprite! - } - public void edgeCollision(Sprite sprite, - Orientation orientation) { - if(orientation == Orientation.RIGHT || - orientation == Orientation.LEFT) - sprite.reverseX(); - else - sprite.reverseY(); - } - private void makeSequencesAndSprites() { - String file; - Point startLoc = new Point(10, 10); - Image[] spinImages = new Image[19]; - - for(int i=0; i < spinImages.length; ++i) { - file = "gifs/spin"; - - if(i < 10) file += "0" + i + ".gif"; - else file += i + ".gif"; - - spinImages[i] = applet.getImage(cb, file); - } - spinSequence = new Sequence(this, spinImages); - javaDrinker = new Sprite(this, spinSequence, startLoc); - - javaDrinker.setMoveVector(new Point(2,2)); - addSprite(javaDrinker); - } -} diff --git a/java/gjt/test/SimpleBargaugeTest.java b/java/gjt/test/SimpleBargaugeTest.java deleted file mode 100644 index 57eb464f4b1..00000000000 --- a/java/gjt/test/SimpleBargaugeTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package gjt.test; - -import java.awt.*; -import gjt.Bargauge; - -/** - * A lone Barguage which animates. This unit test is meant to - * illustrate that a Bargauge can cope with having its - * orientation chanaged from horizontal to vertical or - * vice-versa. This test is best run in appletviewer, so that - * the window may be resized such that the Bargauge changes its - * orientation.<p> - * - * <em> - * Warning: An AWT bug causes this test to be a gluttenous - * consumer of resources (especially under Win95). A mouse down - * will halt the animation thread along with its consumption of - * resources.<p> - * </em> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.Bargauge - */ -public class SimpleBargaugeTest extends UnitTest { - public String title() { - return "Simple Bargauge Test"; - } - public Panel centerPanel() { - return new SimpleBargaugeTestPanel(); - } -} - -class SimpleBargaugeTestPanel extends Panel implements Runnable { - private Bargauge gauge = new Bargauge(Color.blue); - private boolean running = true; - private Thread t; - - public SimpleBargaugeTestPanel() { - setLayout(new BorderLayout()); - add("Center", gauge); - - t = new Thread(this); - t.start(); - } - public void run() { - while(true) { - try { Thread.currentThread().sleep(500,0); } - catch(InterruptedException e) { } - - gauge.setFillPercent(Math.random() * 100); - gauge.fill(); - } - } - public boolean mouseDown(Event event, int x, int y) { - if(running) { t.suspend(); running = false; } - else { t.resume (); running = true; } - return true; - } -} diff --git a/java/gjt/test/StateButtonTest.java b/java/gjt/test/StateButtonTest.java deleted file mode 100644 index 508aee1682e..00000000000 --- a/java/gjt/test/StateButtonTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package gjt.test; - -import java.applet.Applet; -import java.awt.*; -import java.net.URL; -import gjt.StateButton; -import gjt.ImageButtonEvent; - -/** - * A StateButton which cycles through a fascinating series of - * Images.<p> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.StateButton - */ -public class StateButtonTest extends UnitTest { - public String title () { return "StateButton Test"; } - public Panel centerPanel() { - return new StateButtonTestPanel(this); - } -} - -class StateButtonTestPanel extends Panel { - private URL codeBase; - private Image[] images; - private StateButton button; - - public StateButtonTestPanel(Applet applet) { - codeBase = applet.getCodeBase(); - images = new Image[3]; - images[0] = applet.getImage(codeBase, "gifs/fly.gif"); - images[1] = applet.getImage(codeBase, "gifs/frog.gif"); - images[2] = applet.getImage(codeBase, "gifs/eagle.gif"); - button = new StateButton(images); - - setLayout(new FlowLayout(FlowLayout.CENTER, 20, 20)); - add (button); - } -} diff --git a/java/gjt/test/TenPixelBorder.java b/java/gjt/test/TenPixelBorder.java deleted file mode 100644 index bab694d0fb1..00000000000 --- a/java/gjt/test/TenPixelBorder.java +++ /dev/null @@ -1,44 +0,0 @@ -package gjt.test; - -import java.awt.*; - -public class TenPixelBorder extends Panel { - public TenPixelBorder(Component borderMe) { - setLayout(new BorderLayout()); - add("Center", borderMe); - } - public void paint(Graphics g) { - Dimension mySize = size(); - Insets myInsets = insets(); - - g.setColor(Color.gray); - - // Top Inset area - g.fillRect(0, - 0, - mySize.width, - myInsets.top); - - // Left Inset area - g.fillRect(0, - 0, - myInsets.left, - mySize.height); - - // Right Inset area - g.fillRect(mySize.width - myInsets.right, - 0, - myInsets.right, - mySize.height); - - // Bottom Inset area - g.fillRect(0, - mySize.height - myInsets.bottom, - mySize.width, - mySize.height); - } - public Insets insets() { - return new Insets(10,10,10,10); - } - -} diff --git a/java/gjt/test/TitledPanel.java b/java/gjt/test/TitledPanel.java deleted file mode 100644 index cb8d054e888..00000000000 --- a/java/gjt/test/TitledPanel.java +++ /dev/null @@ -1,22 +0,0 @@ -package gjt.test; - -import java.awt.BorderLayout; -import java.awt.Label; -import java.awt.Panel; -import gjt.Separator; - -/** - * A Panel fitted with a BorderLayout that contains a Label - * (title) in the North, and a Separator in the South. - * - * @version 1.0, Apr 2 1996 - * @author David Geary - */ - -public class TitledPanel extends Panel { - public TitledPanel(String title) { - setLayout(new BorderLayout()); - add("North", new Label(title, Label.CENTER)); - add("South", new Separator()); - } -} diff --git a/java/gjt/test/ToolbarTest.java b/java/gjt/test/ToolbarTest.java deleted file mode 100644 index f739ce96236..00000000000 --- a/java/gjt/test/ToolbarTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package gjt.test; - -import java.net.URL; -import java.awt.*; -import java.applet.Applet; -import gjt.ExclusiveImageButtonPanel; -import gjt.ImageButton; -import gjt.ImageButtonEvent; -import gjt.Orientation; -import gjt.Toolbar; -import gjt.Separator; - -/** - * A Toolbar to the north, and an ExclusiveImageButtonPanel on - * the west give this little applet its own unique charm. - * Owner is motivated.<p> - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see gjt.test.UnitTest - * @see gjt.ExclusiveImageButtonPanel - * @see gjt.ImageButton - * @see gjt.Toolbar - */ -public class ToolbarTest extends UnitTest { - public String title() { - return "Toolbar/ImageButtonPanel Test"; - } - public Panel centerPanel() { - return new ToolbarTestPanel(this); - } -} - -class ToolbarTestPanel extends Panel { - ImageButton newButton, openButton, diskButton, - printButton, cutButton, copyButton, - pasteButton; - - public ToolbarTestPanel(Applet app) { - setLayout(new BorderLayout()); - add("North", makeToolbar(app, app.getCodeBase())); - add("West", makePalette(app, app.getCodeBase())); - } - public boolean handleEvent(Event event) { - if(event instanceof ImageButtonEvent) { - ImageButtonEvent ibevent = (ImageButtonEvent)event; - - if(ibevent.isActivated()) { - if(event.target == newButton) - System.out.println("New Button Activated"); - if(event.target == openButton) - System.out.println("Open Button Activated"); - if(event.target == diskButton) - System.out.println("Disk Button Activated"); - if(event.target == printButton) - System.out.println("Print Button Activated"); - if(event.target == cutButton) - System.out.println("Cut Button Activated"); - if(event.target == copyButton) - System.out.println("Copy Button Activated"); - if(event.target == pasteButton) - System.out.println("Paste Button Activated"); - - return true; - } - } - - return super.handleEvent(event); - } - private Toolbar makeToolbar(Applet app, URL cb) { - Toolbar tb = new Toolbar(10, 0); - - newButton = tb.add(app.getImage(cb, "gifs/new.gif")); - openButton = tb.add(app.getImage(cb, "gifs/open.gif")); - diskButton = tb.add(app.getImage(cb, "gifs/disk.gif")); - - tb.addSpacer(newButton.preferredSize().width); - - printButton = tb.add(app.getImage(cb, "gifs/print.gif")); - - tb.addSpacer(newButton.preferredSize().width); - - cutButton = tb.add(app.getImage(cb, "gifs/cut.gif")); - copyButton = tb.add(app.getImage(cb, "gifs/copy.gif")); - pasteButton = tb.add(app.getImage(cb, "gifs/paste.gif")); - - return tb; - } - private Panel makePalette(Applet app, URL cb) { - ExclusiveImageButtonPanel iconPalette; - Panel iconPalettePanel = new Panel(); - - iconPalette = new ExclusiveImageButtonPanel( - Orientation.VERTICAL, - Orientation.CENTER, - Orientation.TOP, 10); - - iconPalette.add(app.getImage(cb,"gifs/ballot_box.gif")); - iconPalette.add(app.getImage(cb,"gifs/palette.gif")); - iconPalette.add(app.getImage(cb,"gifs/light_bulb1.gif")); - iconPalette.add(app.getImage(cb,"gifs/Dining.gif")); - iconPalette.add(app.getImage(cb,"gifs/scissors.gif")); - iconPalette.add(app.getImage(cb,"gifs/tricycle.gif")); - - iconPalettePanel = new Panel(); - iconPalettePanel.setLayout(new BorderLayout()); - iconPalettePanel.add ("Center", iconPalette); - iconPalettePanel.add ("East", new Separator()); - return iconPalettePanel; - } -} diff --git a/java/gjt/test/TwoDrinkersAnimationTest.java b/java/gjt/test/TwoDrinkersAnimationTest.java deleted file mode 100644 index ae4041b9eb6..00000000000 --- a/java/gjt/test/TwoDrinkersAnimationTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package gjt.test; - -import java.net.URL; -import java.applet.Applet; -import java.awt.*; -import java.awt.Panel; - -import gjt.Util; -import gjt.Orientation; -import gjt.animation.*; - -/** - * An animation playfield containing two "java drinkers", that - * both bounce off the sides of the playfield.<p> - * - * One of the java drinkers moves slow and spins fast, while - * the other java drinker moves fast and spins slow. When - * the two java drinkers collide, they both play a bump - * sequence - at different speeds.<p> - * - * @version 1.0, Apr 1 1996 - * @author David Geary - * @see gjt.test.AnimationTest - * @see gjt.animation.Playfield - * @see gjt.animation.Sprite - */ -public class TwoDrinkersAnimationTest extends UnitTest { - public String title() { - return - "TwoDrinkers Animation - Mouse Down Starts/Stops"; - } - public Panel centerPanel() { - return new TwoDrinkersAnimationTestPanel(this); - } -} - -class TwoDrinkersAnimationTestPanel extends Panel { - public TwoDrinkersAnimationTestPanel(Applet applet) { - setLayout(new BorderLayout()); - add("Center", new TwoDrinkersPlayfield(applet)); - } -} - -class TwoDrinkersPlayfield extends Playfield { - private Applet applet; - private URL cb; - private Sprite moveFastSpinSlow, moveSlowSpinFast; - private Sequence fastSpinSequence, - slowSpinSequence, - fastBumpSequence, - slowBumpSequence; - - public TwoDrinkersPlayfield(Applet applet) { - this.applet = applet; - cb = applet.getCodeBase(); - makeSequencesAndSprites(); - } - public void paintBackground(Graphics g) { - Image bg = applet.getImage(cb, "gifs/background.gif"); - Util.wallPaper(this, g, bg); - } - public boolean mouseDown(Event event, int x, int y) { - if(running() == true) stop (); - else start(); - return true; - } - public void spriteCollision(Sprite sprite, Sprite sprite2) { - if(moveSlowSpinFast.getSequence() != fastBumpSequence) { - sprite.reverse(); - sprite2.reverse(); - - moveSlowSpinFast.play(fastBumpSequence, 3); - moveFastSpinSlow.play(slowBumpSequence, 3); - } - } - public void edgeCollision(Sprite sprite, - Orientation orientation) { - if(orientation == Orientation.RIGHT || - orientation == Orientation.LEFT) - sprite.reverseX(); - else - sprite.reverseY(); - } - private void makeSequencesAndSprites() { - String file; - Image[] spinImages = new Image[19]; - Image[] bumpImages = new Image[6]; - Image[] volleyball = new Image[4]; - - for(int i=0; i < spinImages.length; ++i) { - file = "gifs/spin"; - - if(i < 10) file += "0" + i + ".gif"; - else file += i + ".gif"; - - spinImages[i] = applet.getImage(cb, file); - } - for(int i=0; i < bumpImages.length; ++i) { - file = "gifs/bump0" + i + ".gif"; - bumpImages[i] = applet.getImage(cb, file); - } - fastSpinSequence = new Sequence(this, spinImages); - slowSpinSequence = new Sequence(this, spinImages); - - fastBumpSequence = new Sequence(this, bumpImages); - slowBumpSequence = new Sequence(this, bumpImages); - - moveFastSpinSlow = - new Sprite(this, - slowSpinSequence, new Point(25, 75)); - - moveSlowSpinFast = - new Sprite(this, - fastSpinSequence, new Point(250,250)); - - fastSpinSequence.setAdvanceInterval(50); - slowSpinSequence.setAdvanceInterval(300); - - fastBumpSequence.setAdvanceInterval(25); - slowBumpSequence.setAdvanceInterval(200); - - moveFastSpinSlow.setMoveVector(new Point(2,3)); - moveSlowSpinFast.setMoveVector(new Point(-1,-1)); - - moveSlowSpinFast.setMoveInterval(100); - - addSprite(moveFastSpinSlow); - addSprite(moveSlowSpinFast); - } -} diff --git a/java/gjt/test/UnitTest.java b/java/gjt/test/UnitTest.java deleted file mode 100644 index 1fa262d5629..00000000000 --- a/java/gjt/test/UnitTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package gjt.test; - -import java.awt.BorderLayout; -import java.awt.Frame; -import java.awt.Panel; -import java.applet.Applet; -import gjt.*; - -/** - * An (abstract) Applet fitted with a BorderLayout that - * contains a TitledPanel in the North, and a Panel created by - * derived classes in the Center.<p> - * - * Since some Applets take awhile to load, UnitTest changes the - * cursor to a wait cursor in init(), changing it back to the - * default cursor in start(). Derived classes must be sure to - * call super.init() if they override init(); likewise for - * start().<p> - * - * Subclasses must implement: - * <dl> - * <dd>String title() - * <dd>Panel centerPanel() - * </dl> - * Subclasses should populate the Panel returned from - * centerPanel() with whatever makes sense for their unit test. - * - * @version 1.0, April 25, 1996 - * @author David Geary - * @see TitledPanel - */ -abstract public class UnitTest extends Applet { - abstract public String title(); - abstract public Panel centerPanel(); - - public void init() { - Util.getFrame(this).setCursor(Frame.WAIT_CURSOR); - Panel titledPanel = new TitledPanel(title()); - setLayout(new BorderLayout()); - add("North", titledPanel); - add("Center", centerPanel()); - } - public void start() { - Util.getFrame(this).setCursor(Frame.DEFAULT_CURSOR); - } -} diff --git a/java/java-ace.gif b/java/java-ace.gif Binary files differdeleted file mode 100644 index c3d89df46c0..00000000000 --- a/java/java-ace.gif +++ /dev/null diff --git a/java/netsvcs/Logger/DefaultLMR.java b/java/netsvcs/Logger/DefaultLMR.java deleted file mode 100644 index 19e319de015..00000000000 --- a/java/netsvcs/Logger/DefaultLMR.java +++ /dev/null @@ -1,36 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Logger - * - * = FILENAME - * DefaultLMR.java - * - * - *@author Everett Anderson - * - *************************************************/ -package netsvcs.Logger; - -import java.io.*; - -/** - * - * <p><h2>DESCRIPTION</h2> - * - * <blockquote> - * The LogMessageReceiver removes the code that handles a log message from - * the logging service acceptor. The DefaultLMR simply calls the LogRecord's - * print method. - * - * @see netsvcs.Logger.ServerLoggingAcceptor - * @see netsvcs.Logger.LogRecord - */ -class DefaultLMR implements LogMessageReceiver -{ - public void logRecord (String hostname, - LogRecord record) - { - record.print(hostname, true, System.err); - } -} diff --git a/java/netsvcs/Logger/LogMessageReceiver.java b/java/netsvcs/Logger/LogMessageReceiver.java deleted file mode 100644 index c001e06f2bd..00000000000 --- a/java/netsvcs/Logger/LogMessageReceiver.java +++ /dev/null @@ -1,33 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Logger - * - * = FILENAME - * LogMessageReceiver.java - * - *@author Everett Anderson - * - *************************************************/ -package netsvcs.Logger; - -import java.io.*; - -/** - * - * <p><h2>DESCRIPTION</h2> - * - * <blockquote> - * The LogMessageReceiver removes the code that handles a log message from - * the logging service acceptor. The DefaultLMR simply calls the LogRecord's - * print method. Other implementations of this interface can be built and - * given to the ServerLoggingAcceptor to change the result. - * - * @see netsvcs.Logger.ServerLoggingAcceptor - * @see netsvcs.Logger.LogRecord - */ -public interface LogMessageReceiver -{ - public void logRecord (String hostname, - LogRecord record); -}; diff --git a/java/netsvcs/Logger/LogRecord.java b/java/netsvcs/Logger/LogRecord.java deleted file mode 100644 index 0043c040f74..00000000000 --- a/java/netsvcs/Logger/LogRecord.java +++ /dev/null @@ -1,188 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Logger - * - * = FILENAME - * LogRecord.java - * - *@author Chris Cleeland, Everett Anderson - * - *************************************************/ -package netsvcs.Logger; - -import java.util.Date; -import java.io.DataOutputStream; -import java.io.DataInputStream; -import java.io.PrintStream; -import java.io.IOException; -import JACE.OS.*; - -/** - * - * <p><h2>DESCRIPTION</h2> - * - * <blockquote> - * Communicates logging information. Compatible with the C++ ACE - * ACE_Log_Record class. - * - */ -public class LogRecord -{ - final public int MAXLOGMSGLEN = 4 * 1024; - - private int type_; - private int length_; - private long msec_; - private int pid_; - private byte[] msgData_; - private final static int numIntMembers = 5; - private final static int sizeofIntInBytes = 4; - - /** - * Create a default instance. - */ - public LogRecord() - { - type(0); - timeStamp((int)new Date().getTime()); - length(0); - pid(0); - } - - /** - * Create a LogRecord. This is the designated initializer. - * @param priority a numeric specification of the priority (ascending) - * @param milliseconds time attached to the log entry in Unix <pre>time_t</pre> format - * @param pid the process ID; not currently used - */ - public LogRecord(int priority, - long milliseconds, - int pid) - { - type(priority); - timeStamp(milliseconds); - length(0); - pid(pid); - } - - /** - * Conversion to string. Only includes the <pre>msgData_</pre> member. - */ - public String toString() - { - return new String(msgData_); - } - - /** - * Place a textual representation of the record on a PrintStream. - * @param hostname name of the host generating this record - * @param verbose if <b>true</b>, print information in the form, (give example) - * @param ps A PrintStream instance to which the output should go. - * @see PrintStream,String - */ - public void print(String hostname, - boolean verbose, - PrintStream ps) - { - String toprint; - if (verbose) - { - Date now = new Date(this.timeStamp()); - - /* 01234567890123456789012345 */ - /* Wed Oct 18 14:25:36 1989n0 */ - toprint = now.toString().substring(4) + "@" - + hostname + "@" + pid_ + "@" + type_ + "@" - + this.toString(); - } - else - { - toprint = this.toString(); - } - ps.println(toprint); - } - - /** - * Streaming methods - */ - public void streamInFrom(DataInputStream dis) throws IOException - { - // Order here must match layout order in the C++ class. - // This, of course, is VERY fragile, and ought not be used as - // a model for anything except how NOT to do anything. - length(dis.readInt()); - type(dis.readInt()); - this.timeStamp((long)dis.readInt() * 1000); - - // Skip smaller time resolution info since we're lucky if Java's - // timer can handle more than millisecond precision, anyway - dis.skipBytes(4); - - pid(dis.readInt()); - - // Does readFully() allocate space for the buffer? Either - // way, we won't have memory leaks :-) - int dataLength = (int) (length_ - numIntMembers * sizeofIntInBytes); - - msgData_ = new byte[dataLength]; - dis.readFully(msgData_, 0, dataLength); - } - - public void streamOutTo(DataOutputStream dos) throws IOException - { - dos.writeInt(length()); - dos.writeInt(type()); - dos.writeInt((int)(this.msec_ / 1000)); - dos.writeInt(0); - dos.writeInt(pid()); - - dos.write(msgData_); - } - - /** - * Accessor methods - */ - public int type() { return type_; } - public void type(int t) { type_ = t; } - - public int length() { return length_; } - public void length(int l) { length_ = l; } - private void setLen(int msgLen) - { length(msgLen + numIntMembers * sizeofIntInBytes); } - - public long timeStamp() { return this.msec_; } - public void timeStamp(long msec){ this.msec_ = msec; } - - public int pid() { return pid_; } - public void pid(int p) { pid_ = p; } - - public byte[] msgData() { return msgData_; } - public void msgData(byte[] m) - { - int size = m.length; - - if (size > MAXLOGMSGLEN) - size = MAXLOGMSGLEN; - - this.msgData_ = new byte[size]; - - System.arraycopy(m, 0, msgData_, 0, size); - - setLen(size); - } - - public void msgData(String m) - { - byte temp[] = m.getBytes(); - if (temp.length > MAXLOGMSGLEN) { - this.msgData_ = new byte[MAXLOGMSGLEN]; - - System.arraycopy(temp, 0, msgData_, 0, MAXLOGMSGLEN); - } else - this.msgData_ = temp; - - setLen(msgData_.length); - } -}; - diff --git a/java/netsvcs/Logger/Makefile b/java/netsvcs/Logger/Makefile deleted file mode 100644 index a15f673eba0..00000000000 --- a/java/netsvcs/Logger/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -# $Id$ - -.SUFFIXES: .java .class - -JACE_WRAPPER = $(ACE_ROOT)/java - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - -files = LogMessageReceiver.java \ - DefaultLMR.java \ - LogRecord.java \ - ServerLoggingAcceptor.java \ - ServerLoggingHandler.java - -packages = netsvcs \ - netsvcs.Logger - -realclean: - /bin/rm -rf ${JACE_WRAPPER}/classes/netsvcs/Logger - diff --git a/java/netsvcs/Logger/ServerLoggingAcceptor.java b/java/netsvcs/Logger/ServerLoggingAcceptor.java deleted file mode 100644 index d5d4ae5220d..00000000000 --- a/java/netsvcs/Logger/ServerLoggingAcceptor.java +++ /dev/null @@ -1,171 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Logger - * - * = FILENAME - * ServerLoggingAcceptor.java - * - *@author Chris Cleeland, Everett Anderson - * - *************************************************/ -package netsvcs.Logger; - -import JACE.SOCK_SAP.*; -import JACE.Connection.*; -import JACE.OS.*; -import java.io.*; -import java.net.*; -import JACE.Misc.*; - -/** - * - * <p><h2>DESCRIPTION</h2> - * - * <blockquote> - * Acceptor: Listens on a specified port and launches ServerLoggingHandlers - * in response to requests. A LogMessageReceiver can be specified on the - * command line to change the way the logging service processes messages. - * - * @see netsvcs.Logger.ServerLoggingHandler, netsvcs.Logger.LogMessageReceiver - */ -public class ServerLoggingAcceptor extends Acceptor implements Runnable -{ - /** Main function to bootstrap the process - * - * Command line arguments: - * - * -p <port> Select a port for listening for requests - * -r <class name> Specify a LogMessageReceiver (make sure it's a full class name) - * - */ - public static void main (String [] args) - { - ServerLoggingAcceptor sla = new ServerLoggingAcceptor(); - - sla.init(args); - } - - /** - * Receives the command line and launches its own thread - */ - public int init (String [] args) - { - this.parseArgs(args); - - // If the user didn't specify a LogMessageReceiver, use the default - // (which just calls a print method on LogMessage) - if (this.receiver_ == null) - this.receiver_ = new DefaultLMR(); - - new Thread (this).start(); - return 0; - } - - /** - * Specify what LogMessageReceiver to use - */ - public void setLMR(LogMessageReceiver receiver) - { - this.receiver_ = receiver; - } - - /** - * Accessor for the LogMessageReceiver - */ - public LogMessageReceiver getLMR () - { - return this.receiver_; - } - - /** - * Create a new ServerLoggingHandler - */ - protected SvcHandler makeSvcHandler () - throws InstantiationException, IllegalAccessException - { - return new netsvcs.Logger.ServerLoggingHandler (this.receiver_); - } - - /** - * Run forever accepting new connections - */ - public void run () - { - try { - - this.open (this.port_); - while (true) - this.accept(); - - } catch (SocketException e) - { - ACE.ERROR ("Socket Exception: " + e); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - - ACE.ERROR("ServerLoggingAcceptor has exited"); - } - - /** - * Process the command line - */ - protected void parseArgs (String args[]) - { - String s; - GetOpt opt = new GetOpt (args, "p:r:"); - for (int c; (c = opt.next ()) != -1; ) - { - switch (c) - { - case 'p': - s = opt.optarg (); - this.port_ = (new Integer (s)).intValue (); - break; - case 'r': - // Load the LMR with the given name - s = new String(opt.optarg ()); - Class LMRfactory; - try { - LMRfactory = Class.forName(s); - - receiver_ = (LogMessageReceiver)LMRfactory.newInstance(); - - } catch (ClassNotFoundException e) { - ACE.ERROR("Unable to find LMR factory: " + e); - } catch (InstantiationException e) { - ACE.ERROR("Creating LMR: " + e); - } catch (IllegalAccessException e) { - ACE.ERROR("Creating LMR: " + e); - } - // Any of the above exceptions will result in just using the - // default LMR - break; - default: - ACE.ERROR ("Unknown argument: " + c); - ACE.ERROR ("Valid args: -p <port> -r <LogMessageReceiver name>"); - break; - } - } - } - - private int port_ = ACE.DEFAULT_SERVER_PORT; - private LogMessageReceiver receiver_ = null; -}; - - - - - - diff --git a/java/netsvcs/Logger/ServerLoggingHandler.java b/java/netsvcs/Logger/ServerLoggingHandler.java deleted file mode 100644 index 40f1aee8440..00000000000 --- a/java/netsvcs/Logger/ServerLoggingHandler.java +++ /dev/null @@ -1,105 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Logger - * - * = FILENAME - * ServerLoggingHandler.java - * - *@author Chris Cleeland, Everett Anderson - * - *************************************************/ -package netsvcs.Logger; - -import JACE.SOCK_SAP.*; -import JACE.Connection.*; -import JACE.OS.*; -import java.util.*; -import java.io.*; - -/** - * - * <p><h2>DESCRIPTION</h2> - * - * <blockquote> - * Created by ServerLoggingAcceptor every time a client connects. This reads - * a logging statement passes it to the LogMessageReceiver for processing. - * </blockquote> - * - * @see netsvcs.Logger.ServerLoggingAcceptor - */ -public class ServerLoggingHandler extends SvcHandler -{ - // Processes log messages - private LogMessageReceiver receiver_; - - /** - * Constructor - * - *@param receiver LogMessageReceiver that handles what to do with a message - */ - public ServerLoggingHandler (LogMessageReceiver receiver) - { - super(); - this.receiver_ = receiver; - } - - /** - * Start this handler in its own thread - */ - public int open(Object obj) - { - new Thread (this).start(); - return 0; - } - - /** - * Accessor: get the host name of the connected client - */ - protected String hostName () - { - return new String(this.peer().socket().getInetAddress().getHostName()); - } - - /** - * Receive input from the client, and send it to the LMR. This is the - * main loop for this thread. - */ - public void run() - { - DataInputStream dis = new DataInputStream(this.peer().inputStream()); - - for (;;) - { - // Messages arrive in the ACE.LogRecord format - // - // Hey! We need exception catching in here too! - try - { - // Reconstitute a log message from the wire - LogRecord rec = new LogRecord(); - - rec.streamInFrom(dis); - - // Give the record to the log processor - this.receiver_.logRecord(this.hostName(), - rec); - } - catch (EOFException eof) - { - try { - this.stream_.close(); - } catch (IOException n) { } - - return; - } - catch (IOException ioe) - { - ACE.ERROR(Thread.currentThread().getName() - + ": " - + ioe); - } - } - } -}; - diff --git a/java/netsvcs/Naming/Makefile b/java/netsvcs/Naming/Makefile deleted file mode 100644 index af49d9061d8..00000000000 --- a/java/netsvcs/Naming/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -# Makefile -# $Id$ - -.SUFFIXES: .java .class - -JACE_WRAPPER = $(WRAPPER_ROOT)/java - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - -files = NameAcceptor.java \ - NameHandler.java \ - NameRequest.java \ - NameReply.java \ - NameProxy.java \ - -packages = netsvcs \ - netsvcs.Naming - -realclean: - /bin/rm -rf ${JACE_WRAPPER}/classes/netsvcs/Naming - diff --git a/java/netsvcs/Naming/NameAcceptor.java b/java/netsvcs/Naming/NameAcceptor.java deleted file mode 100644 index f704504ee3c..00000000000 --- a/java/netsvcs/Naming/NameAcceptor.java +++ /dev/null @@ -1,306 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Naming - * - * = FILENAME - * NameAcceptor.java - * - * Listens on the specified port (command line option) and launches - * NameHandlers when connections are made. Each NameHandler runs in - * its own thread. - * - * The hash table for the mapping and a timer queue are created here. - * Periodically the mapping is written out to a file. - * - * A small main program is included to start things off. If the - * data file exists, it is read into memory. Currently the service - * stores the entire mapping in memory at all times. The mapping is - * dumped to a file at regular intervals. - * - *@see netsvcs.Naming.NameHandler - * - *@author Everett Anderson - * - *************************************************/ -package netsvcs.Naming; - -import java.io.*; -import java.net.*; -import java.util.*; -import JACE.OS.*; -import JACE.Misc.*; -import JACE.Connection.*; -import JACE.Reactor.*; -import JACE.ASX.TimeValue; - -public class NameAcceptor extends Acceptor implements Runnable -{ - /** - * Constructor - */ - public NameAcceptor () - { - super(); - - // Create the hash table and timer queue - this.mapping_ = new Hashtable(); - this.tq_ = new TimerQueue(true); - } - - /** - * Simple main program. Command line options are - * described under parseArgs. - */ - public static void main (String [] args) - { - // Simple main program to get things rolling - NameAcceptor na = new NameAcceptor(); - - na.init(args); - } - - - /** - * Close the socket when shutting down - */ - public int fini () - { - try - { - this.done_ = true; - this.sockAcceptor_.close(); - } - catch (IOException e) - { - ACE.ERROR("" + e); - return -1; - } - - return 0; - } - - /** - * Stops accepting when suspended - */ - public int suspend() - { - this.suspended_ = true; - return 0; - } - - /** - * Resumes accepting - */ - public int resume() - { - this.suspended_ = false; - return 0; - } - - - /** - * Runs this instance in its own thread - */ - public int init (String [] args) - { - // Parse arguments - this.parseArgs (args); - - System.out.println("Starting naming service on port: " + this.port_); - - // Run in own thread of control so that we don't block the caller - new Thread (this).start(); - - return 0; - } - - /** - * - * Main loop: launches NameHandlers in separate threads whenever a - * connection request is made - */ - public void run () - { - // Load the hash table from disk - this.loadTable(); - - // Schedule to write out the memory copy of the hash table at regular - // intervals - this.tq_.scheduleTimer(this, - null, - new TimeValue(this.updateInterval_), - new TimeValue(this.updateInterval_)); - - try - { - // Create new NameHandlers as requests come in - this.open (this.port_); - while (!this.done_) { - - if (!this.suspended_) - this.accept (); - } - } - catch (SocketException e) - { - ACE.ERROR ("Socket Exception: " + e); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - } - - /** - * Create a new NameHandler - */ - protected SvcHandler makeSvcHandler () - throws InstantiationException, IllegalAccessException - { - return new netsvcs.Naming.NameHandler (this.mapping_); - } - - /** - * Process the command line. The following options are available: - * - * -p <port> Port number for listening - * -f <filename> Name of the database file - * -t <time> Mapping write-out time interval (in seconds) - * - */ - protected void parseArgs (String args[]) - { - String s; - GetOpt opt = new GetOpt (args, "p:f:t:"); - for (int c; (c = opt.next ()) != -1; ) - { - switch (c) - { - // Specify port - case 'p': - s = opt.optarg (); - this.port_ = (new Integer (s)).intValue (); - break; - // Specify file name of the database - case 'f': - s = opt.optarg (); - this.filename_ = new String(s); - break; - // Specify time interval to write out the table - case 't': - s = opt.optarg (); - this.updateInterval_ = (new Integer (s)).intValue(); - break; - default: - ACE.ERROR ("Unknown argument: " + c); - break; - } - } - } - - /** - * Loads the hash table into memory from the specified - * file. Uses ObjectInputStream. - */ - protected void loadTable () - { - File file = new File(this.filename_); - FileInputStream fis; - ObjectInputStream ois; - - Hashtable ht = null; - - try { - - if ((file.exists()) && (file.canRead())) { - - fis = new FileInputStream (file); - - ois = new ObjectInputStream(fis); - - ht = (Hashtable)ois.readObject(); - } else - return; - } catch (ClassNotFoundException e) { - ACE.ERROR(e); - } catch (StreamCorruptedException e) { - ACE.ERROR(e); - } catch (SecurityException e) { - ACE.ERROR(e); - } catch (IOException e) { - ACE.ERROR(e); - } - - if (ht != null) - this.mapping_ = ht; - - } - - /** - * Writes the table out to the specified file. - */ - protected void saveTable () - { - FileOutputStream fos; - ObjectOutputStream oos; - - try { - - fos = new FileOutputStream(this.filename_); - oos = new ObjectOutputStream(fos); - - oos.writeObject(this.mapping_); - - oos.flush(); - - oos.close(); - - } catch (OptionalDataException e) { - ACE.ERROR(e); - } catch (NotSerializableException e) { - ACE.ERROR(e); - } catch (IOException e) { - ACE.ERROR(e); - } - } - - /** - * Call back for the TimerQueue. This calls the method to save the - * hash table. The default time out is 60 seconds. - */ - public int handleTimeout (TimeValue tv, Object obj) - { - this.saveTable(); - - return 0; - } - - // Port to listen on - private int port_ = ACE.DEFAULT_SERVER_PORT; - - // Mapping data structure - Hashtable mapping_ = null; - - // Default file name - String filename_ = "namedata.dat"; - - // How often to save the table (seconds) - int updateInterval_ = 60; - - // Calls handleTimeout at updateInterval_ intervals - TimerQueue tq_ = null; - - boolean done_ = false; - boolean suspended_ = false; - -} - diff --git a/java/netsvcs/Naming/NameHandler.java b/java/netsvcs/Naming/NameHandler.java deleted file mode 100644 index a619eab0733..00000000000 --- a/java/netsvcs/Naming/NameHandler.java +++ /dev/null @@ -1,521 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Naming - * - * = FILENAME - * NameHandler.java - * - * An instance of this class is created in a separate thread for each connection - * request received by the NameAcceptor. All interaction between the - * client's requests and the database are handled here. - * - * In general, the user binds a name to a (value, type) pair. The type is just - * treated as just another String (in the C++ version the name and value are - * arrays of 16 bit data types and the type is an array of 8 bit chars). - * - * For this to work in the hash table scheme, the type and value are wrapped in - * a ValueType class defined at the end of this file. - * - * This is compatible with the C++ ACE remote name service. - * - *@see netsvcs.Naming.NameAcceptor - *@see netsvcs.Naming.NameRequest - *@see netsvcs.Naming.NameReply - * - *@author Everett Anderson - * - *************************************************/ -package netsvcs.Naming; - -import java.io.*; -import java.util.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.Reactor.*; -import JACE.SOCK_SAP.*; - -public class NameHandler extends SvcHandler -{ - /** - * Constructor - * - * @param mapping Hash table created in NameAcceptor - */ - public NameHandler (Hashtable mapping) - { - super(); - - this.mapping_ = mapping; - } - - /** - * Starts this handler in its own thread - * - */ - public int open (Object obj) - { - new Thread (this).start (); - return 0; - } - - /** - * Main loop that this thread executes. Waits for connection requests and - * creates a NameHandler thread for each. - * - */ - public void run () - { - ACE.DEBUG("NameHandler instance running"); - - // Can't assume the SOCKStream uses DataInputStream, so put one - // over its OutputStream - DataInputStream dis = new DataInputStream (this.peer().inputStream()); - - // The NameRequest is the how all requests come in to the naming service. - NameRequest nameRequest = new NameRequest(); - - // Main loop -- wait for requests - int msgLen; - try - { - while (!this.done_) - { - // Read a NameRequest from the stream - nameRequest.streamInFrom(dis); - - // Decide what to do based on the request type - this.dispatch(nameRequest); - - } - } - catch (NullPointerException e) - { - ACE.ERROR ("Connection reset by peer"); - } - catch (EOFException e) - { - /* The client has shut down the connection */ - - } - catch (IOException e) - { - ACE.ERROR (e); - } - finally - { - try - { - this.peer ().close (); - } - catch (IOException e) - { - } - } - } - - - /** - * - * This is the point at which a request is sent to the various methods - * that fulfill it. Switches on the request type -- bind, rebind, resolve, - * etc. - * - *@param nameRequest The request to fill - */ - void dispatch(NameRequest nameRequest) throws IOException - { - - // Call the various other member functions based on the - // message type of the request -- bind, rebind, etc. - switch (nameRequest.requestType()) - { - case NameRequest.BIND: - this.bind(nameRequest, false); - break; - case NameRequest.REBIND: - this.bind(nameRequest, true); - break; - case NameRequest.RESOLVE: - this.resolve(nameRequest); - break; - case NameRequest.UNBIND: - this.unbind(nameRequest); - break; - case NameRequest.LIST_NAMES: - this.listByName(nameRequest.name(), false); - break; - case NameRequest.LIST_VALUES: - this.listByValue(nameRequest.name(), false); - break; - case NameRequest.LIST_TYPES: - this.listByType(nameRequest.name(), false); - break; - case NameRequest.LIST_NAME_ENTRIES: - this.listByName(nameRequest.name(), true); - break; - case NameRequest.LIST_VALUE_ENTRIES: - this.listByValue(nameRequest.name(), true); - break; - case NameRequest.LIST_TYPE_ENTRIES: - this.listByType(nameRequest.name(), true); - break; - default: - System.err.println("unknown type"); - - ACE.ERROR("Unknown type: " + nameRequest.requestType()); - - // Send a failure message. This will only work if the other - // side is expecting something like a NameReply rather than - // a NameRequest. It would've been better to have everything - // use NameRequests to avoid this kind of thing. - NameReply reply = new NameReply(NameReply.FAILURE, 0); - reply.streamOutTo(this.peer()); - - break; - } - - } - - /** - * - * Bind a name and a (value, type) pair. All this data is given in the - * NameRequest from the client. Returns a NameReply back to the client - * with either Reply.SUCCESS or Reply.FAILURE as the type. - * - *@param request NameRequest given by the client - *@param rebind Is this a rebind or not? - */ - void bind (NameRequest request, boolean rebind) throws IOException - { - // The hash table entries consists of (String name, ValueType data) pairs, so - // create the appropriate ValueType - ValueType vt = new ValueType(request.type(), - request.value()); - - // Reply to tell sender of success or failure - NameReply reply = new NameReply(); - - // If it's a rebind request, overwrite the old entry. If the key doesn't - // exist, add it. If it does exist and it's not a bind request, return - // a failure code via a NameReply. - if ((rebind) || (!this.mapping_.containsKey(request.name()))) { - - System.err.println("Binding: " + request.name() + " and " + vt.value_); - - // Add/Update the entry in the hash table - this.mapping_.put(request.name(), vt); - - // Set the reply code to success - reply.type(NameReply.SUCCESS); - - } else { - - ACE.DEBUG("Key " + request.name() + " already exists"); - - // Set reply code to failure - reply.type(NameReply.FAILURE); - - // reply error code unused as far as I know - } - - reply.streamOutTo(this.peer()); - } - - /** - * Given a name, this looks up and returns the type and value. This is - * done by sending back a full NameRequest with the correct info. If - * there is a problem, an "empty" NameRequest is returned -- it has no - * name, type, or value fields. - * - *@param request NameRequest sent by the client (has the name to lookup) - */ - void resolve (NameRequest request) throws IOException - { - // A NameRequest is also used in response - NameRequest result; - - // Wrap a DataOutputStream around the socket's output stream - // (the socket should already have at least a BufferedOutputStream) - DataOutputStream dos = new DataOutputStream(this.peer().outputStream()); - - // If the requested name is in the hash table, return the data - if (this.mapping_.containsKey(request.name())) { - - // Get the data pair based on the name - ValueType vt = (ValueType)this.mapping_.get(request.name()); - - ACE.DEBUG("Good resolve: " + vt.value_); - - // Fill the reply structure - result = new NameRequest(NameRequest.RESOLVE, - null, - vt.value_, - vt.type_, - null); - - } else { - - // Otherwise return a null response - result = new NameRequest(NameRequest.RESOLVE, - null, - null, - null, - null); - - } - - // Send the result to the socket - // result.streamOutTo(dos); - - result.streamOutTo(this.peer()); - - } - - /** - * - * Given a name, remove its entry in the mapping. Returns a NameReply - * to the client with NameReply.SUCCESS or NameReply.FAILURE. - * - *@param request NameRequest from the client (has the name to remove) - */ - void unbind (NameRequest request) throws IOException - { - NameReply reply = new NameReply(); - - // If the given key isn't in the table, return an error - // Otherwise remove it. Uses a NameReply to respond. - if (!this.mapping_.containsKey(request.name())) - reply.type(NameReply.FAILURE); - else { - this.mapping_.remove(request.name()); - reply.type(NameReply.SUCCESS); - } - - // Send the reply out to the socket - reply.streamOutTo(this.peer()); - } - - /** - * - * Given a pattern string (given in NameRequest's name field), this - * finds all the entries in the mapping which have a name that begins with - * the string. Each one is sent back separately via a NameRequest, and this - * sequence is followed by a blank NameRequest. - * - *@param pattern Pattern to find (what result names should begin with) - *@param completeLookup Should the value and type be returned as well? - */ - void listByName (String pattern, boolean completeLookup) throws IOException - { - // Get a listing of all the keys in the hash table - Enumeration enum = this.mapping_.keys(); - - // References used in the loop - String name; - ValueType vt; - - // A NameRequest is used to return each item corresponding to the pattern. - NameRequest result = new NameRequest((completeLookup ? NameRequest.LIST_NAMES : - NameRequest.LIST_NAME_ENTRIES), - null, - null, - null, - null); - - // Keep ourselves safe from null pointer exceptions - if (pattern == null) - pattern = new String(""); - - // Scan through all the elements - while (enum.hasMoreElements()) { - - // Get a key - name = (String)enum.nextElement(); - - // Does it fit the pattern? - if (name.startsWith(pattern)) { - - // Set the result name - result.name(name); - - // Only make another hash table request if the user - // wants all the data - if (completeLookup) { - - // Get data from the hash table - vt = (ValueType)mapping_.get(name); - - // Set the rest of the data - result.type(vt.type_); - result.value(vt.value_); - } - - // Send it to the socket - result.streamOutTo(this.peer()); - } - } - - // Send final null message - result.name(null); - result.type(null); - result.value(null); - result.requestType(NameRequest.MAX_ENUM); - result.streamOutTo(this.peer()); - } - - /** - * - * Given a pattern string (given in NameRequest's name field), this - * finds all the entries in the mapping which have a type that begins with - * the string. Each one is sent back separately via a NameRequest, and this - * sequence is followed by a blank NameRequest. - * - *@param pattern Pattern to find (what result types should begin with) - *@param completeLookup Should the value be returned as well? This is only - * used to decide between LIST_TYPES and LIST_TYPE_ENTRIES - * since we might as well send back both if we look them up - * together. - */ - void listByType (String pattern, boolean completeLookup) throws IOException - { - // Get a listing of all the keys in the hash table - Enumeration enum = this.mapping_.keys(); - - // References used in the loop - String name; - ValueType vt; - - // A NameRequest is used to return each item corresponding to the pattern. - NameRequest result = new NameRequest((completeLookup ? NameRequest.LIST_TYPES : - NameRequest.LIST_TYPE_ENTRIES), - null, - null, - null, - null); - // Keep ourselves safe from null pointer exceptions - if (pattern == null) - pattern = new String(""); - - // Scan through all the elements - while (enum.hasMoreElements()) { - - // Get a key - name = (String)enum.nextElement(); - - // Have to get all the data for this entry to compare - vt = (ValueType)mapping_.get(name); - - // Does it fit the pattern? - if (vt.type_ != null) - if (vt.type_.startsWith(pattern)) { - - // Set the result values - result.name(name); - result.type(vt.type_); - result.value(vt.value_); - - // Send it out to the socket - result.streamOutTo(this.peer()); - } - } - - // Send final null message - result.name(null); - result.type(null); - result.value(null); - result.requestType(NameRequest.MAX_ENUM); - result.streamOutTo(this.peer()); - } - /** - * - * Given a pattern string (given in NameRequest's name field), this - * finds all the entries in the mapping which have a value that begins with - * the string. Each one is sent back separately via a NameRequest, and this - * sequence is followed by a blank NameRequest. - * - *@param pattern Pattern to find (what result values should begin with) - *@param completeLookup Should the type be returned as well? This is only - * used to decide between LIST_VALUES and LIST_VALUE_ENTRIES - * since we might as well send back both if we look them up - * together. - */ - - void listByValue (String pattern, boolean completeLookup) throws IOException - { - // Get a listing of all the keys in the hash table - Enumeration enum = this.mapping_.keys(); - - // References used in the loop - String name; - ValueType vt; - - // A NameRequest is used to return each item corresponding to the pattern. - NameRequest result = new NameRequest((completeLookup ? NameRequest.LIST_VALUES : - NameRequest.LIST_VALUE_ENTRIES), - null, - null, - null, - null); - // Keep ourselves safe from null pointer exceptions - if (pattern == null) - pattern = new String(""); - - // Scan through all the elements - while (enum.hasMoreElements()) { - - // Get a key - name = (String)enum.nextElement(); - - // Have to get all the data for this entry to compare - vt = (ValueType)mapping_.get(name); - - // Does it fit the pattern? - if (vt.value_ != null) - if (vt.value_.startsWith(pattern)) { - - // Set the result values - result.name(name); - result.type(vt.type_); - result.value(vt.value_); - - // Send it out to the socket - result.streamOutTo(this.peer()); - } - } - - // Send final null message - result.name(null); - result.type(null); - result.value(null); - result.requestType(NameRequest.MAX_ENUM); - result.streamOutTo(this.peer()); - } - - boolean done_ = false; - - - // References to the hash table and the timer queue - Hashtable mapping_; -} - - -/** - * A simple wrapper to keep the type and value together in - * the hash table. - */ -class ValueType implements Serializable -{ - /** - * Constructor - * - *@param type Type string to include - *@param value Value string to include - */ - ValueType(String type, String value) - { this.type_ = type; this.value_ = value; } - - public String type_; - public String value_; -} - diff --git a/java/netsvcs/Naming/NameProxy.java b/java/netsvcs/Naming/NameProxy.java deleted file mode 100644 index 249f745f5ce..00000000000 --- a/java/netsvcs/Naming/NameProxy.java +++ /dev/null @@ -1,351 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Naming - * - * = FILENAME - * NameProxy.java - * - * This is a proxy which clients can use to interact with the naming service. They - * open a SOCKStream to the service, and can then call simple bind and resolve - * methods. - * - *@see netsvcs.Naming.NameAcceptor - *@see netsvcs.Naming.NameHandler - * - *@author Everett Anderson - * - *************************************************/ -package netsvcs.Naming; - -import java.io.*; -import java.net.*; -import java.util.*; -import JACE.OS.*; -import JACE.SOCK_SAP.*; - -public class NameProxy -{ - /** - * Constructor - * - *@param socket A SOCKStream already connected to the naming service - */ - public NameProxy(SOCKStream socket) - { - this.socket_ = socket; - } - - /** - * Attempt to bind the given data pair - * @param name Name/key - * @param value Value to bind - * - * @return True iff bind is successful - */ - public boolean bind(String name, String value) throws IOException - { - return this.bind(name, value, null, false); - } - - /** - * Attempt to bind the given data triplet - * @param name Name/key - * @param value Value to bind - * @param type Type to bind (another string) - * - * @return True iff the bind was successful - */ - public boolean bind(String name, String value, String type) throws IOException - { - return this.bind(name, value, type, false); - } - - /** - * The most generic of the bind methods. Allows factoring out of common code. Not public. - */ - boolean bind (String name, String value, String type, boolean rebind) throws IOException - { - // Create a new NameRequest with the desired info - NameRequest request = new NameRequest(rebind ? NameRequest.REBIND : NameRequest.BIND, - name, - value, - type, - null); - - // Send it to the naming service - request.streamOutTo(this.socket_); - - // Create a reply - NameReply reply = new NameReply(); - - // Get the status of the bind from the naming service - reply.streamInFrom(this.socket_); - - // Return true on success - return (reply.type() == NameReply.SUCCESS ? true : false); - } - - /** - * Rebind a name and a value - * @param name Name/key - * @param value Bound value - * - * @return True if the rebind was successful - */ - public boolean rebind (String name, String value) throws IOException - { - return this.bind(name, value, null, true); - } - - /** - * Rebind a name, value, and type - * @param name Name/key - * @param value Bound value - * @param type Bound type - * - * @return True if rebind was successful - */ - public boolean rebind (String name, String value, String type) throws IOException - { - return this.bind(name, value, type, true); - } - /** - * Look up information bound to the given key/name. - * - * @param name Name/key - * - * @return Vector with three elements: - * 0 Name/key - * 1 Value - * 2 Type - */ - public Vector resolve (String name) throws IOException - { - // Create a new NameRequest with the name & request type - NameRequest request = new NameRequest(NameRequest.RESOLVE, - name, - null, - null, - null); - - // Send it to the naming service - request.streamOutTo(this.socket_); - - // Get a response (hopefully with the value and type) - request.streamInFrom(this.socket_); - - // Dump the result into a vector - Vector result = new Vector(); - - result.addElement(request.name()); - result.addElement(request.value()); - result.addElement(request.type()); - - // Cut it down to the size we need - result.trimToSize(); - - return result; - } - - /** - * Remove the entry in the mapping corresponding to the given name/key. - * - * @param name Name/key - * - * @return True if the unbind was successful - */ - public boolean unbind (String name) throws IOException - { - NameRequest request = new NameRequest(NameRequest.UNBIND, - name, - null, - null, - null); - // Send the request to the naming service - request.streamOutTo(this.socket_); - - NameReply reply = new NameReply(); - - // Get reply - reply.streamInFrom(this.socket_); - - return (reply.type() == NameReply.SUCCESS ? true : false); - } - - /** - * Return a vector that's a list of names (Strings) that begin with - * the given pattern - * @param pattern Search pattern - * @return Vector List of names - */ - public Vector listNames (String pattern) throws IOException - { - return this.requestSimpleList(pattern, NameRequest.LIST_NAMES); - } - - /** - * Return a vector that's a list of types (Strings) that begin with - * the given pattern - * @param pattern Search pattern - * @return Vector List of types - */ - public Vector listTypes (String pattern) throws IOException - { - return this.requestSimpleList(pattern, NameRequest.LIST_TYPES); - } - - /** - * Return a vector that's a list of values (Strings) that begin with - * the given pattern - * @param pattern Search pattern - * @return Vector List of values - */ - public Vector listValues (String pattern) throws IOException - { - return this.requestSimpleList(pattern, NameRequest.LIST_VALUES); - } - - /** - * Non-public generic list gathering method - */ - Vector requestSimpleList (String pattern, int type) throws IOException - { - // Make request for a list of the given type - NameRequest request = new NameRequest(type, - pattern, - null, - null, - null); - request.streamOutTo(this.socket_); - - // Allocate and reuse the DIS here rather than each time we call - // streamInFrom - DataInputStream dis = new DataInputStream(this.socket_.inputStream()); - - request.streamInFrom(dis); - Vector result = new Vector(); - - // Add elements until there's a null message with the MAX_ENUM - // request type - while (request.requestType() != NameRequest.MAX_ENUM) { - if (type == NameRequest.LIST_NAMES) - result.addElement(new String(request.name())); - else - if (type == NameRequest.LIST_VALUES) - result.addElement(new String(request.value())); - else - result.addElement(new String(request.type())); - - request.streamInFrom(dis); - } - - // Adjust the vector to the minimal size - result.trimToSize(); - - return result; - } - - /** - * Get a vector with the entire data set for entries whose name begins with - * the given pattern. Each element in the vector is another vector - * with the following layout: - * 0 Name/key - * 1 Value - * 2 Type - * - * @param pattern Search pattern - * @return Vector of vectors - */ - public Vector listNameEntries (String pattern) throws IOException - { - return this.requestComplexList(pattern, NameRequest.LIST_NAME_ENTRIES); - } - - /** - * Get a vector with the entire data set for entries whose value begins with - * the given pattern. Each element in the vector is another vector - * with the following layout: - * 0 Name/key - * 1 Value - * 2 Type - * - * @param pattern Search pattern - * @return Vector of vectors - */ - public Vector listValueEntries (String pattern) throws IOException - { - return this.requestComplexList(pattern, NameRequest.LIST_VALUE_ENTRIES); - } - - /** - * Get a vector with the entire data set for entries whose type begins with - * the given pattern. Each element in the vector is another vector - * with the following layout: - * 0 Name/key - * 1 Value - * 2 Type - * - * @param pattern Search pattern - * @return Vector of vectors - */ - - public Vector listTypeEntries (String pattern) throws IOException - { - return this.requestComplexList(pattern, NameRequest.LIST_TYPE_ENTRIES); - } - - /** - * Non-public generic method for getting a a vector of vectors with the - * entire data set for entries fitting the given pattern. - */ - Vector requestComplexList (String pattern, int type) throws IOException - { - // Create request with desired type - NameRequest request = new NameRequest(type, - pattern, - null, - null, - null); - // Send it to the naming service - request.streamOutTo(this.socket_); - - // Allocate the DIS here and reuse - DataInputStream dis = new DataInputStream(this.socket_.inputStream()); - - // Get the first response - request.streamInFrom(dis); - Vector result = new Vector(); - - // Loop while we don't see a null response with the MAX_ENUM request type - while (request.requestType() != NameRequest.MAX_ENUM) { - Vector entry = new Vector(); - - // Create an element in the main vector - entry.addElement(request.name()); - entry.addElement(request.value()); - entry.addElement(request.type()); - entry.trimToSize(); - - // Add it to the result - result.addElement(entry); - - // Get another NameRequest - request.streamInFrom(dis); - } - - result.trimToSize(); - - return result; - } - - // The SOCKStream used to communication with the service - SOCKStream socket_; -}; - - - - - - - diff --git a/java/netsvcs/Naming/NameReply.java b/java/netsvcs/Naming/NameReply.java deleted file mode 100644 index 52ebb111574..00000000000 --- a/java/netsvcs/Naming/NameReply.java +++ /dev/null @@ -1,145 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Naming - * - * = FILENAME - * NameReply.java - * - * Used by the naming server to give quick status messages - * to the client. This is only used to signal the success or - * failure of bind and unbind requests. The error number is - * unused (same in C++ version?). - * - *@see netsvcs.Naming.NameHandler - * - *@author Everett Anderson - * - *************************************************/ -package netsvcs.Naming; - -import java.io.*; -import java.util.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.Reactor.*; -import JACE.ASX.*; -import JACE.SOCK_SAP.*; - -public class NameReply -{ - // Success and failure constants - public final static int SUCCESS = 1; - public final static int FAILURE = 2; - - /** - * Default Constructor - */ - public NameReply () - { - this.type_ = this.SUCCESS; - this.errno_ = 0; - } - - /** - * Constructor - * - *@param type Success or failure - *@param err Error number (unused) - */ - public NameReply (int type, int err) - { - this.type_ = type; - this.errno_ = err; - } - - /** - * Length accessor - */ - int length() - { return this.length_; } - - /** - * Type accessor -- success or failure - */ - int type() - { return this.type_; } - - /** - * Error number accessor - */ - int errno() - { return this.errno_; } - - /** - * Set type - * @param type New type - */ - void type(int type) - { this.type_ = type; } - - /** - * Set error number - * @param errno New error number - */ - void errno(int errno) - { this.errno_ = errno; } - - /** - * Send this data to the given SOCKStream - * - *@param sock SOCKStream to send to - */ - public void streamOutTo (JACE.SOCK_SAP.SOCKStream sock) throws IOException - { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(bout); - - dos.writeInt(this.length_); - dos.writeInt(this.type_); - dos.writeInt(this.errno_); - - dos.flush(); - - byte[] array = bout.toByteArray(); - - sock.sendN(array, 0, array.length); - } - - /** - * Fill the fields of this instance from data in the socket - * - *@param sock SOCKStream to read from - */ - public void streamInFrom (JACE.SOCK_SAP.SOCKStream sock) throws IOException - { - DataInputStream dis = new DataInputStream(sock.inputStream()); - - this.streamInFrom(dis); - } - - /** - * Send this data to the given DataInputStream (which should be buffered) - * - *@param dis DataInputStream to use - */ - public void streamInFrom (DataInputStream dis) throws IOException - { - int length = dis.readInt(); - - if (length != this.length_) - throw new IOException("Incorrect NameReply length"); - - type_ = dis.readInt(); - errno_ = dis.readInt(); - } - - final static int length_ = 12; - - int type_; - int errno_; -} - - - - diff --git a/java/netsvcs/Naming/NameRequest.java b/java/netsvcs/Naming/NameRequest.java deleted file mode 100644 index f8a3579fa35..00000000000 --- a/java/netsvcs/Naming/NameRequest.java +++ /dev/null @@ -1,331 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Naming - * - * = FILENAME - * NameRequest.java - * - * Used by both client and naming server as detailed in - * the NameHandler. This structure transfers information - * including name, value, type, and request type. - * - *@see netsvcs.Naming.NameHandler - * - *@author Everett Anderson - * - *************************************************/ -package netsvcs.Naming; - -import java.io.*; -import java.util.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.Reactor.*; -import JACE.ASX.*; -import JACE.SOCK_SAP.*; - -public class NameRequest -{ - /** - * Different types of requests - */ - public static final int BIND = 1; - public static final int REBIND = 2; - public static final int RESOLVE = 3; - public static final int UNBIND = 4; - public static final int LIST_NAMES = 5; - public static final int LIST_VALUES = 13; - public static final int LIST_TYPES = 21; - public static final int LIST_NAME_ENTRIES = 6; - public static final int LIST_VALUE_ENTRIES = 14; - public static final int LIST_TYPE_ENTRIES = 22; - public static final int MAX_ENUM = 11; - - /** - * Default constructor - */ - public NameRequest () - { - this.name_ = this.value_ = this.type_ = null; - this.length_ = 32; - } - - /** - * Constructor - * - * @param requestType Type of request this is (BIND, REBIND, etc) - * @param name Key to bind - * @param value Value to bind - * @param type Type to couple with the value - * @param timeout Timer information (not really used in JACE yet) - */ - public NameRequest(int requestType, - String name, - String value, - String type, - TimeValue timeout) - { - this.requestType_ = requestType; - - if (timeout == null) { - - this.blockForever_ = 1; - this.secTimeout_ = 0; - this.usecTimeout_ = 0; - } else { - - this.blockForever_ = 0; - this.secTimeout_ = (int)timeout.sec(); - this.usecTimeout_ = (int)timeout.getMilliTime() * 1000; - } - - // This is necessary to make sure null pointer exceptions are - // avoided. It makes it more consistent later on - if (name == null) - this.name_ = new String(""); - else - this.name_ = new String(name); - if (value == null) - this.value_ = new String(""); - else - this.value_ = new String(value); - if (type == null) - this.type_ = new String(""); - else - this.type_ = new String(type); - - // Set the length - this.calculateLength(); - } - - /** - * Calculate the transmission length (bytes) of this structure - */ - private void calculateLength() - { - // The type is sent as an 8 bit data type (chars in the C++ version), - // but the name and value are sent as 16 bit chars (ACE_USHORT16's in C++) - - this.length_ = 34 + this.type_.length() + 2 * (this.name_.length() + - this.value_.length()); - - } - - /** - * Return the transmission length - */ - public int length() - { return this.length_; } - - /** - * Return the name/key - */ - public String name() - { return new String(this.name_); } - - /** - * Set the name/key - * @param name Name to set to - */ - public void name(String name) - { - if (name == null) - this.name_ = new String(""); - else - this.name_ = new String(name); - - this.calculateLength(); - } - - /** - * Return the value - */ - public String value() - { return new String(this.value_); } - - /** - * Set the value - * @param value New value - */ - public void value(String value) - { - if (value == null) - this.value_ = new String(""); - else - this.value_ = new String(value); - - this.calculateLength(); - } - - /** - * Return the type - */ - public String type() - { return new String(this.type_); } - - /** - * Set the type - * @param type New type - */ - public void type(String type) - { - if (type == null) - this.type_ = new String(""); - else - this.type_ = new String(type); - - this.calculateLength(); - } - - /** - * Fill the fields of this instance with data from the socket - * - *@param sock Socket to read from - */ - public void streamInFrom (JACE.SOCK_SAP.SOCKStream sock) throws IOException - { - DataInputStream dis = new DataInputStream(sock.inputStream()); - - this.streamInFrom(dis); - } - - /** - * Fill the fields of this instance from the given DataInputStream - * - *@param dis DataInputStream to read from - */ - public void streamInFrom (DataInputStream dis) throws IOException - { - // Read the length (32 bits) - length_ = dis.readInt(); - - // Read the request type - requestType_ = dis.readInt(); - - // Can we block forever to fulfill this request? (unused) - blockForever_ = dis.readInt(); - - // How long until we should time out this request? (unused) - secTimeout_ = dis.readInt(); - usecTimeout_ = dis.readInt(); - - // The sizes are in bytes, and there are two bytes per char - // (ACE_USHORT16 in C++ land) - int nameLen = dis.readInt() / 2; - int valueLen = dis.readInt() / 2; - - int typeLen = dis.readInt(); - - // Read the name -- just read chars since they're 16 bits. - // Hopefully the SOCKStream has buffered the data - char buf[] = new char[nameLen]; - for (int i = 0; i < nameLen; i++) { - buf[i] = dis.readChar(); - } - this.name_ = new String(buf); - - // Read the value - buf = new char[valueLen]; - for (int i = 0; i < valueLen; i++) - buf[i] = dis.readChar(); - this.value_ = new String(buf); - - // Read the type -- now we can use readFully since - // the type was sent as 8 bit chars - byte tbuf[] = new byte[typeLen]; - dis.readFully(tbuf); - this.type_ = new String(tbuf); - - // Skip the null char at the end - dis.skipBytes(2); - } - - /** - * Send this NameRequest out to the given SOCKStream - * - *@param sock SOCKStream to send to - */ - public void streamOutTo (JACE.SOCK_SAP.SOCKStream sock) throws IOException - { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(bout); - - dos.writeInt(length_); - dos.writeInt(requestType_); - dos.writeInt(blockForever_); - dos.writeInt(secTimeout_); - dos.writeInt(usecTimeout_); - - // Byte sizes are sent, and the name and value are stored as - // 16 bit char arrays (ACE_USHORT16 arrays in C++ version) - dos.writeInt(this.name_.length() * 2); - dos.writeInt(this.value_.length() * 2); - dos.writeInt(this.type_.length()); - - // Making sure the name_ wasn't null comes in handy - // in situations like this - dos.writeChars(this.name_); - dos.writeChars(this.value_); - dos.writeBytes(this.type_); - - // Null termination - dos.writeChar(0); - - // Send it for real - dos.flush(); - - byte[] array = bout.toByteArray(); - - sock.sendN(array, 0, array.length); - } - - /** - * Set the requestType - *@param type Type to set to - */ - public void requestType(int type) - { - this.requestType_ = type; - } - - /** - * Get requestType - */ - public int requestType() - { - return this.requestType_; - } - - /** - * Can we block forever to fulfill the request? (unused) - */ - public boolean blockForever() - { - return (this.blockForever_ != 0) ? true : false; - } - - /** - * Allowed timeout (unused) - */ - public int secTimeout() - { - return this.secTimeout_; - } - - int length_; - int requestType_; - int blockForever_; - int secTimeout_; - int usecTimeout_; - - String name_; - String value_; - String type_; -}; - - - - - - diff --git a/java/netsvcs/Time/Clerk.java b/java/netsvcs/Time/Clerk.java deleted file mode 100755 index f29e08e06f8..00000000000 --- a/java/netsvcs/Time/Clerk.java +++ /dev/null @@ -1,23 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// netsvcs.Time -// -// = FILENAME -// Clerk.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package netsvcs.Time; - -// Test driver for the time server clerk -public class Clerk -{ - public static void main (String [] args) - { - TSClerkProcessor clerk = new TSClerkProcessor (); - clerk.init (args); - } -} diff --git a/java/netsvcs/Time/Makefile b/java/netsvcs/Time/Makefile deleted file mode 100755 index 830c2646a8a..00000000000 --- a/java/netsvcs/Time/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -# $Id$ - -.SUFFIXES: .java .class - -JACE_WRAPPER = $(ACE_ROOT)/java - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - -files = TSClerkProcessor.java \ - TSClerkHandler.java \ - TSRequestAcceptor.java \ - TSRequestHandler.java \ - TSServerAcceptor.java \ - TSServerHandler.java \ - Clerk.java \ - Server.java - -packages = netsvcs \ - netsvcs.Time - -realclean: - /bin/rm -rf ${JACE_WRAPPER}/classes/netsvcs/Time - diff --git a/java/netsvcs/Time/Server.java b/java/netsvcs/Time/Server.java deleted file mode 100755 index 6b44ddf8d9f..00000000000 --- a/java/netsvcs/Time/Server.java +++ /dev/null @@ -1,23 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// netsvcs.Time -// -// = FILENAME -// Server.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package netsvcs.Time; - -// Test driver for the time service server -public class Server -{ - public static void main (String [] args) - { - TSServerAcceptor server = new TSServerAcceptor (); - server.init (args); - } -} diff --git a/java/netsvcs/Time/TSClerkHandler.java b/java/netsvcs/Time/TSClerkHandler.java deleted file mode 100755 index fc89b69c45c..00000000000 --- a/java/netsvcs/Time/TSClerkHandler.java +++ /dev/null @@ -1,296 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Time - * - * = FILENAME - * TS_Clerk_Handler.java - * - *@author Prashant Jain, Everett Anderson - * - *************************************************/ -package netsvcs.Time; - -import java.io.*; -import java.util.Date; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.Reactor.*; -import JACE.ASX.TimeValue; - -/** - * <hr> - * <p><h2>SYNOPSIS</h2> - * - * <blockquote>Requests the remote time on a server at regular - * intervals.</blockquote> - * - * <p><h2>DESCRIPTION</h2> - * - * <blockquote>TSClerkHandlers are created by a TSClerkProcessor. There - * is one handler for each server that the Clerk Processor factors into - * its calculations.</blockquote> - */ -public class TSClerkHandler extends SvcHandler -{ - /** - * Constructor. TSClerkProcessor specifies the server machine and - * port, as well as the interval at which to make the query. - */ - public TSClerkHandler (String hostname, - int port, - TimerQueue tq, - int timeout, - TSClerkProcessor parent) - { - - this.hostname_ = hostname; - this.port_ = port; - this.tq_ = tq; - this.timeout_ = timeout; - - this.initialTimeout_ = timeout; - this.processor_ = parent; - - this.sendMsg_ = new String ("TIME_UPDATE_REQUEST"); - } - - /** - * Called to start this handler in a new thread. This only - * does it when the state of the handler is INITIALIZING. - */ - public int open (Object obj) - { - if (this.state_ != RECONNECTING) { - - Thread test = new Thread(this); - - new Thread (this).start (); - - } - return 0; - } - - /** - * Accessor - return the host name of the server - */ - public String hostname () - { - return this.hostname_; - } - - /** - * Accessor - return the port used to contact the server - */ - public int port () - { - return this.port_; - } - - /** - * Accessor - returns the difference between the local time and - * the remote server. - */ - public long delta () - { - return this.delta_; - } - - /** - * Called when the thread starts. Schedules itself with the - * timer queue. - */ - public void run () - { - this.timerId_ = this.tq_.scheduleTimer (this, - null, - new TimeValue (this.timeout_), - new TimeValue (this.timeout_)); - - } - - /** - * Accessor - return the state - */ - public int state() - { - return this.state_; - } - - /** - * Sets the state of the handler - */ - public void state(int newState) - { - this.state_ = newState; - } - - /** - * Provides a new time out interval (exponentially increasing) so - * that if the server doesn't respond, we don't keep trying to - * reconnect as often. Maximum value is 5 minutes. - */ - public int recalculateTimeout() - { - this.timeout_ *= 2; - - if (this.timeout_ > this.max_timeout_) - this.timeout_ = max_timeout_; - - return this.timeout_; - } - - /** - * Start the recovery from a server disconnection by closing the - * port and recalculating the timeout value. - */ - protected void errorRecovery() - { - ACE.DEBUG("Time Service failure with server " + this.hostname_); - - this.timeout_ = this.recalculateTimeout(); - - this.reschedule(); - } - - /** - * Removes this handler from the timer queue, and reschedules it - * (presumably with a new timeout value) - */ - public void reschedule() - { - this.tq_.cancelTimer(this); - - this.timerId_ = this.tq_.scheduleTimer (this, - null, - new TimeValue (this.timeout_), - new TimeValue (this.timeout_)); - } - - /** - * Called back by the timer queue. If the handler isn't connected, - * it tries to reconnect to the server. Otherwise, it requests - * the remote time. The server is said to have disconnected when - * an exception is thrown in the socket system, or the result is - * a string with length <= 0. - */ - public int handleTimeout (TimeValue tv, Object obj) - { - if (this.state_ != CONNECTED) { - - this.processor_.initiateConnection(this); - - // If still not connected - if (this.state_ != CONNECTED) { - - // used to set state to reconnecting here - this.state_ = RECONNECTING; - - // Reschedule to try again later - this.errorRecovery(); - return 0; - } - - // If connected, poll the server at the requested intervals - this.resetTimeout(); - } - - StringBuffer ack = new StringBuffer (); - int ackLen; - try - { - // Used to calculate the turn-around time - long sendTime = System.currentTimeMillis(); - - this.peer ().send(this.sendMsg_); - ackLen = this.peer ().recv (ack); - - long recvTime = System.currentTimeMillis(); - - if (ackLen <= 0) { - - this.state_ = DISCONNECTED; - return -1; - - } else { - - long delta = (new Long(ack.toString())).longValue() - recvTime; - - delta += (recvTime - sendTime) / 2; - - this.delta_ = delta; - - System.err.println("Delta: " + this.delta_); - } - - } - catch (NullPointerException e) - { - ACE.ERROR ("connection reset by peer"); - this.state_ = DISCONNECTED; - return -1; - } - catch (IOException e) - { - ACE.ERROR (e); - this.state_ = DISCONNECTED; - return -1; - } - - return 0; - } - - /** - * Resets the timer interval to be the one supplied to the - * constructor. - */ - public void resetTimeout() - { - this.timeout_ = this.initialTimeout_; - - this.reschedule(); - } - - private TSClerkProcessor processor_; - // Reference used to re-establish connections - - public static final int MAX_RETRY_TIMEOUT = 300; - // Wait at most 5 minutes before trying to reconnect - - // States - public static final int CONNECTED = 0; - public static final int DISCONNECTED = 1; - public static final int RECONNECTING = 2; - - // If there has been a failure, try reconnecting - // at least every MAX_RETRY_TIMEOUT seconds - private int max_timeout_ = MAX_RETRY_TIMEOUT; - - // State of the handler - private int state_ = DISCONNECTED; - - // Difference between the remote time and the local time. - private long delta_ = 0; - - // Name of the remote host - private String hostname_; - - // Port used for the connection - private int port_; - - // Current timer interval - private int timeout_; - - // Reference to the Clerk Processor's timer queue - private TimerQueue tq_; - - // Message to send for a time update - private String sendMsg_; - - // ID of the handler in the queue - private int timerId_; - - // Desired time interval to receive updates - private int initialTimeout_; - -} diff --git a/java/netsvcs/Time/TSClerkProcessor.java b/java/netsvcs/Time/TSClerkProcessor.java deleted file mode 100755 index d7b1773cc9e..00000000000 --- a/java/netsvcs/Time/TSClerkProcessor.java +++ /dev/null @@ -1,267 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Time - * - * = FILENAME - * TSClerkProcessor.java - * - *@author Prashant Jain, Everett Anderson - * - *************************************************/ -package netsvcs.Time; - -import java.io.*; -import java.net.*; -import java.util.*; -import JACE.OS.*; -import JACE.Misc.*; -import JACE.Connection.*; -import JACE.Reactor.*; -import JACE.ASX.TimeValue; - -/** - * - * <hr> - * <p><h2>SYNOPSIS</h2> - * - * <blockquote>Monitors a specified port (default 7989) and launches - * TSClerkHandlers when connections are made. The handlers communicate - * with servers and calculate the difference between the server time - * and local time. The Clerk Processor averages these differences - * and reports them to clients.</blockquote> - * - * <p><h2>DESCRIPTION</h2> - * - * <blockquote>This doesn't actually change the system clock, but it - * provides the average of the differences of the local and server - * times. A client could use this information to adjust the clock, or - * just use the midpoint to determine the correct network time.</blockquote> - * - */ -public class TSClerkProcessor extends Connector implements Runnable -{ - /** - * Default constructor - */ - public TSClerkProcessor () - { - this.serverArray_ = new Vector (); - - } - - /** - * Parse the command line, setup the TSRequestAcceptor, and run - * the Clerk Processor in its own thread. - */ - public int init (String [] args) - { - // Parse arguments - this.parseArgs (args); - - TSRequestAcceptor ra = new TSRequestAcceptor (this); - ra.init (args); - - // Run in own thread of control so that we don't block the caller - new Thread (this).start (); - return 0; - } - - - /** - * Makes connections to the servers, schedules itself for intervals - * to update the delta time. - */ - public void run () - { - - // Set up connections with all servers - Enumeration table = this.serverArray_.elements (); - while (table.hasMoreElements ()) - { - this.initiateConnection((TSClerkHandler)table.nextElement()); - } - - // Set up timer - this.timer_id_ = this.tq_.scheduleTimer (this, - null, - new TimeValue (this.timeout_), - new TimeValue (this.timeout_)); - } - - /** - * Makes connections to the servers. - */ - public void initiateConnection (TSClerkHandler handler) - { - this.open (handler.hostname(), handler.port()); - - try - { - // Connect to the server - this.connect (handler); - - // Set the state of the Clerk Handler so it queries the - // server at intervals. - handler.state(TSClerkHandler.CONNECTED); - - } - catch (UnknownHostException e) - { - ACE.ERROR (e); - } - catch (SocketException e) - { - ACE.ERROR ("Connection refused"); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - } - - - /** - * - * Called by the timer queue. Calls updateTime(). - */ - public int handleTimeout (TimeValue tv, Object obj) - { - return this.updateTime (); - } - - /** - * Calculates the delta time by averaging the results from - * Clerk Handler delta()'s. It only includes handlers whose - * state is currently CONNECTED. If they're not connected, it - * reschedules them to begin the error correction process of - * trying to reconnect to the server (possible synch problems?). - */ - protected int updateTime () - { - TSClerkHandler handler; - int count = 0; - long totalDeltaTime = 0; - - Enumeration table = this.serverArray_.elements (); - - while (table.hasMoreElements ()) - { - handler = (TSClerkHandler) table.nextElement (); - - if (handler.state() != TSClerkHandler.CONNECTED) { - - // Reconnecting state means we don't need to put - // it in the timer queue again - if (handler.state() == TSClerkHandler.RECONNECTING) - continue; - else - if (handler.state() == TSClerkHandler.DISCONNECTED) - handler.state(TSClerkHandler.RECONNECTING); - - handler.errorRecovery(); - continue; - } - - long delta = handler.delta(); - - ACE.DEBUG(handler.hostname() + ": " + delta); - - totalDeltaTime += delta; - count++; - } - - if (count > 0) { - - this.timeDelta_ = totalDeltaTime / count; - - ACE.DEBUG("Average deviation: " + totalDeltaTime/count); - - } else - - this.timeDelta_ = 0; - - return 0; - } - - /** - * Return the delta time. - */ - public long getDelta() - { - return this.timeDelta_; - } - - /** - * Parse the command line. Watches for -t <time> and - * -h <machine:port> switches. Must specify time - * value before host switches! - */ - protected void parseArgs (String args[]) - { - String s; - GetOpt opt = new GetOpt (args, "t:h:"); - for (int c; (c = opt.next ()) != -1; ) - { - switch (c) - { - case 't': - s = opt.optarg (); - this.timeout_ = (new Integer (s)).intValue (); - break; - case 'h': - s = opt.optarg (); - this.addNewHandler (s); - break; - default: - ACE.ERROR ("Bad command line argument: " + c); - - ACE.ERROR ("Valid arguments: -t <timeout> -h <hostname>:<port> -h ..."); - break; - } - } - } - - /** - * - * Creates a new Clerk Handler and adds it to the serverArray_ - */ - private void addNewHandler (String s) - { - StringTokenizer tokens = new StringTokenizer (s, ":"); - String hostname = tokens.nextToken (); - - int port = (new Integer (tokens.nextToken ())).intValue (); - - // Create new handler and add it to array of servers - this.serverArray_.addElement (new TSClerkHandler (hostname, - port, - this.tq_, - this.timeout_, - this)); - } - - // Vector of TSClerkHandlers, one for each server - private Vector serverArray_; - - // Default interval at which to update the time - private int timeout_ = 1000; - - // Timer queue which calls handleTimeout when the Clerk Processor - // is supposed to update the time. - private TimerQueue tq_ = new TimerQueue (true); - - // Clerk Processor ID in the timer queue - private int timer_id_; - - // Average of the differences of the local and server times. - private long timeDelta_; -} diff --git a/java/netsvcs/Time/TSRequestAcceptor.java b/java/netsvcs/Time/TSRequestAcceptor.java deleted file mode 100755 index e02b0b261ba..00000000000 --- a/java/netsvcs/Time/TSRequestAcceptor.java +++ /dev/null @@ -1,142 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Time - * - * = FILENAME - * TSRequestAcceptor.java - * - *@author Prashant Jain, Everett Anderson - * - *************************************************/ -package netsvcs.Time; - -import java.io.*; -import java.net.*; -import java.util.*; -import JACE.OS.*; -import JACE.Misc.*; -import JACE.Connection.*; -import JACE.Reactor.*; - -/** - * <hr> - * <p><h2>SYNOPSIS</h2> - * - * <blockquote>Monitors a specified port (default 7990) and launches - * TSRequestHandlers when connections are made. The handlers - * report the average deviation from the local time when input - * is received to their sockets.</blockquote> - * - * <p><h2>DESCRIPTION</h2> - * <blockquote>This is in place of the shared memory system used in C++ ACE. - * The clients need to request the correct time range from the Clerk, so - * they can do it with <a href="ACE.SOCK_SAP.SOCKStream.html#_top_"> - * <tt>sockets</tt></a>. An instance of TSRequestAcceptor is created - * and initialized in TSClerkProcessor init(). This should be the - * only place it's used.</blockquote> - * - * @see ACE.SOCK_SAP.SOCKAcceptor,ACE.netsvcs.Time.TSClerkProcessor - */ - -public class TSRequestAcceptor extends Acceptor implements Runnable -{ - /** - * Create an instance of TSRequestAcceptor. Default constructor. - */ - public TSRequestAcceptor (TSClerkProcessor parent) - { - this.parent_ = parent; - } - - /** - * - * Process command line arguments (port), and start this instance - * in its own thread. - * - */ - public int init(String [] args) - { - this.parseArgs (args); - - new Thread (this).start(); - return 0; - } - - /** - * - * Called when the thread starts. Open the port and accept - * connections. - */ - public void run () - { - try { - this.open (this.port_); - while (true) - this.accept(); - } - catch (SocketException e) - { - ACE.ERROR (e); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - - System.err.println("Stopped accepting"); - } - - /** - * - * Parse the command line. This only looks for -p <port number>. - * - */ - protected void parseArgs (String args[]) - { - String s; - GetOpt opt = new GetOpt (args, "p:"); - - for (int c; (c = opt.next ()) != -1; ) - { - switch (c) - { - case 'p': - s = opt.optarg (); - this.port_ = (new Integer (s)).intValue (); - break; - default: - ACE.ERROR("Invalid argument: " + c); - break; - } - } - } - - /** - * - * Modifies to behavior of Acceptor accept() so the TSClerkProcessor - * reference can be passed to the TSRequestHandler. - * - */ - - protected SvcHandler makeSvcHandler () - throws InstantiationException, IllegalAccessException - { - return (SvcHandler) new TSRequestHandler(parent_); - } - - // Port to monitor - private int port_ = 7990; - - // Reference to the Clerk Processor (which holds the time value) - private TSClerkProcessor parent_; -}; - diff --git a/java/netsvcs/Time/TSRequestHandler.java b/java/netsvcs/Time/TSRequestHandler.java deleted file mode 100755 index dbeded22250..00000000000 --- a/java/netsvcs/Time/TSRequestHandler.java +++ /dev/null @@ -1,106 +0,0 @@ -package netsvcs.Time; -/************************************************* - * - * = PACKAGE - * netsvcs.Time - * - * = FILENAME - * TSRequestHandler.java - * - *@author Prashant Jain, Everett Anderson - * - *************************************************/ -import java.io.*; -import java.util.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.Reactor.*; - -/** - * <hr> - * <p><h2>SYNOPSIS</h2> - * - * <blockquote>Handles giving the client the average difference between - * the local time and the server times.</blockquote> - * - * <p><h2>DESCRIPTION</h2> - * - * <blockquote>Whenever the RequestHandler receives input to the port, it - * sends the current delta (average difference time) in return as a string. - * Instances of this class are created by TSRequestAcceptor.</blockquote> - */ -public class TSRequestHandler extends SvcHandler -{ - /** - * Constructor. Takes in a reference to the Clerk Processor - * so it can call TSClerkProcessor getDelta(). - */ - public TSRequestHandler (TSClerkProcessor processor) - { - this.processor_ = processor; - } - - /** - * - * Run this in a separate thread. - */ - public int open (Object obj) - { - new Thread (this).start (); - return 0; - } - - /** - * - * Called when the thread starts. This is the main code -- whenever - * input comes to the socket, it sends out the current delta time - * as a string. - */ - public void run () - { - int msgLen; - try - { - while (true) - { - StringBuffer msg = new StringBuffer (); - - msgLen = this.peer ().recv (msg); - - if (msgLen < 0) - break; - else { - - // No matter what was sent in, send the average difference back - - String msgOut = new String("" + this.processor_.getDelta() + '\n'); - this.peer ().send (msgOut); - - } - } - } - catch (NullPointerException e) - { - ACE.ERROR ("Connection reset by peer"); - } - catch (IOException e) - { - ACE.ERROR (e); - } - finally - { - try - { - this.peer ().close (); - } - catch (IOException e) - { - ACE.ERROR (e); - } - } - } - - - // Reference to the Clerk Processor to call getDelta() - TSClerkProcessor processor_; -} diff --git a/java/netsvcs/Time/TSServerAcceptor.java b/java/netsvcs/Time/TSServerAcceptor.java deleted file mode 100755 index 2d54f7b740b..00000000000 --- a/java/netsvcs/Time/TSServerAcceptor.java +++ /dev/null @@ -1,100 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Time - * - * = FILENAME - * TS_Server_Acceptor.java - * - *@author Prashant Jain - * - *************************************************/ -package netsvcs.Time; - -import java.io.*; -import java.net.*; -import java.util.*; -import JACE.OS.*; -import JACE.Misc.*; -import JACE.Connection.*; -import JACE.Reactor.*; - -/** - * <hr> - * <p><h2>DESCRIPTION</h2> - * - * Acceptor: listens to a port and launches TSServerHandlers - * when connections are made. - * - * @see netsvcs.Time.TSServerHandler, JACE.Connection.Acceptor - */ -public class TSServerAcceptor extends Acceptor implements Runnable -{ - // Run this in its own thread - public int init (String [] args) - { - // Parse arguments - this.parseArgs (args); - - // Run in own thread of control so that we don't block the caller - new Thread (this).start (); - return 0; - } - - // Create a TSServerHandler for each client that wants to connect - public void run () - { - try - { - this.setHandlerFactory (Class.forName ("netsvcs.Time.TSServerHandler")); - this.open (this.port_); - while (true) - this.accept (); - } - catch (ClassNotFoundException e) - { - ACE.ERROR (e); - } - catch (SocketException e) - { - ACE.ERROR ("Socket Exception: " + e); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - - System.err.println("Stopped accepting"); - } - - // Process the command line - protected void parseArgs (String args[]) - { - String s; - GetOpt opt = new GetOpt (args, "p:"); - for (int c; (c = opt.next ()) != -1; ) - { - switch (c) - { - case 'p': - s = opt.optarg (); - this.port_ = (new Integer (s)).intValue (); - break; - default: - ACE.ERROR ("Unknown argument: " + c); - break; - } - } - } - - private int port_ = 7989; -} - diff --git a/java/netsvcs/Time/TSServerHandler.java b/java/netsvcs/Time/TSServerHandler.java deleted file mode 100755 index 4ee700254ed..00000000000 --- a/java/netsvcs/Time/TSServerHandler.java +++ /dev/null @@ -1,99 +0,0 @@ -/************************************************* - * - * = PACKAGE - * netsvcs.Time - * - * = FILENAME - * TS_Server_Handler.java - * - *@author Prashant Jain, Everett Anderson - * - *************************************************/ -package netsvcs.Time; - -import java.io.*; -import java.util.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.Reactor.*; - -/** - * <hr> - * <p><h2>DESCRIPTION</h2> - * - * <blockquote>Handles requests from a TSClerkHandler and sends - * back the current local time.</blockquote> - * - * @see netsvcs.Time.TSClerkHandler. netsvcs.Time.TSServerAcceptor - */ - -public class TSServerHandler extends SvcHandler -{ - // Constructor - public TSServerHandler () - { - } - - // Start this handler in its own thread - public int open (Object obj) - { - - new Thread (this).start (); - return 0; - } - - // Wait for messages from the Client and send the current local - // time back as a string. - public void run () - { - int msgLen; - try - { - while (true) - { - // Use a new one each time since recv appends - StringBuffer msg = new StringBuffer (); - - // Get the message from the client (blocks) - msgLen = this.peer ().recv (msg); - - // Just keep waiting if there's a problem - if (msgLen <= 0) - break; - - // Is the message for the right thing? - if (msg.toString().compareTo ("TIME_UPDATE_REQUEST") != 0) { - System.err.println("Unknown message: \"" + msg + '\"'); - this.peer().send("\n"); // send so other side isn't stuck - break; - } - - // Get local time - long time = System.currentTimeMillis(); - - // Send as a string - this.peer ().send ("" + time); - - ACE.DEBUG("Time: " + new Date(time)); - } - } - catch (NullPointerException e) - { - ACE.ERROR ("Connection reset by peer"); - } - catch (IOException e) - { - ACE.ERROR (e); - } - finally - { - try - { - this.peer ().close (); - } - catch (IOException e) - { - } - } - } -} diff --git a/java/src/ACE.java b/java/src/ACE.java deleted file mode 100644 index 8fa6e1823fa..00000000000 --- a/java/src/ACE.java +++ /dev/null @@ -1,164 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.OS - * - * = FILENAME - * JACE.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.OS; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - * <blockquote>Constants, utility "functions", etc.</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * Defines default constants for ACE. Many of these are used for the - * ACE tests and applications. You may want to change some of these to - * correspond to your environment. Also, routines for error handling, - * debugging and bit manipulation are included. - *</blockquote> - * - * <h2>NOTES</h2> - *<blockquote> - * This class is non-instantiable, and intended only to provide a constrained - * namespace. - *</blockquote> - */ -public abstract class ACE -{ - /** - * Default port on which a server listens for connections. - */ - public static final int DEFAULT_SERVER_PORT = 10002; - - /** - * Default name to use for a thread group. - */ - public static final String DEFAULT_THREAD_GROUP_NAME = "ace_thread_group"; - - /** - * Disable debugging. Once debugging is disabled, all ACE.DEBUG - * statements would be ignored. - */ - public static final void disableDebugging () - { - ACE.debug_ = false; - } - - /** - * Enable debugging. Once debugging is enabled, all ACE.DEBUG - * statements get printed. - */ - public static final void enableDebugging () - { - ACE.debug_ = true; - } - - /** - * Print the string representation of Java Exception. - *@param e Java exception - */ - public static final void ERROR (Exception e) - { - System.err.println (e); - } - - /** - * Print the string being passed in. - *@param s a Java String - */ - public static final void ERROR (String s) - { - System.err.println (s); - } - - /** - * Print the string being passed in. - *@param s A Java String - *@return Error value passed in - */ - public static final int ERROR_RETURN (String s, int errorVal) - { - System.err.println (s); - return errorVal; - } - - /** - * Print the string being passed in. Note the behavior will vary - * depending upon whether debugging is enabled or disabled. - *@param s a Java String - */ - public static final void DEBUG (String s) - { - if (ACE.debug_) - System.out.println (s); - } - - /** - * Flush out any data that may be buffered. - */ - public static final void FLUSH () - { - System.out.flush (); - } - - /** - * Set the bits of WORD using BITS as the mask. - *@param WORD the bits to be set. - *@param BITS the mask to use. - *@return The value obtained after setting the bits. - */ - public static final long SET_BITS (long WORD, long BITS) - { - return WORD | BITS; - } - - /** - * Clear the bits of WORD using BITS as the mask. - *@param WORD the bits to clear. - *@param BITS the mask to use. - *@return The value obtained after clearing the bits. - */ - public static final long CLR_BITS (long WORD, long BITS) - { - return WORD & ~BITS; - } - - /** - * Check if bits are enabled in WORD. - *@param WORD the bits to check. - *@param BIT the bit to check to see if it is enabled or not. - *@return true if bit is enabled, false otherwise. - */ - public static final boolean BIT_ENABLED (long WORD, long BIT) - { - return (WORD & BIT) != 0; - } - - /** - * Check if bits are disabled in WORD. - *@param WORD the bits to check. - *@param BIT the bit to check to see if it is disabled or not. - *@return true if bit is disabled, false otherwise. - */ - public static final boolean BIT_DISABLED (long WORD, long BIT) - { - return (WORD & BIT) == 0; - } - - // Debug flag (turn debugging on/off) - private static boolean debug_ = true; - - // Default private constructor to avoid instantiation - private ACE () - { - } -} - - diff --git a/java/src/AcceptStrategy.java b/java/src/AcceptStrategy.java deleted file mode 100644 index e5af43f07f5..00000000000 --- a/java/src/AcceptStrategy.java +++ /dev/null @@ -1,89 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * AcceptStrategy.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Interface for specifying a passive connection - * acceptance strategy for a - * <a href="ACE.Connection.SvcHandler.html"><tt>SvcHandler</tt></a> - * . - *</blockquote> - * - * <h2>DESCRIPTION</h2> - * - *<blockquote> - * This class provides a strategy that manages passive - * connection setup for an application, and can be extended - * to define new strategies. - *</blockquote> - * - * @see SvcHandler - * @see Acceptor - */ - -public class AcceptStrategy -{ - /** - * Create an instance of Accept Strategy. - *@param port port number where the server will listen for connections - *@exception IOException couldn't open port - */ - AcceptStrategy (int port) throws IOException - { - this.open (port); - } - - /** - * Initialize AcceptStrategy. - *@param port port number where the server will listen for connections - *@exception IOException couldn't open port - */ - public void open (int port) throws IOException - { - // Create a new SOCK_Acceptor to accept client connections - this.sockAcceptor_ = new SOCKAcceptor (port); - } - - /** - * Accept connections into the SvcHandler. Note that subclasses - * should overwrite this method to provide a different accept - * strategy. - *@param sh Svc Handler in which to accept the connection - *@exception SocketException Socket error - *@exception IOException Socket error - *@return 0 - */ - public int acceptSvcHandler (SvcHandler sh) throws - SocketException, IOException - { - // Create a new stream - SOCKStream sockStream = new SOCKStream (); - - // Block in accept. Returns when a connection shows up - this.sockAcceptor_.accept (sockStream); - - // Set the streams for the new handler - sh.setHandle (sockStream); - return 0; - } - - // Our connection acceptance factory - private SOCKAcceptor sockAcceptor_; - -} diff --git a/java/src/Acceptor.java b/java/src/Acceptor.java deleted file mode 100644 index 945f170fe38..00000000000 --- a/java/src/Acceptor.java +++ /dev/null @@ -1,216 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * Acceptor.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.SOCK_SAP.*; -import JACE.ServiceConfigurator.*; - -/** - * <hr> - * <p><h2>SYNOPSIS</h2> - * - * <blockquote>Abstract factory for creating a service handler - * (<a href="ACE.Connection.SvcHandler.html"><tt>SvcHandler</tt></a>), - * accepting into the - * <a href="ACE.Connection.SvcHandler.html"><tt>SvcHandler</tt></a>, and activating the - * <a href="ACE.Connection.SvcHandler.html"><tt>SvcHandler</tt></a>.</blockquote> - * - * <p><h2>DESCRIPTION</h2> - * - * <blockquote>Implements the basic strategy for passively establishing - * connections with applications. The <tt>Acceptor</tt> - * is a factory for <tt>SvcHandler</tt> instances, and, by default - * generates a new <tt>SvcHandler</tt> instance for each connection - * esablished.</blockquote> - * - * <p> - * - * <blockquote> The user of this class <em>must</em> provide a - * reference to a handler factory prior to calling <a - * href="#accept()"><tt>accept</tt></a>, or an exception will be - * thrown. The handler factory is identified by the meta-class for - * the <tt>SvcHandler</tt>, and is typically obtained by calling <a - * href="java.lang.Class#classForName(java.lang.String)"><tt>Class.classForName("SvcHandler")</tt></a>. - * </blockquote> - * - * <p> - * - * <blockquote> TCP is the transport mechanism used, via - * <a href="ACE.SOCK_SAP.SOCKAcceptor.html#_top_"><tt>SOCKAcceptor</tt></a>, - * <em>et.al.</em> The SvcHandler is instantiated with a concrete type - * that performs the application-specific service. </blockquote> - * - * <h2>NOTES</h2> - * - * <blockquote> This class is not directly related to the - * <tt>AcceptorStrategy</tt> class.</blockquote> - * - * - * @see java.lang.Class - * @see JACE.Connection.SvcHandler - * @see JACE.SOCK_SAP.SOCKAcceptor - */ -public class Acceptor extends ServiceObject -{ - /** - * Create an instance of Acceptor. Default constructor. Note that if - * an instance is created via this method, <tt>setHandlerFactory</tt> - * must be called prior to using <tt>accept</tt>. - * - * @see JACE.Connection.Acceptor#setHandlerFactory - */ - public Acceptor () - { - } - - /** - * Create an instance of Acceptor. - *@param handlerFactory meta-class reference used to create - * an instance of a SvcHandler when a connection is accepted - * (typically obtained by calling <tt>Class.classForName</tt>). - * - *@see java.lang.Class#forName - */ - public Acceptor (Class handlerFactory) - { - this.handlerFactory_ = handlerFactory; - } - - /** - * Set the handler factory. This is provided to aid the default - * no-arg constructor. - *@param handlerFactory meta-class reference used to create - * an instance of a SvcHandler when a connection is accepted - * (typically obtained by calling <tt>Class.forName</tt>). - * - *@see java.lang.Class#forName - */ - public void setHandlerFactory (Class handlerFactory) - { - this.handlerFactory_ = handlerFactory; - } - - /** - * Initialize the Acceptor. - *@param port TCP port number where the Acceptor will listen for connections - *@exception IOException socket level exception - */ - public void open (int port) throws IOException - { - this.sockAcceptor_ = new SOCKAcceptor (port); - } - - /** - * Template method for accepting connections. Delegates operational - * activities to the following bridge methods: - * <ul> - * <li><tt>makeSvcHandler</tt></li> - * <li><tt>acceptSvcHandler</tt></li> - * <li><tt>activateSvcHandler</tt></li> - * </ul> - * - * <p> - * - * The method first obtains a <tt>SvcHandler</tt> via - * <tt>makeSvcHandler</tt>, accepts the connection <q>into</q> the - * handler using <tt>acceptSvcHandler</tt>, and finally turns over - * control to the handler with <tt>activateSvcHandler</tt>. - * - *@exception SocketException socket level error - *@exception InstantiationException <tt>makeSvcHandler</tt> failure - *@exception IllegalAccessException <tt>makeSvcHandler</tt> failure - *@exception IOException socket level error - */ - public void accept () throws SocketException, - InstantiationException, - IllegalAccessException, - IOException - { - - // Create a Svc_Handler using the appropriate Creation_Strategy - SvcHandler sh = this.makeSvcHandler (); - - // Accept a connection into the SvcHandler using the appropriate - // Accept_Strategy - this.acceptSvcHandler (sh); - - // Activate the SvcHandler using the appropriate ActivationStrategy - this.activateSvcHandler (sh); - } - - /** - * Bridge method for creating a <tt>SvcHandler</tt>. The default is to - * create a new <SvcHandler>. However, subclasses can override this - * policy to perform <SvcHandler> creation in any way that they like - * (such as creating subclass instances of <SvcHandler>, using a - * singleton, etc.) - *@return a new instance of the SvcHandler - *@exception InstantiationException could not create new SvcHandler - *@exception IllegalAccessException no SvcHandler factory provided - */ - protected SvcHandler makeSvcHandler () - throws InstantiationException, IllegalAccessException - { - // Create a new handler for the connection - return (SvcHandler) handlerFactory_.newInstance (); - } - - /** - * Bridge method for accepting the new connection into the - * <tt>SvcHandler</tt>. The default behavior delegates the work to - * <tt>SOCKAcceptor.accept</tt>. However, subclasses can override this - * strategy. - *@param sh SvcHandler in which to accept the connection - *@return 0 - *@exception SocketException socket level error - *@exception IOException socket level error - */ - protected int acceptSvcHandler (SvcHandler sh) - throws SocketException, IOException - { - // Create a new stream - SOCKStream sockStream = new SOCKStream (); - - // Block in accept. Returns when a connection shows up - this.sockAcceptor_.accept (sockStream); - - // Set the streams for the new handler - sh.setHandle (sockStream); - return 0; - } - - /** - * Bridge method for activating a <tt>SvcHandler</tt>. The default - * behavior of this method is to activate the <tt>SvcHandler</tt> by - * calling its open() method (which allows the <tt>SvcHandler</tt> to - * define its own concurrency strategy). However, subclasses can - * override this strategy to do more sophisticated concurrency - * activations. - *@param sh SvcHandler to activate - *@return 0 - */ - protected int activateSvcHandler (SvcHandler sh) - { - sh.open (null); - return 0; - } - - // Handler class that should be instantiated when a connection is - // made with a client - private Class handlerFactory_; - - // Our connection acceptance factory - protected SOCKAcceptor sockAcceptor_; -} diff --git a/java/src/ActivateStrategy.java b/java/src/ActivateStrategy.java deleted file mode 100644 index 882203ad552..00000000000 --- a/java/src/ActivateStrategy.java +++ /dev/null @@ -1,43 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * ActivateStrategy.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - - -/** - * <hr> - *<h2>SYNOPSIS</h2> - * Bridge supporting activation strategy used by - * <a href="ACE.Connection.StrategyAcceptor.html#_top_"><tt>StrategyAcceptor</tt></a> - * - *<h2>DESCRIPTION</h2> - * Subclass and overload - * <a href="#activateSvcHandler(ACE.Connection.SvcHandler)"><tt>activateSvcHandler</tt></a> - * in order change the activation strategy. Then, submit this subclass to - * <a href="ACE.Connection.StrategyAcceptor.html#_top_"><tt>StrategyAcceptor</tt></a> - * as the activation strategy. - * - *@see StrategyAcceptor - */ -public class ActivateStrategy -{ - /** - * Activate the Svc Handler. Note that subclasses should overwrite - * this method to provide a different Activate strategy. - *@param sh Svc Handler to activate - *@return zero if success, non-zero for failure - */ - public int activateSvcHandler (SvcHandler sh) - { - sh.open (null); - return 0; - } -} diff --git a/java/src/AddServiceObjectNode.java b/java/src/AddServiceObjectNode.java deleted file mode 100644 index aa99c51ebc3..00000000000 --- a/java/src/AddServiceObjectNode.java +++ /dev/null @@ -1,54 +0,0 @@ -package JACE.ServiceConfigurator; - -import java.io.*; -import JACE.OS.*; - -class AddServiceObjectNode extends ParseNode -{ - - public AddServiceObjectNode () - { - this.locator_ = new String(); - this.params_ = new String(); - } - - /* This should be the class name, fully qualified or in the class path */ - public String locator () - { - return this.locator_; - } - - public String params () - { - return this.params_; - } - - public void params (String params) - { - this.params_ = params; - } - - public boolean suspended () - { - return this.suspended_; - } - - public void init(String name, String locator, boolean suspended) - { - super.name_ = name; - this.locator_ = locator; - this.suspended_ = suspended; - } - - public void apply () - { - ACE.DEBUG("AddServiceObjectNode apply"); - - if (JACE.ServiceConfigurator.ServiceConfig.initialize(this) == -1) - ACE.ERROR("Error adding " + this.name_); - } - - String params_; - String locator_; - boolean suspended_; -}; diff --git a/java/src/Blob.java b/java/src/Blob.java deleted file mode 100644 index 69feef248b3..00000000000 --- a/java/src/Blob.java +++ /dev/null @@ -1,94 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * Blob.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import JACE.ASX.*; -import JACE.OS.*; - -public class Blob -{ - public int open (String filename, String hostname , int port) - { - this.filename_ = filename; - this.hostname_ = hostname; - this.port_ = port; - return 0; - } - - public MessageBlock read (int length, int offset) - { - // Check if we have a valid length and a valid offset - if (length < 0 || offset < 0) - { - ACE.ERROR ("Blob::read(): Negative length or offset"); - return null; - } - - // Create a Blob Reader - BlobReader blobReader = new BlobReader (length, offset, this.filename_, this.hostname_, this.port_); - - // Receive data - MessageBlock mb = blobReader.receiveData (); - if (blobReader.bytesRead () != length) - return null; - else - return mb; - } - - public int write (MessageBlock mb, int length, int offset) - { - // Check if we have a valid length and a valid offset - if (length < 0 || offset < 0) - ACE.ERROR ("Blob::write(): Negative length or offset"); - - // Create a Blob Writer - BlobWriter blobWriter = new BlobWriter (mb, length, offset, this.filename_); - - try - { - // Connect to the server - this.connector_.open (this.hostname_, this.port_); - this.connector_.connect (blobWriter); - } - catch (UnknownHostException e) - { - ACE.ERROR (e); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - - return blobWriter.bytesWritten (); - } - - public int close () - { - return 0; - } - - String filename_; - String hostname_; - int port_; - Connector connector_ = new Connector (); -} diff --git a/java/src/BlobHandler.java b/java/src/BlobHandler.java deleted file mode 100644 index ec282bdeaa9..00000000000 --- a/java/src/BlobHandler.java +++ /dev/null @@ -1,35 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * BlobHandler.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import JACE.ASX.*; -import JACE.OS.*; - -public abstract class BlobHandler extends SvcHandler -{ - public BlobHandler (int length, int offset, String filename) - { - this.length_ = length; - this.offset_ = offset; - this.filename_ = filename; - } - - public abstract int open (Object obj); - - protected int length_ = 0; - protected int offset_ = 0; - protected String filename_ = null; -} - diff --git a/java/src/BlobReader.java b/java/src/BlobReader.java deleted file mode 100644 index 7209f3c721f..00000000000 --- a/java/src/BlobReader.java +++ /dev/null @@ -1,104 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * BlobReader.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import JACE.ASX.*; -import JACE.OS.*; - -// Reader ************************************************** - -public class BlobReader -{ - public BlobReader (int length, - int offset, - String filename, - String hostname, - int port) - { - this.length_ = length; - this.offset_= offset; - this.filename_ = filename; - this.hostname_ = hostname; - this.port_ = port; - } - - - public MessageBlock receiveData () - { - String hostname = this.hostname_; - String filename = this.filename_; - - // Check if the filename begins with a "/" and if so, remove it - // since we are concatenating a "/" to the hostname. - if (this.filename_.startsWith ("/")) - filename = this.filename_.substring (1); - - hostname = hostname + ":" + this.port_ + "/"; - // System.out.println (hostname + filename); - - // Allocate a buffer to hold the offset worth of data - byte tempBuf [] = new byte [this.offset_]; - // Allocate a buffer to hold the actual data - byte dataBuf [] = new byte [this.length_]; - - try - { - // Create a URL to fetch the file - URL url = new URL (this.protocol_ + hostname + filename); - - // Get the input stream and pipe it to a DataInputStream - DataInputStream iStream = new DataInputStream (url.openStream ()); - - // Read the offset worth of bytes - iStream.readFully (tempBuf, 0, this.offset_); - - // Read length worth of bytes - iStream.readFully (dataBuf, 0, this.length_); - } - catch (MalformedURLException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - // Cache number of bytes read - this.bytesRead_ = this.length_; - return new MessageBlock (new String (dataBuf, 0, this.length_)); - } - - public int close (long flags) - { - return 0; - } - - public int bytesRead () - { - return this.bytesRead_; - } - - private String protocol_ = "http://"; - - int length_ = 0; - int offset_= 0; - String filename_ = null; - String hostname_ = "localhost"; - int port_ = 80; - - int bytesRead_ = 0; -} - - diff --git a/java/src/BlobWriter.java b/java/src/BlobWriter.java deleted file mode 100644 index 09cc88a1f9e..00000000000 --- a/java/src/BlobWriter.java +++ /dev/null @@ -1,220 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * BlobWriter.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import JACE.ASX.*; -import JACE.OS.*; - -// Writer ************************************************** - -public class BlobWriter extends BlobHandler -{ - public BlobWriter (MessageBlock mb, - int length, - int offset, - String filename) - { - super (length, offset, filename); - this.mb_ = mb; - this.returnCode_ = -1; - - } - - /******************************* - * This constructor should be used when using the basic HTTP 1.1 - * authentication scheme - *******************************/ - public BlobWriter (MessageBlock mb, - int length, - int offset, - String filename, - String authentication) - { - super (length, offset, filename); - this.mb_ = mb; - this.returnCode_ = -1; - this.authentication_ = authentication; - } - - - public int open (Object obj) - { - if (this.sendRequest () != 0) - { - ACE.ERROR ("BlobWriter::open():sendRequest failed"); - return -1; - } - else if (this.receiveReply () != 0) - { - ACE.ERROR ("BlobWriter::open():receiveReply failed"); - return -1; - } - return 0; - } - - public int close (long flags) - { - return 0; - } - - public int bytesWritten () - { - return this.bytesWritten_;; - } - - protected int sendRequest () - { - // Check for sanity -- check if we have any data to send. - if (this.offset_+ this.length_ > this.mb_.length ()) - { - ACE.ERROR ("BlobWriter::sendRequest():Invalid offset/length"); - return -1; - } - - if (this.sendHeader () == -1) - { - ACE.ERROR ("BlobWriter::sendHeader failed."); - return -1; - } - else - if (this.sendData () == -1) - { - ACE.ERROR ("BlobWriter::sendData failed."); - return -1; - } - return 0; - } - - // Send the header - protected int sendHeader () - { - String filename = this.filename_; - // Check if the filename begins with a "/" and if it doesn't, add it - if (!this.filename_.startsWith ("/")) - filename = "/" + this.filename_; - - // Create the header, store the actual length in mesglen - String mesg = this.requestPrefix_ + " " + filename + " " + this.requestSuffix_; - - if (this.authentication_ != null) - mesg += "Authorization: Basic " + JACE.Connection.HTTPHelper.EncodeBase64(this.authentication_) + '\n'; - - mesg += "Content-length: " + this.length_ + "\n"; - - try - { - if (this.peer ().send (mesg) < 0) - { - ACE.ERROR ("Error sending request"); - return -1; - } - } - catch (IOException e) - { - ACE.ERROR (e); - return -1; - } - return 0; - } - - // Send the data - protected int sendData () - { - // Get the actual data to send - String data = this.mb_.base ().substring (this.offset_, - this.offset_ + this.length_); - - - try - { - // System.out.println (data); - // Now send the data - if (this.peer ().send (data) != this.length_) - { - ACE.ERROR ("Error sending file"); - return -1; - } - } - catch (IOException e) - { - ACE.ERROR (e); - return -1; - } - this.bytesWritten_ = this.length_; - return 0; - } - - - protected int receiveReply () - { - System.out.println("Waiting for reply"); - - // Receive the reply from the server - StringBuffer reply = new StringBuffer (1024); - - try - { - if (this.peer ().recv (reply) < 0) - { - ACE.ERROR ("Error receiving reply from server"); - return -1; - } - } - catch (IOException e) - { - ACE.ERROR (e); - } - - String s = reply.toString (); - - int index = -1; - // Now parse the reply to see if it was a success or a failure - if ((index = s.indexOf (replyPrefix_)) == -1) - { - ACE.ERROR ("Error receiving reply from server"); - return -1; - } - - int codeIndex = index + replyPrefix_.length () + 1; - - // Assume code is a 3 digit number - String codeString = s.substring (codeIndex, codeIndex + 3); - - returnCode_ = (new Integer (codeString)).intValue (); - // System.out.println (code); - - if (returnCode_ >= 200 && returnCode_ < 300) { // Check if everything went smoothly - System.out.println("We got the goodies!"); - return 0; - } else - return -1; - } - - public int returnCode () - { - return this.returnCode_; - } - - protected String authentication_ = null; - protected String protocol_ = "http://"; - protected int bytesWritten_ = 0; - protected MessageBlock mb_ = null; - protected String requestPrefix_ = "PUT"; - protected String requestSuffix_ = "HTTP/1.0\n"; - protected String replyPrefix_ = "HTTP/1.0"; - protected int returnCode_; -} - - diff --git a/java/src/ClassNameGenerator.java b/java/src/ClassNameGenerator.java deleted file mode 100644 index 0be175c5275..00000000000 --- a/java/src/ClassNameGenerator.java +++ /dev/null @@ -1,181 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ClassNameGenerator.java - * - * Given a locator string which may specify a class name, this generates as many possible locations for that - * class file as possible. This is needed when trying to infer a class name from a C++ DLL line in the - * svc.conf file. Implements the Enumeration interface. A variety of questionable tactics are - * used. - * - *@author Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import java.util.*; -import JACE.OS.*; - -public class ClassNameGenerator implements Enumeration -{ - /** - * Constructor - * @param locator Locator string -- approximate class name - */ - public ClassNameGenerator (String locator) - { - this.locator_ = locator; - this.current_ = 0; - this.suggestions_ = new Vector(); - - this.makeSuggestions(); - } - - /** - * More unseen possibilities? - */ - public boolean hasMoreElements() - { - return this.current_ < this.suggestions_.size(); - } - - /** - * Get the next string - */ - public Object nextElement() - { - return this.suggestions_.elementAt(this.current_++); - } - - /** - * Take away things underscores, adjust capitalization. This - * makes a name more like a Java class name - */ - String makeJavaName(String oldName) - { - StringTokenizer tok = new StringTokenizer(oldName, "_"); - String result = new String(); - - while (tok.hasMoreTokens()) { - String token = tok.nextToken(); - - if (token.length() > 0) { - - result += (Character.toUpperCase(token.charAt(0)) + token.substring(1)); - } - } - - return result; - } - - - /** - * Generate the suggestions - */ - void makeSuggestions() - { - String slash = new String(System.getProperty("file.separator")); - - // Discard things like .shobj - if ((this.locator_.charAt(0) == '.') && (this.locator_.charAt(1) != '.')) { - int firstslash = this.locator_.indexOf(slash); - if (firstslash > 0) - this.locator_ = this.locator_.substring(firstslash + 1); - } - - // Find the last directory separator and the colon (inbetween - // these two is the last directory name, and by our convention - // this should be the class name) - int lastSlash = this.locator_.lastIndexOf(slash); - int colon = this.locator_.lastIndexOf(":"); - - ACE.DEBUG("Working with " + this.locator_ + " " + - lastSlash + " " + colon); - - // Best bet first: - // Locator string is a path, and the last directory name is the class - // name - String lastDir = new String(this.locator_.substring(lastSlash + 1, - colon)); - - // Save any other path info for later tries - String path = null; - if (lastSlash >= 0) - path = this.locator_.substring(0, lastSlash + 1); - - int tryNum = 0; - - if (lastDir.length() > 0) { - - // Add this try - this.suggestions_.addElement(lastDir); - - if (path != null) - this.suggestions_.addElement(path + lastDir); - - // Second try: - // Same as the first, but changed to the Java convention for class names: - // Begins with a capital letter, capital letters for new words rather - // than underscores. - - String try2 = this.makeJavaName(lastDir); - - this.suggestions_.addElement(try2); - if (path != null) - this.suggestions_.addElement(path + try2); - } - - // Third try: - // After the colon, the name of the method that created instances of the - // class in C++ may contain the class name. Maybe in the format of - // make_classname, etc. - - String lastWord = new String(this.locator_.substring(colon + 1)); - - if (lastWord.length() > 0) { - - // Try the word after the colon, too - this.suggestions_.addElement(lastWord); - if (path != null) - this.suggestions_.addElement(path + lastWord); - - String try2 = this.makeJavaName(lastWord); - - this.suggestions_.addElement(try2); - if (path != null) - this.suggestions_.addElement(path + try2); - - int make = lastWord.indexOf("make"); - if (make >= 0) { - - make += 4; - String makeTry = new String(lastWord.substring(make)); - - if (makeTry.length() > 0) { - - this.suggestions_.addElement(makeTry); - if (path != null) - this.suggestions_.addElement(path + makeTry); - - String try3 = this.makeJavaName(makeTry); - - this.suggestions_.addElement(try3); - if (path != null) - this.suggestions_.addElement(path + try3); - } - } - } - - } - - String locator_; - Vector suggestions_; - - int current_; -}; - - diff --git a/java/src/ClassReader.java b/java/src/ClassReader.java deleted file mode 100644 index c10c00b061c..00000000000 --- a/java/src/ClassReader.java +++ /dev/null @@ -1,146 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ClassReader.java - * - *@author Everett Anderson - * - *@see JACE.ServiceConfigurator - *@see JACE.ServiceConfigurator.ServiceLoader - * - *************************************************/ -package JACE.ServiceConfigurator; - -import JACE.OS.*; -import java.io.*; -import java.util.*; - -/** - * <hr> - * <p><b>TITLE</b><br> - * Given a classfile name, this determines the qualified class name - * of what's inside (pacakage and class name together). It is necessary - * when users want to dynamically load classes, but don't provide the - * full name in svc.conf. - */ - -public class ClassReader -{ - // Types found in classfiles - public static final byte CONSTANT_Class = 7; - public static final byte CONSTANT_Fieldref = 9; - public static final byte CONSTANT_Methodref = 10; - public static final byte CONSTANT_InterfaceMethodref = 11; - public static final byte CONSTANT_String = 8; - public static final byte CONSTANT_Integer = 3; - public static final byte CONSTANT_Float = 4; - public static final byte CONSTANT_Long = 5; - public static final byte CONSTANT_Double = 6; - public static final byte CONSTANT_NameAndType = 12; - public static final byte CONSTANT_Utf8 = 1; - - /** Returns a string that is the qualified class name of the - * given file. It returns null if there are any problems. - * - *@param fileName File to examine - * - *@return String that's the qualified class name of the - * given file (null on error) - */ - public static String getClassName(String fileName) - { - try { - - // Open the .class file - FileInputStream fis = new FileInputStream(fileName); - - DataInputStream dis = new DataInputStream(fis); - - // Skip magic number and version numbers - dis.skipBytes(8); - - // Find out how many entries are in the constant pool table - int count = dis.readUnsignedShort(); - - // Hash table to hold the text entries (possibilities for - // the class name) - Hashtable ht = new Hashtable(); - - // Vector that holds the index of the class name for each - // class record (the vector is indexed by placement in the - // table) - Vector vt = new Vector(count); - Integer noValue = new Integer(-1); - int type; - - // Scan through all the entries - for (int i = 1; i < count; i++) { - - // Read what type of entry this is - type = dis.readUnsignedByte(); - - switch (type) { - - case CONSTANT_Class: - // Save the index of the class name - vt.addElement(new Integer(dis.readUnsignedShort())); - break; - case CONSTANT_Fieldref: - case CONSTANT_Methodref: - case CONSTANT_InterfaceMethodref: - case CONSTANT_Integer: - case CONSTANT_Float: - case CONSTANT_NameAndType: - // Skip the data - vt.addElement(noValue); - dis.skipBytes(4); - break; - case CONSTANT_String: - // Skip the data - vt.addElement(noValue); - dis.skipBytes(2); - break; - case CONSTANT_Long: - case CONSTANT_Double: - // Skip the data - vt.addElement(noValue); - dis.skipBytes(8); - // These take up two spots in the table - i++; - break; - case CONSTANT_Utf8: - vt.addElement(noValue); - // Save the text in the hash table - ht.put(new Integer(i), new String(dis.readUTF())); - break; - default: - ACE.DEBUG("Unknown type: " + type); - break; - - } - - } - - // Skip the access flags - dis.skipBytes(2); - - // Get index in table of this class - int classIdx = dis.readUnsignedShort(); - - // Get index in the table of the name of this class - Integer idx = (Integer)vt.elementAt(classIdx - 1); - - // Put the result in period separated notation - String result = new String(((String)ht.get(idx)).replace('/', '.')); - - return result; - - } catch (IOException e) { - ACE.ERROR("" + e); - return null; - } - } -} diff --git a/java/src/Condition.java b/java/src/Condition.java deleted file mode 100644 index d0b5e10a84e..00000000000 --- a/java/src/Condition.java +++ /dev/null @@ -1,122 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * Condition.java - * - *@author Irfan Pyarali - * - *************************************************/ -package JACE.Concurrency; - -import JACE.ASX.TimeoutException; -import JACE.ASX.TimeValue; - -/** - * <hr> - * <h2>TITLE</h2> - *<blockquote> - * Abstraction for <em>traditional</em> - * condition variable - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * This condition variable allows the use of one - * mutex between multiple conditions. - * This implementation is based on the C++ version of ACE. - *</blockquote> - */ -public class Condition -{ - /** - * Default constructor - *@param Mutex for synchronization - */ - public Condition (Mutex mutex) - { - mutex_ = mutex; - } - - /** - * Wait for condition to become signaled. - *@exception InterruptedException exception during wait - */ - public void Wait () - throws InterruptedException - { - waiters_++; - - try - { - mutex_.release(); - semaphore_.acquire (); - mutex_.acquire (); - } - finally - { - waiters_--; - } - } - - /** - * TimedWait for condition to become signaled. Note that the - * given TimeValue is an absolute time, not a relative time. - * - *@param tv Absolute time to wait until before timing out - *@exception TimeoutException wait timed out exception - *@exception InterruptedException exception during wait - */ - public void Wait (TimeValue tv) - throws TimeoutException, InterruptedException - { - waiters_++; - - try - { - mutex_.release(); - - semaphore_.acquire (tv); - - mutex_.acquire (tv); - } - finally - { - waiters_--; - } - } - - /** - * Signal condition. Wake one waiter (if any). - */ - public void signal () - { - if (waiters_ > 0) - semaphore_.release (); - } - - /** - * Signal condition. Wake up all waiters (if any). - */ - public void broadcast () - { - for (int i = waiters_; i > 0; i--) - semaphore_.release (); - } - - /** - * Accessor to lock - *@return Mutex - */ - public Mutex mutex () - { - return mutex_; - } - - private int waiters_; - private Semaphore semaphore_ = new Semaphore (0); - private Mutex mutex_; - -} diff --git a/java/src/Connector.java b/java/src/Connector.java deleted file mode 100644 index 7393ea486e0..00000000000 --- a/java/src/Connector.java +++ /dev/null @@ -1,157 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * Connector.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.SOCK_SAP.*; -import JACE.ServiceConfigurator.*; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Abstract factory for connecting a - * (<a href="JACE.Connection.SvcHandler.html"><tt>SvcHandler</tt></a>), - * to an application. - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * Implements the basic strategy for actively establishing connections - * with applications. The <tt>Connector</tt> establishes the connection, - * passing it on to a <tt>SvcHandler</tt> instance, and handing over - * control to that instance. - *<p> - * TCP is the transport mechanism used, via - * <a href="JACE.SOCK_SAP.SOCKConnector.html#_top_"><tt>SOCKConnector</tt></a>. - *</blockquote> - * - *<h2>NOTES</h2> - *<blockquote> - * This class, as currently implemented, does not work like its C++ counterpart. - * Future versions are expected to rectify this discrepancy. - *</blockquote> - * - *@see SOCKConnector - *@see SvcHandler - */ -public class Connector extends ServiceObject -{ - /** - * Create a Connector. Do nothing constructor. Allows user to - * call <a href="#open(java.lang.String)">open</a>() later. - */ - public Connector () - { - } - - /** - * Create a Connector passing in server hostname and port - * number, effectively shorthand for calling - * <a href="#open(java.lang.String)">open</a>(). - *@param hostname server hostname - *@param port server port number - */ - public Connector (String hostname, int port) - { - this.open (hostname, port); - } - - /** - * Initialize the Connector passing in server hostname and port - * number. Note that no connection attempt is made. - *@param hostname server hostname - *@param port server port number - */ - public void open (String hostname, int port) - { - this.hostname_ = hostname; - this.port_ = port; - } - - /** - * Connect to the server. - *@param sh Svc Handler to use to handle the connection - *@exception UnknownHostException Bad host - *@exception SocketException Socket error - *@exception InstantiationException Couldn't create new SOCKConnector - *@exception IllegalAccessException No strategy available - *@exception IOException Socket error - */ - public void connect (SvcHandler sh) throws UnknownHostException, - SocketException, - InstantiationException, - IllegalAccessException, - IOException - { - // Make a connection using the appropriate Connection_Strategy - this.connectSvcHandler (sh); - - // Activate the Svc_Handler using the appropriate Activation_Strategy - this.activateSvcHandler (sh); - } - - /** - * Bridge method for making a new connection. The default behavior - * creates a new SOCKConnector and then calls setHandle() on the - * <SvcHandler> that was passed in. Subclasses can override this - * strategy, if needed. - *@param sh Svc Handler to use to handle the connection - *@return 0 - *@exception SocketException Socket error - *@exception IOException Socket error - */ - protected int connectSvcHandler (SvcHandler sh) throws - SocketException, IOException - { - // Create a new stream - SOCKStream sockStream = new SOCKStream (); - - // Create a SOCK_Connector (note the constructor does the connect for us) - this.sockConnector_ = new SOCKConnector (sockStream, - this.hostname_, - this.port_); - ACE.DEBUG ("Connected to " + - sockStream.socket ().getInetAddress ()); - - // Set the streams for the new handler - sh.setHandle (sockStream); - return 0; - } - - /** - * Bridge method for activating a <SvcHandler>. The default - * behavior of this method is to activate the <SvcHandler> by - * calling its open() method (which allows the SVC_HANDLER to define - * its own concurrency strategy). However, subclasses can override - * this strategy to do more sophisticated concurrency activations. - *@param sh Svc Handler to activate - *@return 0 - */ - protected int activateSvcHandler (SvcHandler sh) - { - sh.open (null); - return 0; - } - - - // Port server is listening on - private int port_; - - // Server hostname - private String hostname_; - - // Our connection factory - private SOCKConnector sockConnector_; -} diff --git a/java/src/CreationStrategy.java b/java/src/CreationStrategy.java deleted file mode 100644 index f929ef86204..00000000000 --- a/java/src/CreationStrategy.java +++ /dev/null @@ -1,64 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * CreationStrategy.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Defines the interface for specifying a creation strategy for a - * <a href="ACE.Connection.SvcHandler.html#_top_"><tt>SvcHandler</tt></a> to the - * <a href="ACE.Connection.StrategyAcceptor.html#_top_"><tt>StrategyAcceptor</tt></a>. - *</blockquote> - * - * <p><b>DESCRIPTION</b><br> - *<blockquote> - * The default behavior is to make a new SvcHandler. However, - * subclasses can override this strategy to perform SvcHandler - * creation in any way that they like (such as creating subclass - * instances of SvcHandler, using a singleton, dynamically - * linking the handler, etc.). - *</blockquote> - * - *@see SvcHandler - *@see StrategyAcceptor - *@see AcceptStrategy - *@see ActivateStrategy - */ -public class CreationStrategy -{ - /** - * Create an instance of Creation Strategy. - *@param handlerFactory Svc Handler factory that is used to create - * an instance of a Svc Handler - */ - public CreationStrategy (Class handlerFactory) - { - this.handlerFactory_ = handlerFactory; - } - - /** - * Create a new SvcHandler. Note that subclasses should override - * this method to provide a new creation strategy. - *@return reference to a new instance of the SvcHandler (or subclass) - *@exception InstantiationException Unable to instantiate. - *@exception IllegalAccessException No handler factory available. - */ - public SvcHandler makeSvcHandler () throws InstantiationException, - IllegalAccessException - { - // Create a new Svc_Handler - return (SvcHandler) handlerFactory_.newInstance (); - } - - private Class handlerFactory_; -} diff --git a/java/src/EventHandler.java b/java/src/EventHandler.java deleted file mode 100644 index 30f5bb1dba4..00000000000 --- a/java/src/EventHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Reactor - * - * = FILENAME - * EventHandler.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Reactor; - -import JACE.ASX.TimeValue; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Provides an abstract interface for handling timer events. - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * Classes implementing this interface handle a timer's - * expiration. - *</blockquote> - * - * <h2>NOTES</h2> - *<blockquote> - * Users of C++ ACE will notice that this defines a substantially - * smaller interface than the C++ counterpart. Signal events are - * absent due to the complete absence of this feature from Java itself. - * Moreover, at this point - * there is still some question regarding whether or not the I/O - * portion will make any sense or fit into the Java model for I/O. - *</blockquote> - * - *@see TimerQueue - *@see JACE.Reactor - */ -public interface EventHandler -{ - /** - * Called when timer expires. - *@param tv Time Value at which the event occured - *@param obj An arbitrary object that was passed to the Timer Queue - * (Asynchronous Completion Token) - */ - public int handleTimeout (TimeValue tv, Object obj); -} - -// Note that more methods will be added as needed diff --git a/java/src/GetOpt.java b/java/src/GetOpt.java deleted file mode 100644 index 2bf5d27c406..00000000000 --- a/java/src/GetOpt.java +++ /dev/null @@ -1,150 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Misc - * - * = FILENAME - * GetOpt.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Misc; - -import java.io.*; -import java.util.Hashtable; -import java.util.StringTokenizer; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Iterator for parsing command-line arguments. - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * This version of `get_opt' appears to the caller like standard - * Unix `get_opt' but it behaves differently for the user, since - * it allows the user to intersperse the options with the other - * arguments. - * - * <p> As `get_opt' works, it permutes the elements of `argv' so that, - * when it is done, all the options precede everything else. Thus - * all application programs are extended to handle flexible argument - * order. - *</blockquote> - * - */ -public class GetOpt -{ - /** - * Constructor - *@param args command line arguments - *@param optstring string containing the legitimate option - * characters. A colon in optstring means that the previous character - * is an option that wants an argument which is then taken from the - * rest of the current args-element. Here is an example of what - * optstring might look like: "c:dP:p". - */ - public GetOpt (String[] args, String optstring) - { - // Cache the arguments - this.args_ = args; - this.hasArg_ = false; - - // Build the arg hashtable - this.buildArgTable (optstring); - } - - /** - * Scan elements specified in optstring for next option flag. - *@return The character corresponding to the next flag. - */ - public int next () - { - if (this.args_ == null) - return -1; - - if (this.index_ < this.args_.length) - { - String arg = this.args_[this.index_++]; - - // Make sure flag starts with "-" - if (!arg.startsWith ("-")) - return -1; - - // Check if there is more than one character specified as flag - if (arg.length () > 2) - return -1; - - // So far so good - // Check if the flag is in the arg_table and if it is get the - // associated binding. - Character c = (Character) this.argTable_.get (new Character (arg.charAt (1))); - if (c == null) - return -1; - - if (c.charValue () == '#') - { - this.hasArg_ = false; - return arg.charAt (1); - } - else if (c.charValue () == ':') - { - this.hasArg_ = true; - return arg.charAt (1); - } - else // This should not happen - return -1; - } - return -1; - } - - /** - * Get the argument (if any) associated with the flag. - *@return the argument associated with the flag. - */ - public String optarg () - { - if (this.hasArg_) - return this.args_[this.index_++]; - else - return null; - } - - // Build the argument table - private void buildArgTable (String s) - { - this.argTable_ = new Hashtable (); - StringTokenizer tokens = new StringTokenizer (s, ":"); - while (tokens.hasMoreTokens ()) - { - // Get the next token - String t = tokens.nextToken (); - - // First add all flags except the one with ":" after it - // Note "#" is an arbitrary character we use to distinguish - // the two cases - for (int i = 0; i < t.length () - 1; i++) - this.argTable_.put (new Character (t.charAt (i)), - new Character ('#')); - - // Now Add the flag just before ":" to the arg_table - this.argTable_.put (new Character (t.charAt (t.length () - 1)), - new Character (':')); - } - } - - private String [] args_; - // Copy of the args passed in - - private boolean hasArg_; - // Indicator that the flag has an argument following it - - private int index_; - // Index into the array of arguments - - private Hashtable argTable_; - // Table of flags that take arguments after them -} diff --git a/java/src/HTTPHelper.java b/java/src/HTTPHelper.java deleted file mode 100644 index d946913693c..00000000000 --- a/java/src/HTTPHelper.java +++ /dev/null @@ -1,84 +0,0 @@ -package JACE.Connection; - -import JACE.OS.*; -// Collection of various methods that have to do with HTTP - -public class HTTPHelper -{ - // Encoding and decoding yadda - public static String Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - // Basic encoding used in the HTTP 1.1 RFC. This doesn't - // put the string "Basic " at the beginning of the return - // string. Adapted from James' JAWS HTTP_Helpers code. - // Returns null on error. - public static String EncodeBase64 (String secret) - { - StringBuffer output = new StringBuffer(); - - // Index of the input string - int inidx = 0; - - // character value - int c; - - int char_count = 0; - int bits = 0; - boolean error = false; - - while (inidx < secret.length()) - { - c = secret.charAt(inidx++); - - // This will mess up internationalization. I wonder if it is really - // necessary for HTTP? - if (c > 255) - { - ACE.DEBUG ("encountered char > 255 (decimal %d): " + c); - error = true; - break; - } - - bits += c; - char_count++; - - if (char_count == 3) - { - output.append(HTTPHelper.Alphabet.charAt(bits >> 18)); - output.append(HTTPHelper.Alphabet.charAt((bits >> 12) & 0x3f)); - output.append(HTTPHelper.Alphabet.charAt((bits >> 6) & 0x3f)); - output.append(HTTPHelper.Alphabet.charAt(bits & 0x3f)); - - bits = 0; - char_count = 0; - } - else - bits <<= 8; - } - - if (!error) - { - if (char_count != 0) - { - bits <<= 16 - (8 * char_count); - output.append(HTTPHelper.Alphabet.charAt(bits >> 18)); - output.append(HTTPHelper.Alphabet.charAt((bits >> 12) & 0x3f)); - - if (char_count == 1) - { - output.append("=="); - } - else - { - output.append(HTTPHelper.Alphabet.charAt((bits >> 6) & 0x3f)); - output.append('='); - } - } - - return output.toString(); - } - - // Returns null on error - return null; - } -}; diff --git a/java/src/INETAddr.java b/java/src/INETAddr.java deleted file mode 100644 index 8d16c46c6b3..00000000000 --- a/java/src/INETAddr.java +++ /dev/null @@ -1,99 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.SOCK_SAP - * - * = FILENAME - * INETAddr.java - * - *@author Chris Cleeland - * - *************************************************/ -package JACE.SOCK_SAP; - -import java.io.*; -import java.net.*; -import JACE.OS.*; - -/** - * <hr> - * <p><b>TITLE</b><br> - * Defines an endpoint of a connection, encapsulating host and port. - * This is only a part-way implementation of C++ ACE's ACE_INET_Addr. - * - * <p><b>LIMITATIONS</b><br> - * Currently the class is very limited in its capabilities; it will - * be expanded in future revisions of ACE. - */ -public class INETAddr // extends Addr -{ - private InetAddress addr_; - private int port_ = 0; - /** - */ - public INETAddr () - { - // Do nothing constructor - } - - /** - * Create an INETAddr from a port/hostname - *@param port port number to connect with server at - *@param hostname hostname of the server - */ - public INETAddr (int port, String hostname) throws UnknownHostException - { - super(); - port_ = port; - addr_ = InetAddress.getByName(hostname); - // Should really use getAllByName(), - // but I don't think we do that in - // C++ ACE, even. - } - - /** - * Create an INETAddr from an address. - * @param address an address in the form "ip-number:port-number", <em>e.g.</em> <pre>tango.cs.wustl.edu:1234</pre> or <pre>128.252.166.57:1234</pre>; if no ':' is present address is assumed to be <b>INADDR_ANY</b> and address contains only the port number - * @throws UnknownHostException - */ - public INETAddr (String address) throws UnknownHostException - { - int colon = address.indexOf(':'); - if (colon != 0) - { - addr_ = InetAddress.getByName(address.substring(0, colon)); - address = address.substring(colon+1); - } - - port_ = Integer.parseInt(address); - } - - /** - * Return the name of the host. - */ - public String getHostName() - { - return addr_.getHostName(); - } - - /** - * Return the dotted Internet address. - */ - public String getHostAddr() - { - return addr_.toString(); - } - - /** - * Return the port number. - */ - public int getPortNumber() - { - return port_; - } - - public String toString() - { - return getHostAddr() + Integer.toString(port_); - } -} diff --git a/java/src/IOCntlCmds.java b/java/src/IOCntlCmds.java deleted file mode 100644 index 2469428a3a6..00000000000 --- a/java/src/IOCntlCmds.java +++ /dev/null @@ -1,34 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * TaskFlags.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -public abstract class IOCntlCmds -{ - /** Set the low water mark. */ - public static final int SET_LWM = 1; - - /** Get the low water mark. */ - public static final int GET_LWM = 2; - - /** Set the high water mark. */ - public static final int SET_HWM = 3; - - /** Get the high water mark. */ - public static final int GET_HWM = 4; - - /** Link modules */ - public static final int MOD_LINK = 5; - - /** Unlink modules */ - public static final int MOD_UNLINK = 6; - -} diff --git a/java/src/IOCntlMsg.java b/java/src/IOCntlMsg.java deleted file mode 100644 index 8b69310c4f7..00000000000 --- a/java/src/IOCntlMsg.java +++ /dev/null @@ -1,128 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * IOCntlMsg.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Data format for IOCTL messages - *</blockquote> - */ -public class IOCntlMsg -{ - - // = Initialization method. - - /* - * Initialize the control message. - *@param c IOCntlCmd for the control message. Note that this should - * be of type IOCntlCmds - */ - public IOCntlMsg (int c) - { - this.cmd_ = c; - } - - // = Get/set methods - - /* - * Get the command. - *@return the command. - */ - public int cmd () - { - return this.cmd_; - } - - /* - * Set the command. - *@param c the command. - */ - public void cmd (int c) - { - this.cmd_ = c; - } - - /* - * Get the count. - *@return the count. - */ - public int count () - { - return this.count_; - } - - /* - * Set the count. - *@param c the count. - */ - public void count (int c) - { - this.count_ = c; - } - - /* - * Get the error. - *@return the error. - */ - public int error () - { - return this.error_; - } - - /* - * Set the error. - *@param e the error. - */ - public void error (int e) - { - this.error_ = e; - } - - /* - * Get the return value. - *@return the return value. - */ - public int rval () - { - return this.rval_; - } - - /* - * Set the return value. - *@param r the return value. - */ - public void rval (int r) - { - this.rval_ = r; - } - - public String toString () - { - return (new Integer (this.cmd_)).toString (); - } - - private int cmd_; - // Command. - - private int count_; - // Count. - - private int error_; - // Error. - - private int rval_; - // Return value -} diff --git a/java/src/JACE.DSP b/java/src/JACE.DSP deleted file mode 100644 index 8c564995235..00000000000 --- a/java/src/JACE.DSP +++ /dev/null @@ -1,292 +0,0 @@ -# Microsoft Developer Studio Project File - Name="JACE" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 5.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=JACE - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "JACE.MAK".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "JACE.MAK" CFG="JACE - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "JACE - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "JACE - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "JACE - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\classes-r\"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "JACE - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\classes\"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "JACE - Java Virtual Machine Release"
-# Name "JACE - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\Acceptor.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\AcceptStrategy.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ACE.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ActivateStrategy.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\AddServiceObjectNode.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\Blob.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\BlobHandler.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\BlobReader.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\BlobWriter.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ClassNameGenerator.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ClassReader.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\Condition.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\Connector.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\CreationStrategy.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\EventHandler.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\GetOpt.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\HTTPHelper.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\INETAddr.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\IOCntlCmds.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\IOCntlMsg.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\MessageBlock.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\MessageQueue.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\MessageType.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\Module.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\Mutex.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\OS.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ParseNode.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ProfileTimer.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\RemoveNode.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ResumeNode.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\RWMutex.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\Semaphore.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ServiceConfig.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ServiceLoader.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ServiceObject.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ServiceObjectRecord.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ServiceRecord.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ServiceRepository.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\SOCKAcceptor.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\SOCKConnector.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\SOCKStream.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\StrategyAcceptor.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\Stream.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\StreamHead.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\StreamTail.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\SuspendNode.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\SvcHandler.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\Task.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\TaskFlags.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ThreadManager.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\ThruTask.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\TimedWait.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\TimeoutException.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\TimerQueue.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\TimeValue.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\Token.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/src/JACE.DSW b/java/src/JACE.DSW deleted file mode 100644 index 1adb106b259..00000000000 --- a/java/src/JACE.DSW +++ /dev/null @@ -1,29 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 5.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "JACE"=.\JACE.DSP - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - diff --git a/java/src/Makefile b/java/src/Makefile deleted file mode 100644 index ebdf2329861..00000000000 --- a/java/src/Makefile +++ /dev/null @@ -1,153 +0,0 @@ -# Makefile -# $Id$ - -.SUFFIXES: .java .class - -JACE_WRAPPER = .. -CLASSDIR = $(JACE_WRAPPER)/classes -DOCDIR = $(JACE_WRAPPER)/doc - -JC = javac -JCOPTS = -g -d $(CLASSDIR) -JD = javadoc -JDOPTS = -d $(DOCDIR) - -COMPILE.java = $(JC) $(JCOPTS) $(filter %.java,$?) - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: asx os concurrency connection timers misc reactor svcconfig socksap - -pkg_all = $(pkg_asx_timestuff) $(pkg_asx) $(pkg_os) $(pkg_concurrency) \ - $(pkg_connection) $(pkg_timers) $(pkg_misc) $(pkg_reactor) \ - $(pkg_socksap) $(pkg_svcconfig) - -doc: - $(JD) $(JDOPTS) $(addsuffix .java,$(pkg_all)) $(packages) - -clean: - find ${JACE_WRAPPER}/classes/JACE -name '*.class' -print | xargs ${RM} - -docclean: - find ${JACE_WRAPPER}/doc -name '*.html' -print | xargs ${RM} - -realclean: clean docclean - - -pkg_asx_timestuff = \ - TimeValue \ - TimeoutException \ - TimedWait - -asx_timestuff: $(addsuffix .java,$(pkg_asx_timestuff)) - $(COMPILE.java) - -pkg_asx = \ - IOCntlCmds \ - IOCntlMsg \ - Task \ - TaskFlags \ - ThruTask \ - Module \ - MessageType \ - MessageBlock \ - MessageQueue \ - StreamHead \ - StreamTail \ - Stream - -asx: os asx_timestuff reactor concurrency $(addsuffix .java,$(pkg_asx)) - $(COMPILE.java) - -pkg_os = \ - OS \ - ACE - -os: $(addsuffix .java,$(pkg_os)) - $(COMPILE.java) - -pkg_concurrency = \ - Condition \ - Mutex \ - RWMutex \ - Semaphore \ - ThreadManager \ - Token - -concurrency: $(addsuffix .java,$(pkg_concurrency)) asx_timestuff os - $(COMPILE.java) - -pkg_connection = \ - SvcHandler \ - Acceptor \ - Connector \ - AcceptStrategy \ - ActivateStrategy \ - CreationStrategy \ - StrategyAcceptor \ - Blob \ - BlobHandler \ - BlobReader \ - BlobWriter \ - HTTPHelper - -connection: os socksap svcconfig $(addsuffix .java,$(pkg_connection)) - $(COMPILE.java) - -pkg_timers = \ - ProfileTimer - -timers: $(addsuffix .java,$(pkg_timers)) - $(COMPILE.java) - -pkg_misc = \ - GetOpt - -misc: $(addsuffix .java,$(pkg_misc)) - $(COMPILE.java) - -pkg_reactor = \ - EventHandler \ - TimerQueue - -reactor: asx_timestuff $(addsuffix .java,$(pkg_reactor)) - $(COMPILE.java) - -pkg_socksap = \ - INETAddr \ - SOCKStream \ - SOCKAcceptor \ - SOCKConnector - -socksap: os $(addsuffix .java,$(pkg_socksap)) - $(COMPILE.java) - -pkg_svcconfig = \ - ServiceLoader \ - ClassReader \ - ParseNode \ - SuspendNode \ - ResumeNode \ - RemoveNode \ - ServiceRecord \ - ServiceObjectRecord \ - AddServiceObjectNode \ - ServiceObject \ - ServiceConfig \ - ServiceRepository - -svcconfig: os reactor misc $(addsuffix .java,$(pkg_svcconfig)) - $(COMPILE.java) - -packages = JACE \ - JACE.ASX \ - JACE.Connection \ - JACE.Concurrency \ - JACE.Misc \ - JACE.OS \ - JACE.Reactor \ - JACE.SOCK_SAP \ - JACE.ServiceConfigurator \ - JACE.Timers - - diff --git a/java/src/MessageBlock.java b/java/src/MessageBlock.java deleted file mode 100644 index 1741f9bef80..00000000000 --- a/java/src/MessageBlock.java +++ /dev/null @@ -1,453 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * MessageBlock.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Object used to store messages in the ASX framework. - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * <tt>MessageBlock</tt> is modeled after the message data structures - * used in System V STREAMS. A <tt>MessageBlock</tt> is composed of - * one or more <tt>MessageBlock</tt>s that are linked together by <em>PREV</em> - * and <em>NEXT</em> pointers. In addition, a <tt>MessageBlock</tt> may also be - * linked to a chain of other <tt>MessageBlock</tt>s. This structure - * enables efficient manipulation of arbitrarily-large messages - * <em>without</em> incurring memory copying overhead. - *</blockquote> - * - *@see MessageQueue - */ -public class MessageBlock -{ - /** - * Create an empty Message Block - */ - public MessageBlock () - { - this (0); - } - - /** - * Create an empty Message Block. - * Note that this assumes that type of MessageBlock is MB_DATA. - *@param size size of the Message Block to create. - */ - public MessageBlock (int size) - { - // Note the explicit cast toString() is needed. For some strange - // reason, it fails otherwise if size == 0. - this ((new StringBuffer (size)).toString ()); - } - - /** - * Create a Message Block. Note that this assumes that type of - * MessageBlock is MB_DATA. - *@param data initial data to create a Message Block with. - */ - public MessageBlock (String data) - { - this (MessageType.MB_DATA, - null, - data); - } - - /** - * Create a Message Block. - *@param type type of the Message Block (must be one of those - * specified in class Message Type) - *@param cont next block of data - *@param data initial data to create Message Block with - */ - public MessageBlock (int type, - MessageBlock cont, - String data) - { - this.flags_ = 0; - this.priority_ = 0; - this.next_ = null; - this.prev_ = null; - - this.init (type, cont, data); - } - - /** - * Create a Message Block. Note that this assumes that type of - * MessageBlock is MB_OBJECT. - *@param obj initial object to create a Message Block with. - */ - public MessageBlock (Object obj) - { - this (MessageType.MB_OBJECT, - null, - obj); - } - - /** - * Create a Message Block. - *@param type type of the Message Block (must be one of those - * specified in class Message Type) - *@param cont next block of data - *@param obj initial object to create Message Block with - */ - public MessageBlock (int type, - MessageBlock cont, - Object obj) - { - this.init (type, cont, obj); - } - - /* Initialize the Message Block - *@param data data to initialize Message Block with - */ - public void init (String data) - { - this.base_ = new StringBuffer (data); - } - - /** - * Initialize a Message Block. - *@param type type of the Message Block (must be one of those - * specified in class Message Type) - *@param cont next block of data - *@param data data to initialize Message Block with - */ - public void init (int msgType, - MessageBlock msgCont, - String data) - { - if (data.length () == 0) - this.base_ = new StringBuffer (0); - else - this.base_ = new StringBuffer (data); - this.type_ = msgType; - this.cont_ = msgCont; - } - - /** - * Initialize a Message Block. Note that this assumes that type of - * MessageBlock is MB_OBJECT. - *@param obj initial object to initialize a Message Block with. - */ - public void init (Object obj) - { - this.init (MessageType.MB_OBJECT, null, obj); - } - - /** - * Initialize a Message Block. - *@param type type of the Message Block (must be one of those - * specified in class Message Type) - *@param cont next block of data - *@param obj object to initialize Message Block with - */ - public void init (int msgType, - MessageBlock msgCont, - Object obj) - { - this.obj_ = obj; - this.type_ = msgType; - this.cont_ = msgCont; - this.flags_ = 0; - this.priority_ = 0; - this.next_ = null; - this.prev_ = null; - } - - /** - * Set message flags. Note that the flags will be set on top of - * already set flags. - *@param moreFlags flags to set for the Message Block. - */ - public long setFlags (long moreFlags) - { - // Later we might mask more_flags so that user can't change - // internal ones: more_flags &= ~(USER_FLAGS -1). - this.flags_ = ACE.SET_BITS (this.flags_, moreFlags); - return this.flags_; - } - - /** - * Unset message flags. - *@param lessFlags flags to unset for the Message Block. - */ - public long clrFlags (long lessFlags) - { - // Later we might mask more_flags so that user can't change - // internal ones: less_flags &= ~(USER_FLAGS -1). - this.flags_ = ACE.CLR_BITS (this.flags_, lessFlags); - return this.flags_; - } - - /** - * Get the message flags. - *@return Message flags - */ - public long flags () - { - return this.flags_; - } - - /** - * Get the type of the message. - *@return message type - */ - public int msgType () - { - return this.type_; - } - - /** - * Set the type of the message. - *@param t type of the message - */ - public void msgType (int t) - { - this.type_ = t; - } - - /** - * Get the class of the message. Note there are two classes, - * <normal> messages and <high-priority> messages. - *@return message class - */ - public int msgClass () - { - return this.msgType () >= MessageType.MB_PRIORITY - ? MessageType.MB_PRIORITY : MessageType.MB_NORMAL; - } - - /** - * Find out if the message is a data message. - *@return true if message is a data message, false otherwise - */ - public boolean isDataMsg () - { - int mt = this.msgType (); - return mt == MessageType.MB_DATA - || mt == MessageType.MB_PROTO - || mt == MessageType.MB_PCPROTO; - } - - /** - * Find out if the message is an object message. - *@return true if message is an object message, false otherwise - */ - public boolean isObjMsg () - { - int mt = this.msgType (); - return mt == MessageType.MB_OBJECT - || mt == MessageType.MB_PROTO - || mt == MessageType.MB_PCPROTO; - } - - /** - * Get the priority of the message. - *@return message priority - */ - public long msgPriority () - { - return this.priority_; - } - - /** - * Set the priority of the message. - *@param pri priority of the message - */ - public void msgPriority (long pri) - { - this.priority_ = pri; - } - - /** - * Get message data. This assumes that msgType is MB_DATA. - *@return message data - */ - public String base () - { - // Create a String object to return - char temp[] = new char [this.base_.length ()]; - this.base_.getChars (0, this.base_.length (), temp, 0); - return new String (temp); - } - - /** - * Set the message data. This assumes that msgType is MB_DATA. - *@param data message data - *@param msgFlags message flags - */ - public void base (String data, - long msgFlags) - { - this.base_ = new StringBuffer (data); - this.flags_ = msgFlags; - } - - /** - * Get message object. This assumes that msgType is MB_OBJECT. - *@return message object - */ - public Object obj () - { - return this.obj_; - } - - /** - * Set the message object. This assumes that msgType is MB_OBJECT. - *@param object message object - *@param msgFlags message flags - */ - public void obj (Object obj, - long msgFlags) - { - this.obj_ = obj; - this.flags_ = msgFlags; - } - - // = The following four methods only make sense if the Message_Block - // is of type MB_DATA and not MB_OBJECT. - - /** - * Get length of the message. This method only makes sense if the - * MessageBlock is of type MB_DATA and not MB_OBJECT. - *@return length of the message. - */ - public int length () - { - return this.base_.length (); - } - - /** - * Set the length of the message. This method only makes sense if the - * MessageBlock is of type MB_DATA and not MB_OBJECT. - *@param n message length - */ - public void length (int n) - { - this.base_.setLength (n); - } - - /** - * Get size of the allocated buffer for the message. This method - * only makes sense if the MessageBlock is of type MB_DATA and not - * MB_OBJECT. - *@return size of the message buffer - */ - public int size () - { - return this.base_.capacity (); - } - - /** - * Set the total size of the buffer. This method will grow the - * buffer if need be. Also, this method only makes sense if the - * MessageBlock is of type MB_DATA and not MB_OBJECT. - *@param n size of message buffer - */ - public void size (int n) - { - this.base_.ensureCapacity (n); - } - - - /** - * Get the continuation field. The coninuation field is used to - * chain together composite messages. - *@return the continuation field - */ - public MessageBlock cont () - { - return this.cont_; - } - - /** - * Set the continuation field. The coninuation field is used to - * chain together composite messages. - *@param msgCont continuation field - */ - void cont (MessageBlock msgCont) - { - this.cont_ = msgCont; - } - - /** - * Get link to next message. The next message points to the - * <MessageBlock> directly ahead in the MessageQueue. - *@return next message block - */ - MessageBlock next () - { - return this.next_; - } - - /** - * Set link to next message. The next message points to the - * <MessageBlock> directly ahead in the MessageQueue. - *@param msgBlock next message block - */ - void next (MessageBlock msgBlock) - { - this.next_ = msgBlock; - } - - /** - * Get link to previous message. The previous message points to the - * <MessageBlock> directly before in the MessageQueue. - *@return previous message block - */ - MessageBlock prev () - { - return this.prev_; - } - - /** - * Set link to previous message. The previous message points to the - * <MessageBlock> directly before in the MessageQueue. - *@param msgBlock previous message block - */ - void prev (MessageBlock msgBlock) - { - this.prev_ = msgBlock; - } - - private int type_; - // Type of message. - - private long flags_; - // Misc flags. - - private long priority_; - // Priority of message. - - private StringBuffer base_; - // String data of message block (initialized to null). - - private Object obj_; - // Object data of message block (initialized to null). - - private MessageBlock cont_; - // Next message block in the chain. - - private MessageBlock next_; - // Next message in the list. - - private MessageBlock prev_; - // Previous message in the list. - -} - diff --git a/java/src/MessageQueue.java b/java/src/MessageQueue.java deleted file mode 100644 index 8c8dab1a0fe..00000000000 --- a/java/src/MessageQueue.java +++ /dev/null @@ -1,639 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * MessageQueue.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import java.util.Date; -import JACE.OS.*; -import JACE.Reactor.*; - -class NotFullCondition extends TimedWait -{ - public NotFullCondition (MessageQueue mq) - { - super (mq); - this.mq_ = mq; - } - - public boolean condition () { - // Delegate to the appropriate conditional - // check on the MessageQueue. - return !this.mq_.isFull (); - } - private MessageQueue mq_; -} - -class NotEmptyCondition extends TimedWait -{ - public NotEmptyCondition (MessageQueue mq) - { - super (mq); - this.mq_ = mq; - } - - public boolean condition () { - // Delegate to the appropriate conditional - // check on the MessageQueue. - return !this.mq_.isEmpty (); - } - private MessageQueue mq_; -} - - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * A thread-safe message queueing facility, modeled after the - * queueing facilities in System V StreamS. - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *</blockquote> - * <tt>MessageQueue</tt> is the central queueing facility for messages - * in the ASX framework. All operations are thread-safe, as it is intended - * to be used for inter-thread communication (<em>e.g.</em>, a producer and - * consumer thread joined by a <tt>MessageQueue</tt>). The queue - * consiste of <tt>MessageBlock</tt>s. - *</blockquote> - * - *@see MessageBlock - *@see TimeValue - */ -public class MessageQueue -{ - /** - * Default constructor - */ - public MessageQueue () - { - this (DEFAULT_HWM, DEFAULT_LWM); - } - - /** - * Create a Message Queue with high and low water marks. - *@param hwm High water mark (max number of bytes allowed in the - * queue) - *@param lwm Low water mark (min number of bytes in the queue) - */ - public MessageQueue (int hwm, int lwm) - { - if (this.open (hwm, lwm) == -1) - ACE.ERROR ("open"); - } - - /** - * Initialize a Message Queue with high and low water marks. - *@param hwm High water mark (max number of bytes allowed in the - * queue) - *@param lwm Low water mark (min number of bytes in the queue) - */ - public synchronized int open (int hwm, int lwm) - { - this.highWaterMark_ = hwm; - this.lowWaterMark_ = lwm; - this.deactivated_ = false; - this.currentBytes_ = 0; - this.currentCount_ = 0; - this.tail_ = null; - this.head_ = null; - return 0; - } - - // ************ Note! *********** - // = For enqueue, enqueueHead, enqueueTail, and dequeueHead if - // timeout is specified, the caller will wait until the *absolute time* - // tv. Calls will return, however, when queue is closed, - // deactivated, or if it is past the time tv - - /** - * Enqueue a <MessageBlock> into the <MessageQueue> in accordance - * with its <msgPriority> (0 is lowest priority). Note that the - * call will block (unless the queue has been deactivated). - * - *@exception java.lang.InterruptedException Interrupted while accessing queue - *@param newItem item to enqueue onto the Message Queue - *@return -1 on failure, else the number of items still on the queue. - */ - public synchronized int enqueue (MessageBlock newItem) throws InterruptedException - { - return this.enqueue (newItem, null); - } - - /** - * Enqueue a <MessageBlock> into the <MessageQueue> in accordance - * with its <msgPriority> (0 is lowest priority). Note that the - * call will return if the queue has been deactivated or it is - * later than the specified absolute time value. - *@param newItem item to enqueue onto the Message Queue - *@param tv absolute TimeValue to timeout after - *@return -1 on failure, else the number of items still on the - * queue. - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - public synchronized int enqueue (MessageBlock newItem, - TimeValue tv) throws InterruptedException - { - int result = -1; - if (this.deactivated_) - return -1; - try - { - if (tv == null) // Need to do a blocking wait - notFullCondition_.timedWait (); - else // Need to do a timed wait - notFullCondition_.timedWait (tv); - } - catch (TimeoutException e) - { - return -1; - } - - // Check again if queue is still active - if (this.deactivated_) - return -1; - else - result = this.enqueueInternal (newItem); - - // Tell any blocked threads that the queue has a new item! - this.notEmptyCondition_.broadcast (); - return result; - } - - /** - * Enqueue a <MessageBlock> at the end of the <MessageQueue>. Note - * that the call will block (unless the queue has been deactivated). - *@param newItem item to enqueue onto the Message Queue - *@return -1 on failure, else the number of items still on the queue. - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - public synchronized int enqueueTail (MessageBlock newItem) throws InterruptedException - { - return this.enqueueTail (newItem, null); - } - - /** - * Enqueue a <MessageBlock> at the end of the <MessageQueue>. Note - * that the call will return when it's later than the given TimeValue or - * if the queue has been deactivated. - *@param newItem item to enqueue onto the Message Queue - *@param tv absolute TimeValue to wait until before returning (unless - * the operation compeltes before this time) - *@return -1 on failure, else the number of items still on the queue. - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - public synchronized int enqueueTail (MessageBlock newItem, - TimeValue tv) throws InterruptedException - { - int result = -1; - if (this.deactivated_) - return -1; - try - { - if (tv == null) // Need to do a blocking wait - notFullCondition_.timedWait (); - else // Need to do a timed wait - notFullCondition_.timedWait (tv); - } - catch (TimeoutException e) - { - return -1; - } - - // Check again if queue is still active - if (this.deactivated_) - return -1; - else - result = this.enqueueTailInternal (newItem); - - // Tell any blocked threads that the queue has a new item! - this.notEmptyCondition_.broadcast (); - return result; - } - - /** - * Enqueue a <MessageBlock> at the head of the <MessageQueue>. Note - * that the call will block (unless the queue has been deactivated). - *@param newItem item to enqueue onto the Message Queue - *@return -1 on failure, else the number of items still on the queue. - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - public synchronized int enqueueHead (MessageBlock newItem) throws InterruptedException - { - return this.enqueueHead (newItem, null); - } - - /** - * Enqueue a <MessageBlock> at the head of the <MessageQueue>. Note - * that the call will return when it's later than the given TimeValue or - * if the queue has been deactivated. - *@param newItem item to enqueue onto the Message Queue - *@param tv absolute TimeValue to wait until before returning (unless - * the operation completes before that time) - *@return -1 on failure, else the number of items still on the queue. - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - public synchronized int enqueueHead (MessageBlock newItem, - TimeValue tv) throws InterruptedException - { - int result = -1; - if (this.deactivated_) - return -1; - try - { - if (tv == null) // Need to do a blocking wait - notFullCondition_.timedWait (); - else // Need to do a timed wait - notFullCondition_.timedWait (tv); - } - catch (TimeoutException e) - { - return -1; - } - - // Check again if queue is still active - if (this.deactivated_) - return -1; - else - result = this.enqueueHeadInternal (newItem); - - // Tell any blocked threads that the queue has a new item! - this.notEmptyCondition_.broadcast (); - return result; - } - - /** - * Dequeue and return the <MessageBlock> at the head of the - * <MessageQueue>. Note that the call will block (unless the queue - * has been deactivated). - *@return null on failure, else the <MessageBlock> at the head of queue. - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - public synchronized MessageBlock dequeueHead () throws InterruptedException - { - return this.dequeueHead (null); - } - - /** - * Dequeue and return the <MessageBlock> at the head of the - * <MessageQueue>. Note that the call when return if the queue has - * been deactivated or when the current time is later than the given - * time value. - *@param tv absolute time timeout (blocks indefinitely if null) - *@return null on failure, else the <MessageBlock> at the head of queue. - *@exception InterruptedException Interrupted while accessing queue - */ - public synchronized MessageBlock dequeueHead (TimeValue tv) - throws InterruptedException - { - MessageBlock result = null; - if (this.deactivated_) - return null; - try - { - if (tv == null) // Need to do a blocking wait - notEmptyCondition_.timedWait (); - else // Need to do a timed wait - notEmptyCondition_.timedWait (tv); - } - catch (TimeoutException e) - { - return null; - } - - // Check again if queue is still active - if (this.deactivated_) - return null; - else - result = this.dequeueHeadInternal (); - - // Tell any blocked threads that the queue has room for an item! - this.notFullCondition_.broadcast (); - return result; - } - - /** - * Check if queue is full. - *@return true if queue is full, else false. - */ - public synchronized boolean isFull () - { - return this.isFullInternal (); - } - - /** - * Check if queue is empty. - *@return true if queue is empty, else false. - */ - public synchronized boolean isEmpty () - { - return this.isEmptyInternal (); - } - - /** - * Get total number of bytes on the queue. - *@return total number number of bytes on the queue - */ - public int messageBytes () - { - return this.currentBytes_; - } - - /** - * Get total number of messages on the queue. - *@return total number number of messages on the queue - */ - public int messageCount () - { - return this.currentCount_; - } - - // = Flow control routines - - /** - * Get high watermark. - *@return high watermark - */ - public int highWaterMark () - { - return this.highWaterMark_; - } - - /** - * Set high watermark. - *@param hwm high watermark - */ - public void highWaterMark (int hwm) - { - this.highWaterMark_ = hwm; - } - - /** - * Get low watermark. - *@return low watermark - */ - public int lowWaterMark () - { - return this.lowWaterMark_; - } - - /** - * Set low watermark. - *@param lwm low watermark - */ - public void lowWaterMark (int lwm) - { - this.lowWaterMark_ = lwm; - } - - // = Activation control methods. - - /** - * Deactivate the queue and wakeup all threads waiting on the queue - * so they can continue. No messages are removed from the queue, - * however. Any other operations called until the queue is - * activated again will immediately return -1. - *@return WAS_INACTIVE if queue was inactive before the call and - * WAS_ACTIVE if queue was active before the call. - */ - public synchronized int deactivate () - { - return this.deactivateInternal (); - } - - - /** - * Reactivate the queue so that threads can enqueue and dequeue - * messages again. - *@return WAS_INACTIVE if queue was inactive before the call and - * WAS_ACTIVE if queue was active before the call. - */ - public synchronized int activate () - { - return this.activateInternal (); - } - - protected boolean isEmptyInternal () - { - // Not sure about this one!!!! - return this.currentBytes_ <= this.lowWaterMark_ && this.currentCount_ <= 0; - } - - protected boolean isFullInternal () - { - return this.currentBytes_ > this.highWaterMark_; - } - - protected int deactivateInternal () - { - int currentStatus = - this.deactivated_ ? WAS_INACTIVE : WAS_ACTIVE; - - this.notFullCondition_.broadcast (); - this.notEmptyCondition_.broadcast (); - - this.deactivated_ = true; - return currentStatus; - } - - protected int activateInternal () - { - int currentStatus = - this.deactivated_ ? WAS_INACTIVE : WAS_ACTIVE; - this.deactivated_ = false; - - return currentStatus; - } - - protected int enqueueTailInternal (MessageBlock newItem) - { - if (newItem == null) - return -1; - - // List was empty, so build a new one. - if (this.tail_ == null) - { - this.head_ = newItem; - this.tail_ = newItem; - newItem.next (null); - newItem.prev (null); - } - // Link at the end. - else - { - newItem.next (null); - this.tail_.next (newItem); - newItem.prev (this.tail_); - this.tail_ = newItem; - } - - if (newItem.msgType() != MessageType.MB_OBJECT) - { - // Make sure to count *all* the bytes in a composite message!!! - for (MessageBlock temp = newItem; - temp != null; - temp = temp.cont ()) - this.currentBytes_ += temp.size (); - } - - this.currentCount_++; - return this.currentCount_; - } - - protected int enqueueHeadInternal (MessageBlock newItem) - { - if (newItem == null) - return -1; - - newItem.prev (null); - newItem.next (this.head_); - - if (this.head_ != null) - this.head_.prev (newItem); - else - this.tail_ = newItem; - - this.head_ = newItem; - - if (newItem.msgType() != MessageType.MB_OBJECT) - { - // Make sure to count *all* the bytes in a composite message!!! - for (MessageBlock temp = newItem; - temp != null; - temp = temp.cont ()) - this.currentBytes_ += temp.size (); - } - - this.currentCount_++; - - return this.currentCount_; - } - - protected int enqueueInternal (MessageBlock newItem) - { - if (newItem == null) - return -1; - - if (this.head_ == null) - // Check for simple case of an empty queue, where all we need to - // do is insert <newItem> into the head. - return this.enqueueHeadInternal (newItem); - else - { - MessageBlock temp; - - // Figure out where the new item goes relative to its priority. - - for (temp = this.head_; - temp != null; - temp = temp.next ()) - { - if (temp.msgPriority () <= newItem.msgPriority ()) - // Break out when we've located an item that has lower - // priority that <newItem>. - break; - } - - if (temp == null) - // Check for simple case of inserting at the end of the queue, - // where all we need to do is insert <newItem> after the - // current tail. - return this.enqueueTailInternal (newItem); - else if (temp.prev () == null) - // Check for simple case of inserting at the beginning of the - // queue, where all we need to do is insert <newItem> before - // the current head. - return this.enqueueHeadInternal (newItem); - else - { - // Insert the message right before the item of equal or lower - // priority. - newItem.next (temp); - newItem.prev (temp.prev ()); - temp.prev ().next (newItem); - temp.prev (newItem); - } - } - - if (newItem.msgType() != MessageType.MB_OBJECT) - { - // Make sure to count *all* the bytes in a composite message!!! - for (MessageBlock temp = newItem; - temp != null; - temp = temp.cont ()) - this.currentBytes_ += temp.size (); - } - - this.currentCount_++; - return this.currentCount_; - } - - protected MessageBlock dequeueHeadInternal () - { - MessageBlock firstItem = this.head_; - this.head_ = this.head_.next (); - - if (this.head_ == null) - this.tail_ = null; - - if (firstItem.msgType() != MessageType.MB_OBJECT) - { - // Make sure to subtract off all of the bytes associated with this - // message. - for (MessageBlock temp = firstItem; - temp != null; - temp = temp.cont ()) - this.currentBytes_ -= temp.size (); - } - - this.currentCount_--; - return firstItem; - } - - - /** Default high watermark (16 K). */ - public final static int DEFAULT_HWM = 16 * 1024; - - /** Default low watermark. */ - public final static int DEFAULT_LWM = 0; - - /** Message queue was active before activate() or deactivate(). */ - public final static int WAS_ACTIVE = 1; - - /** Message queue was inactive before activate() or deactivate(). */ - public final static int WAS_INACTIVE = 2; - - private int highWaterMark_; - // Greatest number of bytes before blocking. - - private int lowWaterMark_; - // Lowest number of bytes before unblocking occurs. - - private boolean deactivated_; - // Indicates that the queue is inactive. - - private int currentBytes_; - // Current number of bytes in the queue. - - private int currentCount_; - // Current number of messages in the queue. - - private MessageBlock head_; - // Head of Message_Block list. - - private MessageBlock tail_; - // Tail of Message_Block list. - - // The Delegated Notification mechanisms. - private NotFullCondition notFullCondition_ = new NotFullCondition (this); - private NotEmptyCondition notEmptyCondition_ = new NotEmptyCondition (this); - -} diff --git a/java/src/MessageType.java b/java/src/MessageType.java deleted file mode 100644 index 62c34455854..00000000000 --- a/java/src/MessageType.java +++ /dev/null @@ -1,110 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * MessageType.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Message types used by ACE.MessageBlock. - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * Defines bit masks used to identify various types of messages. - *</blockquote> - * - *<h2>NOTES</h2> - *<blockquote> - * This class is not intended to be instantiable. - *</blockquote> - */ -public class MessageType -{ - // = Data and protocol messages (regular and priority) - /** regular data */ - public static final int MB_DATA = 0x01; - - /** protocol control */ - public static final int MB_PROTO = 0x02; - - /** regular data */ - public static final int MB_OBJECT = 0x09; - - - // = Control messages (regular and priority) - /** line break */ - public static final int MB_BREAK = 0x03; - - /** pass file pointer */ - public static final int MB_PASSFP = 0x04; - - /** post an event to an event queue */ - public static final int MB_EVENT = 0x05; - - /** generate process signal */ - public static final int MB_SIG = 0x06; - - /** ioctl; set/get params */ - public static final int MB_IOCTL = 0x07; - - /** set various stream head options */ - public static final int MB_SETOPTS = 0x08; - - - // = Control messages (high priority; go to head of queue) - /** acknowledge ioctl */ - public static final int MB_IOCACK = 0x81; - - /** negative ioctl acknowledge */ - public static final int MB_IOCNAK = 0x82; - - /** priority proto message */ - public static final int MB_PCPROTO = 0x83; - - /** generate process signal */ - public static final int MB_PCSIG = 0x84; - - /** generate read notification */ - public static final int MB_READ = 0x85; - - /** flush your queues */ - public static final int MB_FLUSH = 0x86; - - /** stop transmission immediately */ - public static final int MB_STOP = 0x87; - - /** restart transmission after stop */ - public static final int MB_START = 0x88; - - /** line disconnect */ - public static final int MB_HANGUP = 0x89; - - /** fatal error used to set u.u_error */ - public static final int MB_ERROR = 0x8a; - - /** post an event to an event queue */ - public static final int MB_PCEVENT = 0x8b; - - - /** Normal priority messages */ - public static final int MB_NORMAL = 0x00; - - /** High priority control messages */ - public static final int MB_PRIORITY = 0x80; - - // Default private constructor to avoid instantiation - private MessageType () - { - } -} - diff --git a/java/src/Module.java b/java/src/Module.java deleted file mode 100644 index 6eb56bcbf43..00000000000 --- a/java/src/Module.java +++ /dev/null @@ -1,253 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * Module.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Provides an abstraction for managing a bi-directional flow of - * messages. - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * This is based on the Module concept in System V Streams, - * which contains a pair of Tasks, one for handling upstream - * processing, one for handling downstream processing. - *</blockquote> - */ -public class Module -{ - // = Initialization and termination methods. - - /** - * Create an empty Module. - */ - public Module () - { - // Do nothing... - this.name ("<unknown>"); - } - - /* - * Create an initialized module. - *@param modName identity of the module. - *@param writerQ writer task of the module. - *@param readerQ reader task of the module. - *@param flags Module flags - */ - public Module (String modName, - Task writerQ, - Task readerQ, - Object flags) - { - this.open (modName, writerQ, readerQ, flags); - } - - /* - * Create an initialized module. - *@param modName identity of the module. - *@param writerQ writer task of the module. - *@param readerQ reader task of the module. - *@param flags Module flags - */ - public void open (String modName, - Task writerQ, - Task readerQ, - Object arg) - { - this.name (modName); - this.arg_ = arg; - - if (writerQ == null) - writerQ = new ThruTask (); - if (readerQ == null) - readerQ = new ThruTask (); - - this.reader (readerQ); - this.writer (writerQ); - - // Setup back pointers. - readerQ.module (this); - writerQ.module (this); - } - - - /* - * Set the writer task. - *@param q the writer task - */ - public void writer (Task q) - { - this.qPair_[1] = q; - if (q != null) - q.flags (ACE.CLR_BITS (q.flags (), TaskFlags.ACE_READER)); - } - - /* - * Set the reader task. - *@param q the reader task - */ - public void reader (Task q) - { - this.qPair_[0] = q; - if (q != null) - q.flags (ACE.SET_BITS (q.flags (), TaskFlags.ACE_READER)); - } - - /* - * Link this Module on top of Module. - *@param m the module to link this on top of. - */ - public void link (Module m) - { - this.next (m); - this.writer ().next (m.writer ()); - m.reader ().next (this.reader ()); - } - - /* - * Set and get pointer to sibling Task in Module. - *@param orig the task to get the sibling for - *@return the sibling of the task - */ - public Task sibling (Task orig) - { - if (this.qPair_[0] == orig) - return this.qPair_[1]; - else if (this.qPair_[1] == orig) - return this.qPair_[0]; - else - return null; - } - - /* - * Close down the module and its tasks. - *@param flags Module flags - *@return 0 on success, -1 on failure - */ - public int close (long flags) - { - Task readerQ = this.reader (); - Task writerQ = this.writer (); - int result = 0; - - if (readerQ != null) - { - if (readerQ.close (flags) == -1) - result = -1; - readerQ.flush (flags); - readerQ.next (null); - } - - if (writerQ != null) - { - if (writerQ.close (flags) == -1) - result = -1; - writerQ.flush (flags); - writerQ.next (null); - } - - return result; - } - - /* - * Get the argument passed to tasks. - *@return the argument passed to tasks. - */ - public Object arg () - { - return this.arg_; - } - - /* - * Set the argument to be passed to tasks. - *@param a the argument to be passed to tasks. - */ - public void arg (Object a) - { - this.arg_ = a; - } - - /* - * Get the name of the module. - *@return the name of the module. - */ - public String name () - { - return this.name_; - } - - /* - * Set the name of the module. - *@param n the name of the module. - */ - public void name (String n) - { - this.name_ = n; - } - - /* - * Get the writer task of the module. - *@return the writer task of the module. - */ - public Task writer () - { - return this.qPair_[1]; - } - - /* - * Get the reader task of the module. - *@return the reader task of the module. - */ - public Task reader () - { - return this.qPair_[0]; - } - - /* - * Get the next pointer to the module above in the stream. - *@return the next pointer to the module above in the stream. - */ - public Module next () - { - return this.next_; - } - - /* - * Set the next pointer to the module above in the stream. - *@param m the next pointer to the module above in the stream. - */ - public void next (Module m) - { - this.next_ = m; - } - - private Task qPair_[] = new Task[2]; - // Pair of Tasks that form the "read-side" and "write-side" of the - // ACE_Module partitioning. - - private String name_ = null; - // Name of the ACE_Module. - - private Module next_; - // Next ACE_Module in the stack. - - private Object arg_; - // Argument passed through to the reader and writer task when they - // are opened. - -} - diff --git a/java/src/Mutex.java b/java/src/Mutex.java deleted file mode 100644 index 1b796062ae8..00000000000 --- a/java/src/Mutex.java +++ /dev/null @@ -1,109 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * Mutex.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Concurrency; - -import java.util.*; -import JACE.ASX.*; - -class TimedWaitMAdapter extends TimedWait -{ - TimedWaitMAdapter (Object obj) - { - super (obj); - } - - // Check to see if the lock is currently held or not. - public boolean condition () - { - return !this.inUse_; - } - - // Acquire/Release the lock - public void inUse (boolean c) - { - this.inUse_ = c; - } - - private boolean inUse_ = false; - // The actual lock -} - - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Value added abstraction for mutex variable creation. - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * A timed mutex, <em>i.e.</em> a mutex whose operations do not - * block forever and can <q>time out</q>. - *</blockquote> - */ -public class Mutex -{ - /** - * Acquire the mutex. Note that this will block. - *@exception InterruptedException exception during wait - */ - public synchronized void acquire () throws InterruptedException - { - this.monitor_.timedWait (); - this.monitor_.inUse (true); - setOwner(); - } - - /** - * Acquire the mutex. - * Throws a TimeoutException if the mutex isn't acquired before the - * given absolute time timeout. - *@param tv time (TimeValue) to wait until before throwing a - * TimeoutException (unless the mutex is acquired before that) - *@exception TimeoutException wait timed out exception - *@exception InterruptedException exception during wait - */ - public synchronized void acquire (TimeValue tv) throws - TimeoutException, InterruptedException - { - this.monitor_.timedWait (tv); - this.monitor_.inUse (true); - setOwner(); - } - - /** - * Release the mutex. This is safe for non-owners to call. - */ - public synchronized void release () - { - if (isOwner()) { - this.monitor_.inUse (false); - this.monitor_.signal (); - } - } - - private TimedWaitMAdapter monitor_ = new TimedWaitMAdapter (this); - // The monitor (adapter) to wait on - - // Keep track of the owner. Allow subclasses to redefine this - // behavior - private Object owner_ = null; - - protected void setOwner() { - this.owner_ = Thread.currentThread().toString(); - } - - protected boolean isOwner() { - return Thread.currentThread().toString().equals(this.owner_); - } -} diff --git a/java/src/OS.java b/java/src/OS.java deleted file mode 100644 index c17fd6d07f2..00000000000 --- a/java/src/OS.java +++ /dev/null @@ -1,72 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.OS - * - * = FILENAME - * OS.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.OS; - -import java.util.StringTokenizer; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Methods to extend the capabilities of the Java runtime system. - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * This non-instantiable class contains little <q>utility functions</q> - * that should have been in Java to begin with :-) - *</blockquote> - */ -public class OS -{ - /** - * Create an array of Strings from a single String using <delim> as - * the delimiter. - *@param args the String to break up to make an array of Strings - *@param delim the delimeter to use to break the String up - *@return an array containing the original String broken up - */ - public static String [] createStringArray (String args, String delim) - { - // First determine the number of arguments - int count = 0; - StringTokenizer tokens = new StringTokenizer (args, delim); - while (tokens.hasMoreTokens ()) - { - tokens.nextToken (); - count++; - } - if (count == 0) - return null; - - // Create argument array - String [] argArray = new String [count]; - int index = 0; - tokens = new StringTokenizer (args, " "); - while (tokens.hasMoreTokens ()) - { - argArray [index] = tokens.nextToken (); - index++; - } - - // Assert index == count - if (index != count) - return null; - else - return argArray; - } - - // Default private constructor to avoid instantiation - private OS () - { - } -} diff --git a/java/src/ParseNode.java b/java/src/ParseNode.java deleted file mode 100644 index cdf8bb57955..00000000000 --- a/java/src/ParseNode.java +++ /dev/null @@ -1,69 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ParseNode.java - * - * Base class for the data types used in the parse tree for adjusting - * services. Things like SuspendNode extend this. - * - *@author Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import JACE.OS.*; - -public class ParseNode -{ - /** - * Constructor - * - */ - public ParseNode () - { - this.name_ = new String("Uninitialized"); - } - - /** - * Initialize the service (subclasses - * may do more than set the name) - */ - public void init (String name) - { - this.name_ = name; - } - - /** - * Subclasses override to do real work, usually - * initiating a service or modifying one - */ - public void apply () - { - // Empty - } - - /** - * Retrive the service name - */ - public String name() - { - return this.name_; - } - - /** - * Set the name of the service - */ - public void name(String newName) - { - this.name_ = newName; - } - - String name_; -}; - - - diff --git a/java/src/ProfileTimer.java b/java/src/ProfileTimer.java deleted file mode 100644 index b7e9c908a13..00000000000 --- a/java/src/ProfileTimer.java +++ /dev/null @@ -1,48 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Timers - * - * = FILENAME - * ProfileTimer.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Timers; - -/** - * <hr> - * <p><b>TITLE</b><br> - * A Java wrapper for interval timers. - */ -public class ProfileTimer -{ - /** - * Start the timer. - */ - public void start () - { - this.startTime_ = java.lang.System.currentTimeMillis (); - } - - /** - * Stop the timer. - */ - public void stop () - { - this.stopTime_ = java.lang.System.currentTimeMillis (); - } - - /** - * Determine elapsed time between start and stop. - *@return Total elapsed time (stop - start). - */ - public long elapsedTime () - { - return this.stopTime_ - this.startTime_; - } - - private long startTime_; - private long stopTime_; -} diff --git a/java/src/README b/java/src/README deleted file mode 100644 index 1882de26380..00000000000 --- a/java/src/README +++ /dev/null @@ -1,19 +0,0 @@ -$Id$ - -Make sure to update the environment variable CLASSPATH to include the -path to where java/classes/ is located. The Java compiler uses this to -find classes when resolving dependencies. - -As with the C++ version of ACE, the Makefile requires GNU Make. - -Suggestions are welcome to: - -Douglas C. Schmidt (schmidt@cs.wustl.edu) -Everett Anderson (eea1@cs.wustl.edu) -Darrell Brunsch (brunsch@cs.wustl.edu) -Prashant Jain (pjain@cs.wustl.edu) - -The documentation for Java ACE has not been included in the release -but can be automatically generated by typing "make doc" in the src -directory. Note that the gif images needed by the documentation ARE -included in the release. diff --git a/java/src/RWMutex.java b/java/src/RWMutex.java deleted file mode 100644 index 1161d9a8618..00000000000 --- a/java/src/RWMutex.java +++ /dev/null @@ -1,174 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * RWMutex.java - * - *@author Ross Dargahi (rossd@krinfo.com), Prashant Jain, and Irfan Pyarali - * - *************************************************/ - -package JACE.Concurrency; - -import JACE.OS.*; - -/******************************************************************************* -* <HR> -* <B> Description </B> -* <BR> -* This class increments a read/write lock. A read/write lock allows multiple -* readers or a single writer to access the guarded element. -* This implementation is based on the C++ version of ACE. -* </PRE><P><HR> -* <B> Notes </B> -* <UL> -* <LI> This class does not support recursive semantics -* </UL> -*******************************************************************************/ -public class RWMutex -{ - /** - * Acquires the write lock - * @exception InterruptedException Lock acquisition interrupted - **/ - public void acquire() - throws InterruptedException - { - acquireWrite(); - } - - /** - * Acquires the read lock - * @exception InterruptedException Lock acquisition interrupted - **/ - public void acquireRead() - throws InterruptedException - { - // make sure we start with no exception - InterruptedException exception_ = null; - - // grab lock - lock_.acquire (); - - // Give preference to writers who are waiting. - while (referenceCount_ < 0 || numberOfWaitingWriters_ > 0) - { - numberOfWaitingReaders_++; - try - { - waitingReaders_.Wait (); - } - catch (InterruptedException exception) - { - // cache exception - exception_ = exception; - } - numberOfWaitingReaders_--; - } - - if (exception_ == null) - // No errors - referenceCount_++; - - // make sure this is released in all cases - lock_.release (); - - if (exception_ != null) - // error: propogate - throw exception_; - } - - /** - * Acquires the write lock - * @exception InterruptedException Lock acquisition interrupted - **/ - public void acquireWrite() - throws InterruptedException - { - // make sure we start with no exception - InterruptedException exception_ = null; - - // grab lock - lock_.acquire (); - - // Give preference to writers who are waiting. - while (referenceCount_ != 0) - { - numberOfWaitingWriters_++; - try - { - waitingWriters_.Wait (); - } - catch (InterruptedException exception) - { - // cache exception - exception_ = exception; - } - numberOfWaitingWriters_--; - } - - if (exception_ == null) - // No errors - referenceCount_ = -1; - - // make sure this is released in all cases - lock_.release (); - - if (exception_ != null) - // error: propogate - throw exception_; - } - - /** - * Release held lock - * @exception InterruptedException Lock acquisition interrupted - **/ - public void release() - throws InterruptedException - { - lock_.acquire (); - - // Releasing a reader. - if (referenceCount_ > 0) - referenceCount_--; - else - // Releasing a writer. - if (referenceCount_ == -1) - referenceCount_ = 0; - - // Give preference to writers over readers... - if (numberOfWaitingWriters_ > 0) - { - waitingWriters_.signal (); - } - else if (numberOfWaitingReaders_ > 0) - { - waitingReaders_.broadcast (); - } - - - lock_.release (); - } - - private Mutex lock_ = new Mutex (); - // Serialize access to internal state. - - private Condition waitingReaders_ = new Condition (lock_); - // Reader threads waiting to acquire the lock. - - private int numberOfWaitingReaders_; - // Number of waiting readers. - - private Condition waitingWriters_ = new Condition (lock_); - // Writer threads waiting to acquire the lock. - - private int numberOfWaitingWriters_ = 0; - // Number of waiting writers. - - private int referenceCount_ = 0; - // Value is -1 if writer has the lock, else this keeps track of the - // number of readers holding the lock. -} - diff --git a/java/src/RemoveNode.java b/java/src/RemoveNode.java deleted file mode 100644 index b613d981ee5..00000000000 --- a/java/src/RemoveNode.java +++ /dev/null @@ -1,35 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * RemoveNode.java - * - * Used when a service is specified to be removed based on a line - * in a service configurator file. Note: Make sure to call the - * prepareToReload method in ServiceConfig before reloading the - * service that is being removed. - * - *@author Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import JACE.OS.*; - -class RemoveNode extends ParseNode -{ - public RemoveNode () - { - } - - public void apply () - { - ACE.DEBUG("RemoveNode apply"); - - if (JACE.ServiceConfigurator.ServiceConfig.remove(this.name_) == -1) - ACE.ERROR("Error removing " + this.name_); - } -}; diff --git a/java/src/ResumeNode.java b/java/src/ResumeNode.java deleted file mode 100644 index 055c19da408..00000000000 --- a/java/src/ResumeNode.java +++ /dev/null @@ -1,34 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ResumeNode.java - * - * Used when a service is specified to be resumed based on a line - * in a service configurator file. The actual implementation of the - * service being resumed does the work. - * - *@author Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import JACE.OS.*; - -class ResumeNode extends ParseNode -{ - public ResumeNode () - { - } - - public void apply () - { - ACE.DEBUG("ResumeNode apply: " + this.name_); - - if (JACE.ServiceConfigurator.ServiceConfig.resume(this.name_) == -1) - ACE.ERROR("Error resuming " + this.name_); - } -}; diff --git a/java/src/SOCKAcceptor.java b/java/src/SOCKAcceptor.java deleted file mode 100644 index f94d037d462..00000000000 --- a/java/src/SOCKAcceptor.java +++ /dev/null @@ -1,115 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.SOCK_SAP - * - * = FILENAME - * SOCKAcceptor.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.SOCK_SAP; - -import java.io.*; -import java.net.*; -import JACE.OS.*; - -/** - * <hr> - * <p><b>TITLE</b><br> - * Defines the format and interface for an ACE.SOCKAcceptor. - */ -public class SOCKAcceptor -{ - // = Initialization - - /** - * Create a SOCKAcceptor. Do nothing constructor. Allows user to - * call open() later and pass in the port number. - */ - public SOCKAcceptor () - { - } - - /** - * Create a SOCKAcceptor. - *@param port port number where the server will listen for connections - */ - public SOCKAcceptor (int port) throws IOException - { - this.open (port); - } - - /** - * Create socket to listen for connections on. - *@param port port number where the server will listen for connections - */ - public void open(int port) throws IOException - { - // Close old socket (if there is one) - this.close (); - - // Create a new server socket - this.listenSocket_ = new ServerSocket (port); - // ACE.DEBUG ("Server listening on port " + port); - } - - /** - * Close the socket and do any necessary cleanup. - */ - public void close () throws IOException - { - if (this.listenSocket_ != null) - { - this.listenSocket_.close (); - this.listenSocket_ = null; - } - } - - /** - * Accept a connection. The streams are set when the method returns. - *@param sockStream SOCK Stream to use for the connection - */ - public void accept (SOCKStream sockStream) throws SocketException, IOException - { - // Block in accept. Returns when a connection shows up and sets - // the streams - sockStream.socket (this.listenSocket_.accept ()); - ACE.DEBUG ("Accepted connection from " + - sockStream.socket ().getInetAddress ()); - } - - /** - * Get the underlying listen socket. - *@return the underlying listen socket - */ - public ServerSocket listenSocket () - { - return this.listenSocket_; - } - - /** - * Set the underlying listen socket. - *@param s the underlying listen socket - */ - public void listenSocket (ServerSocket s) - { - this.listenSocket_ = s; - } - - /** - * Clean up when the garbage collector gets run (if at all). Note - * that there is no guarantee that finalize () will get called. - *@exception Throwable (Probably IOException from the socket level) - */ - protected void finalize () throws Throwable - { - super.finalize (); - this.close (); - } - - // Socket on which listen for connections (by default initialized to - // null) - private ServerSocket listenSocket_; -} diff --git a/java/src/SOCKConnector.java b/java/src/SOCKConnector.java deleted file mode 100644 index 98dfcaf6b3d..00000000000 --- a/java/src/SOCKConnector.java +++ /dev/null @@ -1,75 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.SOCK_SAP - * - * = FILENAME - * SOCKConnector.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.SOCK_SAP; - -import java.io.*; -import java.net.*; -import JACE.OS.*; - -/** - * <hr> - * <p><b>TITLE</b><br> - * Defines an active connection factory for the socket wrappers. - */ -public class SOCKConnector -{ - // = Initialization - - /** - * Create a SOCKConnector. Do nothing constructor. Allows user to - * call connect() later. - */ - public SOCKConnector () - { - // Do nothing constructor - } - - /** - * Create a SOCKConnector and connect to the server. - *@param sockStream SOCK Stream to use for the connection - *@param hostname hostname of the server - *@param port port number to connect with server at - */ - public SOCKConnector (SOCKStream sockStream, - String hostname, - int port) throws SocketException, IOException - { - this.connect (sockStream, - hostname, - port); - } - - /** - * Connect to the server. - *@param sockStream SOCK Stream to use for the connection - *@param hostname hostname of the server - *@param port port number to connect with server at - */ - public void connect (SOCKStream sockStream, - String hostname, - int port) throws SocketException, IOException - { - sockStream.socket (new Socket (hostname, port)); - } - - /** - * Connect to the server. - *@param sockStream SOCK Stream to use for the connection - *@param addr INETAddr instance specifying host/port - */ - public void connect (SOCKStream sockStream, - INETAddr addr) throws SocketException, IOException - { - sockStream.socket (new Socket (addr.getHostName(), - addr.getPortNumber())); - } -} diff --git a/java/src/SOCKStream.java b/java/src/SOCKStream.java deleted file mode 100644 index f255b7bc44a..00000000000 --- a/java/src/SOCKStream.java +++ /dev/null @@ -1,218 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.SOCK_SAP - * - * = FILENAME - * SOCKStream.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.SOCK_SAP; - -import java.io.*; -import java.net.*; -import JACE.OS.*; - -/** - * <hr> - * <p><b>TITLE</b><br> - * Defines the methods in the ACE.SOCKStream abstraction. - * - * <p><b>DESCRIPTION</b><br> - * This adds additional wrapper methods atop the java Socket class. - */ -public class SOCKStream -{ - /** - * Create a default SOCK Stream. Do nothing constructor. - */ - public SOCKStream () - { - } - - /** - * Create a SOCK Stream. - *@param s Socket to initialize SOCK Stream with. - */ - public SOCKStream (Socket s) throws IOException - { - this.socket (s); - } - - /** - * Set the socket and the underlying streams. - *@param s Socket associated with the SOCK Stream. - */ - public void socket (Socket s) throws IOException - { - this.socket_ = s; - // Note that if s is not a valid socket or is null, the - // following calls will throw exceptions - - // Create buffered, platform independent byte streams. This hasn't been switched - // to the newer character streams since the change would break cross talk with - // non-Java sockets. - - this.iStream_ = new DataInputStream(new BufferedInputStream(s.getInputStream())); - - this.oStream_ = new DataOutputStream(new BufferedOutputStream(s.getOutputStream())); - } - - /* Get the underlying Socket. - *@return the underlying socket - */ - public Socket socket () - { - return this.socket_; - } - - /** - * Close the streams and the underlying socket. - */ - public void close () throws IOException - { - if (this.socket_ != null) - this.socket_.close (); - this.socket_ = null; - } - - // = The following send and recv methods are overloaded to provide a - // flexible interface - - /** - * Send a StringBuffer. Note that the method blocks. - *@param s the StringBuffer to send - *@return the length of the StringBuffer - */ - public int send (StringBuffer s) throws IOException - { - // Get the data out - String buf = s.toString (); - - //this.oStream_.println(buf); - this.oStream_.writeChars(buf.toString()); - this.oStream_.writeChar('\n'); - this.oStream_.flush (); - - return buf.length (); - } - - /** - * Send a String. Note that the method blocks. - *@param s the String to send - *@return the length of the String - */ - public int send (String s) throws IOException - { - this.oStream_.writeChars(s); - this.oStream_.writeChar('\n'); - - //this.oStream_.println(s); - this.oStream_.flush(); - - return s.length (); - } - - /** - * Send an array of bytes. Note that the method blocks. - *@param b array of bytes to send - *@param offset offset into the byte array to start sending from - *@param length number of bytes to send - *@return number of bytes sent - */ - public int sendN (byte[] b, int offset, int length) throws IOException - { - this.oStream_.write (b, offset, length); - this.oStream_.flush (); - return length; - } - - /** - * Receive data and append it to the StringBuffer that was passed - * in. Note that the method blocks. - *@param s the StringBuffer to append the result of the recv to - *@return the length of the String received - */ - public int recv (StringBuffer s) throws IOException - { - int len = 0; - char in = (char)this.iStream_.readByte(); - - while (in != '\n') { - s.append(in); - in = (char)this.iStream_.readByte(); - len++; - } - - return len; - } - - /** - * Receive an array of characters. This method blocks until either - * all the bytes are read, the end of the stream is detected, or - * an exception is thrown. - *@param b byte array to receive the data in - *@param offset the start offset of the data in the byte array. - *@param n number of bytes to receive - *@return n - */ - public int recvN (byte[] b, int offset, int n) throws IOException - { - this.iStream_.readFully (b, offset, n); - return n; - } - - /** - * Set the underlying input stream. - *@param iStream the input stream - */ - public void inputStream (InputStream iStream) - { - this.iStream_ = new DataInputStream(new BufferedInputStream(iStream)); - } - - /** - * Get the underlying input stream. - *@return the underlying input stream - */ - public InputStream inputStream () - { - return this.iStream_; - } - - /** - * Set the underlying output stream. - *@param iStream the output stream - */ - public void outputStream (OutputStream oStream) - { - this.oStream_ = new DataOutputStream(new BufferedOutputStream(oStream)); - } - - /** - * Get the underlying output stream. - *@return the underlying output stream - */ - public OutputStream outputStream () - { - return this.oStream_; - } - - /** - * Cleanup when the SOCK Stream is garbage collected. - *@exception Throwable (Probably IOException from the socket level) - */ - protected void finalize () throws Throwable - { - super.finalize (); - this.close (); - } - - private Socket socket_; - - // = The input and output streams (by default null) - private DataInputStream iStream_; - private DataOutputStream oStream_; -} diff --git a/java/src/Semaphore.java b/java/src/Semaphore.java deleted file mode 100644 index 6c5427bb0c0..00000000000 --- a/java/src/Semaphore.java +++ /dev/null @@ -1,103 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * Semaphore.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Concurrency; - -import java.util.*; -import JACE.ASX.*; - -class TimedWaitSAdapter extends JACE.ASX.TimedWait -{ - TimedWaitSAdapter (Object obj) - { - super (obj); - } - - // Check to see if there are any semaphores available. - public boolean condition () - { - return this.count_ > 0; - } - - // Increment the count by one - public void increment () - { - this.count_++; - } - - // Decrement the count by one - public void decrement () - { - this.count_--; - } - - // Set the count - public void count (int c) - { - this.count_ = c; - } - - private int count_ = 0; -} - -/** - * <hr> - * <h2>SYNOPSIS</h2> - * Implementation of Dijkstra's counting semaphore in java. - */ -public class Semaphore -{ - /** - * Create a Semaphore. - *@param count semaphore count - */ - public Semaphore (int c) - { - this.monitor_.count (c); - } - - /** - * Acquire the Semaphore. Note that this will block. - *@exception InterruptedException exception during wait - */ - public synchronized void acquire () throws InterruptedException - { - this.monitor_.timedWait (); - this.monitor_.decrement (); - } - - /** - * Acquire the Semaphore. Throws a TimeoutException if the semaphore - * isn't acquired before the given absolute time. - *@param tv time (TimeValue) to wait until before throwing a - * TimeoutException (unless the semaphore is acquired before that) - *@exception TimeoutException wait timed out exception - *@exception InterruptedException exception during wait - */ - public synchronized void acquire (TimeValue tv) - throws JACE.ASX.TimeoutException, InterruptedException - { - this.monitor_.timedWait (tv); - this.monitor_.decrement (); - } - - /** - * Release the Semaphore. - */ - public synchronized void release () - { - this.monitor_.increment (); - this.monitor_.signal (); - } - - private TimedWaitSAdapter monitor_ = new TimedWaitSAdapter (this); - // The monitor (adapter) to wait on -} diff --git a/java/src/ServiceConfig.java b/java/src/ServiceConfig.java deleted file mode 100644 index e749076137b..00000000000 --- a/java/src/ServiceConfig.java +++ /dev/null @@ -1,375 +0,0 @@ - /************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ServiceConfig.java - * - * Services can be suspended, resumed, removed, and reloaded. Reloading requires a - * call to prepareForReload method after removing a service (done in remove()). You can't access - * the ServiceObjects that are loaded directly -- anything loaded with a class loader - * must be wrapped and have its methods called via reflection. This is because a - * loaded class doesn't exist in the same space as one loaded with the system loader. - * - * - *@author Prashant Jain, Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import java.util.*; -import java.net.*; -import JACE.OS.*; -import JACE.Misc.*; - -/** - * <hr> - * <p><b>TITLE</b><br> - * Provide the base class that supplies common server daemon - * operations. Also provides a global point for interacting with - * the service repository. - */ -public class ServiceConfig -{ - /** Begins the process of loading a service configurator file: - * parses the command line and calls processDirectives - * - *@exception FileNotFoundException Couldn't find service config file - *@exception IOException Problem reading or parsing - *@exception ClassNotFoundException Couldn't find a certain class - *@exception IllegalAccessException Inappropriate method call on a class - *@exception InstantiationException Couldn't create a certain class instance - */ - public static int open (String [] args) throws FileNotFoundException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException - { - // Parse the command line - ServiceConfig.parseArgs (args); - - // Create a repository and class loader - if (ServiceConfig.svcRep_ == null) - ServiceConfig.svcRep_ = new ServiceRepository (); - if (ServiceConfig.loader_ == null) - ServiceConfig.loader_ = new ServiceLoader(); - - return ServiceConfig.processDirectives (); - - } - - /** Parses the command line - * Valid command line options: - * -b Run as a daemon (not implemented yet) - * -d Debug mode - * -n No defaults - * -f <filename> Load services in the given file [see below for info] - * - */ - protected static void parseArgs (String [] args) - { - GetOpt getopt = new GetOpt (args, "bdnf:"); - for (int c; (c = getopt.next ()) != -1; ) - switch (c) - { - case 'b': - // Note: not supported yet! - ServiceConfig.beADaemon_ = true; - break; - case 'd': - ServiceConfig.debug_ = true; - break; - case 'n': - ServiceConfig.noDefaults_ = true; - break; - case 'f': - ServiceConfig.serviceConfigFile_ = getopt.optarg (); - break; - default: - ACE.ERROR ((char ) c + " is not a ServiceConfig option"); - break; - } - } - - /** Called by ParseNode subclass - * Asks the Service Repository to spend a service - */ - public static int suspend (String name) - { - return svcRep_.suspend(name); - } - - /** Called by ParseNode subclass - * Asks the Service Repository to resume a service - */ - public static int resume (String name) - { - return svcRep_.resume(name); - } - - /** Called by ParseNode subclass - * Asks the Service Repository to remove a service, also calls - * prepareForReload so the user doesn't have to. - */ - public static int remove (String name) - { - int result = svcRep_.remove(name); - - prepareForReload(); - - return result; - } - - /** Should be called before the user wants to reload - * a service. This calls garbage collection to - * (hopefully) obliterate the names of any unused - * service classes, and creates a new instance - * of the ClassLoader so there won't be problems - * reloading. - */ - public static void prepareForReload() - { - ServiceConfig.loader_ = new ServiceLoader(); - - System.gc(); - - } - - /** - * Parse a service configurator file, creating classes as necessary - * - * This is getting complicated, but there were too many installation problems when using - * CUP and JLex to merit developing a grammar. - * - * Current formats: - * - * load <Service Name> <Full Class Name> Service_Object "<argument list>" - * - * resume <Service Name> - * suspend <Service Name> - * remove <Service Name> - * - *@exception FileNotFoundException Couldn't find the file (default "svc.conf") - *@exception IOException Problem reading/parsing - *@exception ClassNotFoundException Couldn't find a certain class - *@exception IllegalAccessException Inappropriate method call - *@exception InstantiationException Couldn't create a class instance - */ - protected static int processDirectives () throws FileNotFoundException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException - { - if (ServiceConfig.serviceConfigFile_ == null) - ServiceConfig.serviceConfigFile_ = "svc.conf"; - - ACE.DEBUG("Processing directives in file " + ServiceConfig.serviceConfigFile_); - - File configFile = new File (ServiceConfig.serviceConfigFile_); - - // Check if file exists and is a normal file - if (!configFile.exists () || !configFile.isFile ()) - throw new FileNotFoundException ("File " + ServiceConfig.serviceConfigFile_ + " not found"); - - // Check if the file is readable - if (!configFile.canRead ()) - throw new IOException ("File " + ServiceConfig.serviceConfigFile_ + " not readable"); - - // Set up the stream - FileInputStream fileIn = new FileInputStream (configFile); - - // Parse the file - Reader r = new BufferedReader(new InputStreamReader(fileIn)); - StreamTokenizer in = new StreamTokenizer (r); - - // Set '#' as comment character to be ignored and set '/' as - // ordinary character (was original comment character) - // in.commentChar ('#'); - in.ordinaryChar ('/'); - - // Set characters in ASCII range 33 to 47, ASCII range 91 to 96, - // and ASCII range 123 to 126 as ordinary characters - in.wordChars ('!', '/'); // ASCII range 33 to 47 - in.wordChars (':', '@'); // ASCII range 58 to 64 - in.wordChars ('[', '`'); // ASCII range 91 to 96 - in.wordChars ('{', '~'); // ASCII range 123 to 126 - - String commandName = null; - String serviceName = null; - String className = null; - String classType = null; - String args = null; - // Create a state machine - int state = ServiceConfig.COMMAND_NAME; - - // The apply() method on ParseNode starts the process of actually executing the - // desired action (suspend, load, etc) - ParseNode result = null; - - while (in.nextToken () != StreamTokenizer.TT_EOF) - { - switch (state) - { - case ServiceConfig.COMMAND_NAME: - if (in.ttype == StreamTokenizer.TT_WORD) { - commandName = in.sval; - - // **** This should be changed so that instantiation is only done - // when we find out the type (ServiceObject or something else) a few - // words later. Right now it works because we only have ServiceObjects - // to load. - if (commandName.equals("load")) - result = new AddServiceObjectNode(); - else - if (commandName.equals("remove")) - result = new RemoveNode(); - else - if (commandName.equals("suspend")) - result = new SuspendNode(); - else - if (commandName.equals("resume")) - result = new ResumeNode(); - else - throw new IOException ("COMMAND NAME missing or invalid: " + commandName); - - ACE.DEBUG("Command node type: " + ((Object)result).getClass().getName()); - - - } else - throw new IOException ("Illegal COMMAND NAME argument in file " + ServiceConfig.serviceConfigFile_); - state = ServiceConfig.SERVICE_NAME; - break; - case ServiceConfig.SERVICE_NAME: - if (in.ttype == StreamTokenizer.TT_WORD) - serviceName = in.sval; - else - throw new IOException ("Illegal SERVICE NAME argument in file " + ServiceConfig.serviceConfigFile_); - - - if (!commandName.equals("load")) { - result.init(serviceName); - result.apply(); - in.whitespaceChars (' ', ' '); - state = ServiceConfig.SERVICE_NAME; - } else - state = ServiceConfig.CLASS_NAME; - break; - case ServiceConfig.CLASS_NAME: - if (in.ttype == StreamTokenizer.TT_WORD) - className = in.sval; - else - throw new IOException ("Illegal CLASS NAME argument in file " + ServiceConfig.serviceConfigFile_); - state = ServiceConfig.CLASS_TYPE; - break; - case ServiceConfig.CLASS_TYPE: - // This is only Service_Object or ServiceObject at this time - if (in.ttype == StreamTokenizer.TT_WORD) - classType = in.sval; - else - throw new IOException ("Illegal CLASS TYPE argument in file " + ServiceConfig.serviceConfigFile_); - state = ServiceConfig.ARGS; - // Set space to be an ordinary character to allow - // arguments to be parsed in - in.wordChars (' ', ' '); - break; - case ServiceConfig.ARGS: - ACE.DEBUG("Processing arguments"); - - args = new String(""); - - if (in.ttype == StreamTokenizer.TT_WORD) - { - args = in.sval; - - // If just two double quotes, there are no args - if (args.length() == 2) { - args = new String(""); - } else - args = args.substring(1, args.length() - 1); - } - - // Quick hack until more parsing necessary -- set the needed data - ((AddServiceObjectNode)result).init(serviceName, className, false); - ((AddServiceObjectNode)result).params(args); - - result.apply(); - - state = ServiceConfig.SERVICE_NAME; - // Set space back to whitespace-character to extract the - // next token - in.whitespaceChars (' ', ' '); - break; - default: - throw new IOException ("Illegal argument in file " + ServiceConfig.serviceConfigFile_); - } - } - return 0; - } - - - /** - * This is called when apply() is called on AddServiceObjectNodes. Similar - * methods could be developed for later data types (AddStreamNode, etc). This - * tries to load the ServiceObject and its classes. When trying to find info - * from the C++ files, this generates possible file paths. - */ - public static int initialize (AddServiceObjectNode son) - { - Class c = null; - - try { - - c = loader_.loadClass(son.locator(), true); - - } catch (ClassNotFoundException e) { - ACE.ERROR("Can't find class with locator: " + son.locator()); - return -1; - } - - try { - - Object service = c.newInstance(); - // Can't cast this to a ServiceObject, even though it will look just - // like one -- Java puts things loaded with a non-standard class loader - // in their own name space. The ServiceObjectRecord is a wrapper that - // gets around this by using reflection. - ServiceObjectRecord svcObjRec = new ServiceObjectRecord(service, son.name()); - - // Split the argument array up into smaller pieces - String [] argArray = OS.createStringArray (son.params(), " "); - - // Initialize the service -- start it running - svcObjRec.init(argArray); - - // Put it in the service repository - svcRep_.insert((ServiceRecord)svcObjRec); - - } catch (IllegalAccessException e) { - ACE.ERROR("Error " + e); - return -1; - } catch (InstantiationException e) { - ACE.ERROR("Error " + e); - return -1; - } - - return 0; - } - - // Set by command line options - private static boolean beADaemon_ = false; - private static boolean debug_ = false; - private static boolean noDefaults_ = false; - - public static String serviceConfigFile_ = "svc.conf"; - - private static ServiceRepository svcRep_ = null; - private static ServiceLoader loader_ = null; - - // States for the state-machine used in parsing the config file - private final static int SERVICE_NAME = 0; - private final static int CLASS_NAME = 1; - private final static int CLASS_TYPE = 2; - private final static int ARGS = 3; - private final static int COMMAND_NAME = 4; - - -} - - - diff --git a/java/src/ServiceLoader.java b/java/src/ServiceLoader.java deleted file mode 100644 index 86f15dc57c9..00000000000 --- a/java/src/ServiceLoader.java +++ /dev/null @@ -1,260 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ServiceLoader.java - * - * Implementation of a ClassLoader - * - *@author Prashant Jain, Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import java.util.*; -import java.net.*; -import JACE.OS.*; -import JACE.Misc.*; - -public class ServiceLoader extends ClassLoader -{ - /** - * Constructor - */ - public ServiceLoader () - { - super (); - this.getClassPath (); - } - - /** - * Searches the class path for a given file - * - *@param filename File name to look for - *@return Returns the absolute path to the file - * (useful for package name) - */ - public String findFileInClasspath (String filename) - { - // Checks for the given name across the classpath - StringTokenizer tokens = new StringTokenizer (this.classPath_, - this.pathSeparator_); - - while (tokens.hasMoreTokens()) - { - String fn = tokens.nextToken() + this.fileSeparator_ + filename; - - File f = new File (fn); - - if (f.exists() && f.isFile() && f.canRead()) - return new String(f.getAbsolutePath()); - } - - return null; - } - - /** - * Load a class from across the network - *@exception ClassNotFoundException Couldn't find the class - */ - public Class loadClass (URL url, boolean resolve) throws ClassNotFoundException - { - Class newClass = null; - - // Extract the name of the class from the URL - - String className = url.getFile(); - - // Remove any directory information - int idx = className.lastIndexOf("/"); - if (idx != -1) - className = className.substring(idx + 1); - - // Get rid of the class suffix - idx = className.lastIndexOf(".class"); - if (idx != -1) - className = className.substring(0, idx); - - ACE.DEBUG("The name of the class about to load is " + className); - - // Try to load it the class by reading in the bytes. - // Note that we are not catching ClassNotFoundException here - // since our caller will catch it. - try - { - URLConnection urlConnection = url.openConnection (); - - // Get the input stream associated with the URL connection and - // pipe it to a newly created DataInputStream - DataInputStream i = new DataInputStream (urlConnection.getInputStream ()); - - // Allocate a buffer big enough to hold the contents of the - // data we are about to read - byte [] buf = new byte [urlConnection.getContentLength ()]; - - // Now read all the data into the buffer - i.readFully (buf); - - newClass = defineClass (className, buf, 0, buf.length); - // ACE.DEBUG ("Loaded class: "+ name); - - // Check if we need to load other classes referred to by this class. - if (resolve) - resolveClass (newClass); - } - catch (IOException e) - { - throw new ClassNotFoundException (e.toString ()); - } - return newClass; - } - - - /** - * Load a class file: - * - * @param fn A file name WITHOUT the .class extension - * @param resolve Standard resolve flag -- user should set to true - * - * @return A Class file capable of creating quasi-useful instances - * of the loaded class. They can't exist in the normal - * Java space, though, so it's impossible to cast them - * to something useful. Use a wrapper and reflection - * as in ServiceRecords. - *@exception ClassNotFoundException Couldn't find the class - */ - public Class loadClass (String fn, boolean resolve) throws ClassNotFoundException - { - Class newClass; - - // Load built-in java classes with the system loader - if (fn.startsWith("java")) { - newClass = findSystemClass(fn); - if (newClass == null) - throw (new ClassNotFoundException()); - else - return newClass; - } - - // If given a dot separated qualified name, put it in OS path format. - // This assumes the file separator is one char - String str = new String(fn); - if (str.indexOf('.') >= 0) - str = str.replace('.', this.fileSeparator_.charAt(0)); - str = str + ".class"; - - // Search the class path for the given file name - String fullname = this.findFileInClasspath(str); - if (fullname == null) { - - // If we can't find the class file, see if the - // system can - if ((newClass = findSystemClass(fn)) != null) { - return newClass; - } else - throw (new ClassNotFoundException()); - } - - try - { - // Try to load it the class by reading in the bytes. - // Note that we are not catching ClassNotFoundException here - // since our caller will catch it. - try - { - byte[] buf = bytesForClass (fullname); - - // ***** Note ***** - // This looks inside the class file and digs up the true - // fully qualified class name. You need this to - // load the class! - String className = ClassReader.getClassName(fullname); - - if (className != null) { - ACE.DEBUG("Defining class with name: " + className); - newClass = defineClass (className, buf, 0, buf.length); - } else { - // Try it anyway - newClass = defineClass (null, buf, 0, buf.length); - - ACE.ERROR("Unknown class name"); - } - - // Check if we need to load other classes referred to by this class. - if (resolve) - resolveClass (newClass); - - } catch (ClassNotFoundException e) { - - ACE.DEBUG ("Using default loader for class: " + fn); - - if ((newClass = findSystemClass (fn)) != null) - return newClass; - else - throw (e); // Rethrow the exception - } - } - catch (IOException e) - { - throw new ClassNotFoundException (e.toString ()); - } - - return newClass; - } - - /** - * Get system properties for later use - */ - private void getClassPath () - { - // Cache system properties that are needed when trying to find a - // class file - this.classPath_ = System.getProperty ("java.class.path", "."); - this.pathSeparator_ = System.getProperty ("path.separator", ":"); - this.fileSeparator_ = System.getProperty ("file.separator", "/"); - } - - /** - * Read file into a byte array - */ - private byte[] bytesForClass (String name) throws IOException, ClassNotFoundException - { - // Set up the stream - FileInputStream in = new FileInputStream (name); - - // Get byte count - int length = in.available (); - - if (length == 0) - throw new ClassNotFoundException (name); - - // Create an array of bytes to read the file in - byte[] buf = new byte[length]; - - // Read the file - in.read (buf); - - // Return byte array - return buf; - } - - private String classPath_; - // Class path that is loaded at construction - - private String pathSeparator_; - // Platform-dependent path separator (e.g., : or ;) - - private String fileSeparator_; - // Platform-dependent file separator (e.g., / or \) - - private String context_ = null; -} - - - - - - diff --git a/java/src/ServiceObject.java b/java/src/ServiceObject.java deleted file mode 100644 index faf5a28daa4..00000000000 --- a/java/src/ServiceObject.java +++ /dev/null @@ -1,80 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ServiceObject.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import JACE.ASX.*; -import JACE.Reactor.*; - -public class ServiceObject implements EventHandler -{ - /** - * Initialize object when dynamic loading occurs. Overwrite this - * method to do anything useful. - *@return -1 (default implementation) - */ - public int init (String [] args) - { - return -1; - } - - /** - * Terminate the object. Note that an object can not be explicitly - * unloaded. Overwrite this method to do anything useful. - *@return -1 (default implementation) - */ - public int fini () - { - return -1; - } - - /** - * Get information on an active object. Overwrite this method to do - * anything useful. - *@return null (default implementation) - */ - public String info () - { - return null; - } - - /** - * Called when timer expires. Overwrite this method to do - * anything useful. - *@param tv Time Value for when timer expired - *@param obj An arbitrary object that was passed to the Timer Queue - * (Asynchronous Completion Token) - *@return -1 - */ - public int handleTimeout (TimeValue tv, Object obj) - { - return -1; - } - - /** - * Request that this service suspend activity. Overwrite this - * method to do anything useful. - */ - public int suspend () - { - return -1; - } - - /** - * Request that this service resume activity. Overwrite this - * method to do anything useful. - */ - public int resume () - { - return -1; - } -} diff --git a/java/src/ServiceObjectRecord.java b/java/src/ServiceObjectRecord.java deleted file mode 100644 index 282d4360fbf..00000000000 --- a/java/src/ServiceObjectRecord.java +++ /dev/null @@ -1,33 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ServiceObjectRecord.java - * - * Provided to show future symmetry. ServiceRecord currently - * provides all the desired behavior necessary for a record - * of a ServiceObject, but later there could be ModuleRecords, - * etc. - * - *@see JACE.ServiceConfigurator.ServiceRecord; - * - *@author Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -public class ServiceObjectRecord extends ServiceRecord -{ - public ServiceObjectRecord (Object so, String name) - { - super (so, name); - } - -}; - - - - - diff --git a/java/src/ServiceRecord.java b/java/src/ServiceRecord.java deleted file mode 100644 index e0bd75a1405..00000000000 --- a/java/src/ServiceRecord.java +++ /dev/null @@ -1,253 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ServiceRecord.java - * - * This class structure is used in the ServiceRepository. Each service - * object, module, or stream in the repository should be wrapped by a - * type of ServiceRecord. The contained object does the real work. - * - * Modules and Streams will require records with more functionality. - * - * The caller should never be allowed to access the Object within the - * record -- casting will result in a ClassCastException because of - * the problem with loading classes with a ClassLoader. To get - * around this, all the method calls are made on the Object via - * reflection. - * - *@see JACE.ServiceConfigurator.ServiceObject - *@see JACE.ServiceConfigurator.ServiceRepository - * - *@author Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import java.lang.reflect.*; -import JACE.OS.*; - -public class ServiceRecord -{ - /** - * Constructor - * - *@param service A java Object, the service - *@param name Name of this service - */ - ServiceRecord (Object service, String name) - { - this.service_ = service; - this.name_ = name; - this.suspended_ = false; - } - - /** - * Forward the call to suspend - * @return -1 error - */ - public int suspend() - { - this.setSuspend(true); - - Object result = this.invokeSimpleReflected("suspend"); - - if (result == null) - return -1; - else - return ((Integer)result).intValue(); - } - - - /** - * Forward the call to resume - * @return -1 error - */ - public int resume() - { - this.setSuspend(false); - - Object result = this.invokeSimpleReflected("resume"); - - if (result == null) - return -1; - else - return ((Integer)result).intValue(); - } - - - /** - * Initialize the service, provide the given command line args to it. - * - */ - public int init(String [] args) - { - Class types[] = new Class[1]; - if (args == null) - args = new String[0]; - - types[0] = args.getClass(); - - // Find the method we want to call - Method m; - try { - m = this.object().getClass().getMethod("init", types); - } catch (NoSuchMethodException e) { - ACE.ERROR("" + e); - return -1; - } catch (SecurityException e) { - ACE.ERROR("" + e); - return -1; - } - - Class ptypes[] = m.getParameterTypes(); - //for (int x = 0; x < ptypes.length; x++) - // System.err.println(ptypes[x].getName()); - Object params[] = new Object[1]; - - params[0] = args; - - int result = -1; - try { - result = ((Integer)m.invoke(this.object(), params)).intValue(); - } catch (IllegalAccessException e) { - ACE.ERROR("" + e); - return -1; - } catch (IllegalArgumentException e) { - ACE.ERROR("" + e); - return -1; - } catch (InvocationTargetException e) { - ACE.ERROR("init(): " + e.getTargetException()); - return -1; - } - - return result; - } - - /** - * Prepare to close it - */ - public int fini() - { - Object result = this.invokeSimpleReflected("fini"); - - if (result == null) - return -1; - else - return ((Integer)result).intValue(); - } - - /** - * Obtain information about this service - */ - public String info() - { - Object result = this.invokeSimpleReflected("info"); - - if (result == null) - return null; - else - return new String((String)result); - } - - /** Invokes the method with the given name on the ServiceObject. - * The invoked method must take no parameters for this to work. - * Could be adjusted to throw a generic exception. - */ - private Object invokeSimpleReflected(String name) - { - Method m; - - // find the desired method - try { - m = this.object().getClass().getMethod(name, null); - } catch (NoSuchMethodException e) { - ACE.ERROR("" + e); - return null; - } catch (SecurityException e) { - ACE.ERROR("" + e); - return null; - } - - // Invoke it - Object result = null; - - try { - result = m.invoke(this.object(), null); - } catch (IllegalAccessException e) { - ACE.ERROR("" + e); - } catch (IllegalArgumentException e) { - ACE.ERROR("" + e); - } catch (InvocationTargetException e) { - ACE.ERROR(name + "(): " + e.getTargetException()); - } - - return result; - } - - /** - * Accessor for the name - */ - public String name() - { - return new String(this.name_); - } - - /** Set the name of the service - */ - public void name(String name) - { - this.name_ = name; - } - - /** Is this service suspended? - */ - public boolean suspended() - { - return this.suspended_; - } - - /** Set the suspended flag - */ - void setSuspend (boolean suspended) - { - this.suspended_ = suspended; - } - - /** Accessor for the contained Object. This should - * never be available to the end user since they - * might try casting the result. - */ - Object object() - { - return this.service_; - } - - /** - * Set the contained object - */ - void object(Object service) - { - this.service_ = service; - } - - Object service_; - String name_; - boolean suspended_; -}; - - -/* -class ModuleRecord extends ServiceRecord -{ -}; - -class StreamRecord extends ServiceRecord -{ -}; -*/ - - diff --git a/java/src/ServiceRepository.java b/java/src/ServiceRepository.java deleted file mode 100644 index 4190646d213..00000000000 --- a/java/src/ServiceRepository.java +++ /dev/null @@ -1,189 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * ServiceRepository.java - * - * The service repository stores the network services, allowing them to be removed, suspended, - * resumed, etc. To reload a service, ServiceConfig.prepareForReload() must be called. This is - * already done in the ServiceConfig.remove method. - * - *@see JACE.ServiceConfigurator.ServiceRecord; - *@see JACE.ServiceConfigurator.ServiceConfig; - * - *@author Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import java.util.*; - -public class ServiceRepository -{ - /** - * Constructor - */ - public ServiceRepository () - { - this.serviceVector_ = new Vector(); - } - - /** - * Constructor - * - *@param initialSize Initial vector size for the repository - */ - public ServiceRepository (int initialSize) - { - this.serviceVector_ = new Vector (initialSize); - } - - /** - * Shut down all the services, closing them in reverse order of insertion - * - * Maybe should be called by finalize? - */ - public int close() - { - for (int i = this.size() - 1; i >= 0; i--) { - ServiceRecord rec = (ServiceRecord)this.serviceVector_.elementAt(i); - - rec.fini(); - - this.serviceVector_.removeElementAt(i); - } - - return 0; - } - - /** - * Insert a ServiceRecord into the repository. - * (If already in, calls fini() and replaces) - * - *@param srvRec ServiceRecord to add - */ - public void insert (ServiceRecord srvRec) - { - ServiceRecord alreadyIn = find(srvRec.name()); - - // Replace the service - if (alreadyIn != null) { - alreadyIn.fini(); - this.serviceVector_.removeElement(alreadyIn); - } - - this.serviceVector_.addElement(srvRec); - } - - /** - * Finds the ServiceRecord associated with a given - * service name. Note -- the user should not try to - * get a ServiceObject out of the ServiceRecord. - * Same as saying ignoreSuspended is false on the - * next method. - * - *@param name Name of the service to find - */ - public ServiceRecord find (String name) - { - return this.find(name, false); - } - - /** Return the service record for the given service. The caller - * should NOT try to access a ServiceObject (or Module or Stream) - * by taking it out of the ServiceRecord -- just make the calls - * through the record! - * - *@param name Name of the service to find - *@param ignoreSuspended Allow finding suspended services? - */ - public ServiceRecord find (String name, boolean ignoreSuspended) - { - ServiceRecord rec; - - for (int i = 0; i < this.size(); i++) { - rec = (ServiceRecord)this.serviceVector_.elementAt(i); - - if ((rec.name().equals(name)) && ((!ignoreSuspended) || (!rec.suspended()))) - return rec; - } - - return null; - } - - /** Take the given service out of the repository. This also sets the - * reference in the repository to null to ensure there are no - * hidden references to the old ServiceObject. To reload, the - * ServiceConfig.prepareToReload method must be called. This is already - * done in the ServiceConfig.remove method. - */ - public int remove (String name) - { - ServiceRecord rec = this.find(name, false); - - if (rec == null) - return -1; - - int index = this.serviceVector_.indexOf(rec); - - // Shut down the service - rec.fini(); - - // Make sure there are no hidden references left - this.serviceVector_.setElementAt(null, index); - - this.serviceVector_.removeElementAt(index); - - return 0; - } - - /** - * Resume a suspended service - *@param name Name of the service to resume - */ - public int resume (String name) - { - ServiceRecord rec = this.find(name, false); - - if (rec == null) - return -1; - - return rec.resume(); - } - - /** - * Suspend a service - *@param name Name of the service to suspend - */ - public int suspend (String name) - { - ServiceRecord rec = this.find(name, true); - - if (rec == null) - return -1; - - return rec.suspend(); - } - - /** - * Returns the number of items in the repository - */ - public int size () - { - return this.serviceVector_.size(); - } - - // Vector representation - Vector serviceVector_; -}; - - - - - - - - diff --git a/java/src/StrategyAcceptor.java b/java/src/StrategyAcceptor.java deleted file mode 100644 index d73c7b93006..00000000000 --- a/java/src/StrategyAcceptor.java +++ /dev/null @@ -1,156 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * StrategyAcceptor.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.SOCK_SAP.*; - -public class StrategyAcceptor -{ - /** - * Create an instance of StrategyAcceptor. - *@param handlerFactory Svc Handler factory that is used to create - * an instance of a Svc Handler when a connection is accepted. - */ - public StrategyAcceptor (Class handlerFactory) - { - this (handlerFactory, null, null, null); - } - - /** - * Create an instance of StrategyAcceptor. Use the creation - * strategy and the handlerFactory passed in to creae a new instance - * of the Svc Handler. - *@param handlerFactory Svc Handler factory that is used to create - * an instance of a Svc Handler when a connection is accepted. - *@param creStrategy Creation strategy to use to create a new - * instance of the Svc Handler. - *@param acceptStrategy Accept strategy to use to accept a new - * connection into the Svc Handler. - *@param activateStrategy Activate strategy to use to activate the - * instance of the Svc Handler. - */ - public StrategyAcceptor (Class handlerFactory, - CreationStrategy creStrategy, - AcceptStrategy acceptStrategy, - ActivateStrategy activateStrategy) - { - // Cache everything - this.handlerFactory_ = handlerFactory; - this.creStrategy_ = creStrategy; - this.acceptStrategy_ = acceptStrategy; - this.activateStrategy_ = activateStrategy; - } - - /** - * Initialize the Strategy Acceptor. The method creates the - * appropriate strategies as needed. - *@param port port number where the server will listen for connections - *@exception IOException Socket level error - */ - public void open (int port) throws IOException - { - if (this.creStrategy_ == null) - this.creStrategy_ = new CreationStrategy (this.handlerFactory_); - if (this.acceptStrategy_ == null) - this.acceptStrategy_ = new AcceptStrategy (port); - else - this.acceptStrategy_.open (port); - if (this.activateStrategy_ == null) - this.activateStrategy_ = new ActivateStrategy (); - } - - /** - * Accept a connection using the appropriate strategies. - * - *@exception SocketException Socket level error - *@exception InstantiationException Problem creating a handler - *@exception IllegalAccessException No strategy available - *@exception IOException Socket level error - */ - public void accept () throws SocketException, - InstantiationException, - IllegalAccessException, - IOException - { - // Create a Svc_Handler using the appropriate Creation_Strategy - SvcHandler sh = this.makeSvcHandler (); - - // Accept a connection into the Svc_Handler - this.acceptSvcHandler (sh); - - // Activate the Svc_Handler - this.activateSvcHandler (sh); - } - - /** - * Bridge method for creating a SvcHandler. The strategy for - * creating a SvcHandler is configured into the Acceptor via it's - * creStrategy_. If no strategy is passed in, the default behavior - * of this method is to use the default CreationStrategy. - *@return a new instance of the Svc Handler - *@exception InstantiationException Couldn't create SvcHandler - *@exception IllegalAccessException No strategy available - */ - protected SvcHandler makeSvcHandler () throws InstantiationException, IllegalAccessException - { - // Create a new handler for the connection - return this.creStrategy_.makeSvcHandler (); - } - - - /** - * Bridge method for accepting the new connection into the - * <SvcHandler>. The strategy for accepting into a SvcHandler is - * configured into the Acceptor via it's acceptStrategy_. If no - * strategy is passed in, the default behavior of this method is to - * use the default AcceptStrategy. - *@param sh Svc Handler in which to accept the connection - *@return result of accepting a connection using the accept strategy - *@exception SocketException Socket level error - *@exception IOException Socket level error - */ - protected int acceptSvcHandler (SvcHandler sh) throws SocketException, IOException - { - // Delegate responsibility to the appropriate strategy - return this.acceptStrategy_.acceptSvcHandler (sh); - } - - /** - * Bridge method for activating a <SvcHandler>. The strategy for - * activating a SvcHandler is configured into the Acceptor via it's - * activateStrategy_. If no strategy is passed in, the default - * behavior of this method is to use the default ActivateStrategy. - *@param sh Svc Handler to activate - *@return result of activating the Svc Handler - */ - protected int activateSvcHandler (SvcHandler sh) - { - // Delegate responsibility to the appropriate strategy - return this.activateStrategy_.activateSvcHandler (sh); - } - - // Handler class that should be instantiated when a connection is - // made with a client - private Class handlerFactory_; - - // Creation Strategy - private CreationStrategy creStrategy_; - - // Accept Strategy - private AcceptStrategy acceptStrategy_; - - // Activation Strategy - private ActivateStrategy activateStrategy_; -} diff --git a/java/src/Stream.java b/java/src/Stream.java deleted file mode 100644 index 3c67efef220..00000000000 --- a/java/src/Stream.java +++ /dev/null @@ -1,440 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * Stream.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * This class is the primary abstraction for the ASX framework. - * It is moduled after System V Stream. - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * A Stream consists of a stack of <Modules>, each of which - * contains two <Tasks>. - *</blockquote> - */ - -public class Stream -{ - - public Stream () - { - this (null, null, null); - } - - // Create a Stream consisting of <head> and <tail> as the Stream - // head and Stream tail, respectively. If these are 0 then the - // <ACE_Stream_Head> and <ACE_Stream_Tail> are used, respectively. - // <arg> is the value past in to the open() methods of the tasks. - - public Stream (Object a, - Module head, - Module tail) - { - this.linkedUs_ = null; - // this.final_close_ = this.lock_; - - if (this.open (a, head, tail) == -1) - ACE.ERROR ("open" + head.name () + " " + tail.name ()); - } - - public int push (Module newTop) - { - if (this.pushModule (newTop, - this.streamHead_.next (), - this.streamHead_) == -1) - return -1; - else - return 0; - } - - // Note that the timeout tv is absolute time - public int put (MessageBlock mb, TimeValue tv) - { - return this.streamHead_.writer ().put (mb, tv); - } - - // Note that the timeout tv is absolute time - public MessageBlock get (TimeValue tv) throws InterruptedException - { - return this.streamHead_.reader ().getq (tv); - } - -// Return the "top" ACE_Module in a ACE_Stream, skipping over the -// stream_head. - - public Module top () - { - if (this.streamHead_.next () == this.streamTail_) - return null; - else - return this.streamHead_.next (); - } - -// Remove the "top" ACE_Module in a ACE_Stream, skipping over the -// stream_head. - - public int pop (long flags) - { - if (this.streamHead_.next () == this.streamTail_) - return -1; - else - { - // Skip over the ACE_Stream head. - Module top = this.streamHead_.next (); - Module newTop = top.next (); - - this.streamHead_.next (newTop); - - // Close the top ACE_Module. - - top.close (flags); - - this.streamHead_.writer ().next (newTop.writer ()); - newTop.reader ().next (this.streamHead_.reader ()); - - return 0; - } - } - -// Remove a named ACE_Module from an arbitrary place in the -// ACE_Stream. - - public int remove (String name, long flags) - { - Module prev = null; - - for (Module mod = this.streamHead_; - mod != null; mod = mod.next ()) - if (name.compareTo (mod.name ()) == 0) - { - if (prev == null) // Deleting ACE_Stream Head - this.streamHead_.link (mod.next ()); - else - prev.link (mod.next ()); - - mod.close (flags); - return 0; - } - else - prev = mod; - - return -1; - } - - public Module find (String name) - { - for (Module mod = this.streamHead_; - mod != null; - mod = mod.next ()) - if (name.compareTo (mod.name ()) == 0) - return mod; - - return null; - } - -// Actually push a module onto the stack... - - private int pushModule (Module newTop, - Module currentTop, - Module head) - { - Task ntReader = newTop.reader (); - Task ntWriter = newTop.writer (); - Task ctReader = null; - Task ctWriter = null; - - if (currentTop != null) - { - ctReader = currentTop.reader (); - ctWriter = currentTop.writer (); - ctReader.next (ntReader); - } - - ntWriter.next (ctWriter); - - if (head != null) - { - if (head != newTop) - head.link (newTop); - } - else - ntReader.next (null); - - newTop.next (currentTop); - - if (ntReader.open (newTop.arg ()) == -1) - return -1; - - if (ntWriter.open (newTop.arg ()) == -1) - return -1; - return 0; - } - - public synchronized int open (Object a, - Module head, - Module tail) - { - Task h1 = null, h2 = null; - Task t1 = null, t2 = null; - - if (head == null) - { - h1 = new StreamHead (); - h2 = new StreamHead (); - head = new Module ("ACEStreamHead", h1, h2, a); - } - - if (tail == null) - { - t1 = new StreamTail (); - t2 = new StreamTail (); - tail = new Module ("ACEStreamTail", - t1, t2, a); - } - - // Make sure *all* the allocation succeeded! - if (h1 == null || h2 == null || head == null - || t1 == null || t2 == null || tail == null) - { - // Close up! - head.close (0); - tail.close (0); - return -1; - } - - this.streamHead_ = head; - this.streamTail_ = tail; - - if (this.pushModule (this.streamTail_, - null, null) == -1) - return -1; - else if (this.pushModule (this.streamHead_, - this.streamTail_, - this.streamHead_) == -1) - return -1; - else - return 0; - } - - public synchronized int close (long flags) - { - if (this.streamHead_ != null - && this.streamTail_ != null) - { - // Don't bother checking return value here. - this.unlinkInternal (); - - int result = 0; - - // Remove and cleanup all the intermediate modules. - - while (this.streamHead_.next () != this.streamTail_) - { - if (this.pop (flags) == -1) - result = -1; - } - - // Clean up the head and tail of the stream. - if (this.streamHead_.close (flags) == -1) - result = -1; - if (this.streamTail_.close (flags) == -1) - result = -1; - - this.streamHead_ = null; - this.streamTail_ = null; - - // Tell all threads waiting on the close that we are done. - // this.final_close_.broadcast (); - return result; - } - return 0; - } - - public int control (int cmd, Object a) throws InterruptedException - { - IOCntlMsg ioc = new IOCntlMsg (cmd); - - // Create a data block that contains the user-supplied data. - MessageBlock db = - new MessageBlock (MessageType.MB_IOCTL, - null, - a); - - // Create a control block that contains the control field and a - // pointer to the data block. - MessageBlock cb = - new MessageBlock (MessageType.MB_IOCTL, - db, - (Object) ioc); - - int result = 0; - - if (this.streamHead_.writer ().put (cb, null) == -1) - result = -1; - else if ((cb = this.streamHead_.reader ().getq (null)) == null) - result = -1; - else - result = ((IOCntlMsg ) cb.obj ()).rval (); - - return result; - } - -// Link two streams together at their bottom-most Modules (i.e., the -// one just above the Stream tail). Note that all of this is premised -// on the fact that the Stream head and Stream tail are non-NULL... -// This must be called with locks held. - - private int linkInternal (Stream us) - { - this.linkedUs_ = us; - // Make sure the other side is also linked to us! - us.linkedUs_ = this; - - Module myTail = this.streamHead_; - - if (myTail == null) - return -1; - - // Locate the module just above our Stream tail. - while (myTail.next () != this.streamTail_) - myTail = myTail.next (); - - Module otherTail = us.streamHead_; - - if (otherTail == null) - return -1; - - // Locate the module just above the other Stream's tail. - while (otherTail.next () != us.streamTail_) - otherTail = otherTail.next (); - - // Reattach the pointers so that the two streams are linked! - myTail.writer ().next (otherTail.reader ()); - otherTail.writer ().next (myTail.reader ()); - return 0; - } - - public synchronized int link (Stream us) - { - return this.linkInternal (us); - } - -// Must be called with locks held... - - private int unlinkInternal () - { - // Only try to unlink if we are in fact still linked! - - if (this.linkedUs_ != null) - { - Module myTail = this.streamHead_; - - // Only relink if we still exist! - if (myTail != null) - { - // Find the module that's just before our stream tail. - while (myTail.next () != this.streamTail_) - myTail = myTail.next (); - - // Restore the writer's next() link to our tail. - myTail.writer ().next (this.streamTail_.writer ()); - } - - Module otherTail = this.linkedUs_.streamHead_; - - // Only fiddle with the other side if it in fact still remains. - if (otherTail != null) - { - while (otherTail.next () != this.linkedUs_.streamTail_) - otherTail = otherTail.next (); - - otherTail.writer ().next (this.linkedUs_.streamTail_.writer ()); - - } - - // Make sure the other side is also aware that it's been unlinked! - this.linkedUs_.linkedUs_ = null; - - this.linkedUs_ = null; - return 0; - } - else - return -1; - } - - public synchronized int unlink () - { - return this.unlinkInternal (); - } - - public void dump () - { - ACE.DEBUG ("-------- module links --------"); - - for (Module mp = this.streamHead_; ; mp = mp.next ()) - { - ACE.DEBUG ("module name = " + mp.name ()); - if (mp == this.streamTail_) - break; - } - - ACE.DEBUG ("-------- writer links --------"); - - Task tp; - - for (tp = this.streamHead_.writer (); ; tp = tp.next ()) - { - ACE.DEBUG ("writer queue name = " + tp.name ()); - tp.dump (); - ACE.DEBUG ("-------\n"); - if (tp == this.streamTail_.writer () - || (this.linkedUs_ != null && tp == this.linkedUs_.streamHead_.reader ())) - break; - } - - ACE.DEBUG ("-------- reader links --------\n"); - for (tp = this.streamTail_.reader (); ; tp = tp.next ()) - { - ACE.DEBUG ("reader queue name = " + tp.name ()); - tp.dump (); - ACE.DEBUG ("-------\n"); - if (tp == this.streamHead_.reader () - || (this.linkedUs_ != null && tp == this.linkedUs_.streamHead_.writer ())) - break; - } - } - - Module streamHead_ = null; - // Pointer to the head of the stream. - - Module streamTail_ = null; - // Pointer to the tail of the stream. - - Stream linkedUs_ = null; - // Pointer to an adjoining linked stream. - - // = Synchronization objects used for thread-safe streams. - // ACE_SYNCH_MUTEX lock_; - // Protect the stream against race conditions. - - // ACE_SYNCH_CONDITION final_close_; - // Use to tell all threads waiting on the close that we are done. - -} - - diff --git a/java/src/StreamHead.java b/java/src/StreamHead.java deleted file mode 100644 index fc4419d819e..00000000000 --- a/java/src/StreamHead.java +++ /dev/null @@ -1,127 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * StreamHead.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Standard module that acts as the head of a ustream. - *</blockquote> - */ - -public class StreamHead extends Task -{ - // Module that acts as the head of a Stream. - - public int open (Object obj) - { - return 0; - } - - public int close (long l) - { - return 0; - } - - public int svc () - { - return -1; - } - - private int control (MessageBlock mb) - { - - IOCntlMsg ioc = (IOCntlMsg) mb.obj (); - int cmd = ioc.cmd (); - - switch (cmd) - { - case IOCntlCmds.SET_LWM: - case IOCntlCmds.SET_HWM: - this.waterMarks (cmd, mb.cont ().length ()); - ioc.rval (0); - break; - default: - return 0; - } - return ioc.rval (); - } - - /* Performs canonical flushing at the ACE_Stream Head */ - - private int canonicalFlush (MessageBlock mb) - { - String s = mb.base (); - long f = (new Long (s)).longValue (); - - if ((f & TaskFlags.ACE_FLUSHR) != 0) - { - this.flush (TaskFlags.ACE_FLUSHALL); - f &= ~TaskFlags.ACE_FLUSHR; - } - if ((f & TaskFlags.ACE_FLUSHW) != 0) - return this.reply (mb, null); - return 0; - } - - // Will block forever to add the given MessageBlock - public int put (MessageBlock mb) - { - return this.put (mb, null); - } - - // tv is absolute time - public int put (MessageBlock mb, TimeValue tv) - { - int res = 0; - if (mb.msgType () == MessageType.MB_IOCTL - && (res = this.control (mb)) == -1) - return res; - - if (this.isWriter ()) - { - return this.putNext (mb, tv); - } - else /* this.isReader () */ - { - switch (mb.msgType ()) - { - case MessageType.MB_FLUSH: - return this.canonicalFlush (mb); - default: - break; - } - - try - { - return this.putq (mb, tv); - } - catch (InterruptedException e) - { - return -1; - } - } - } - - public void dump () - { - } - - public int handleTimeout (TimeValue tv, Object obj) - { - return 0; - } - -} diff --git a/java/src/StreamTail.java b/java/src/StreamTail.java deleted file mode 100644 index 1c28c676c9c..00000000000 --- a/java/src/StreamTail.java +++ /dev/null @@ -1,119 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * StreamTail.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Standard module that acts as the tail of a ustream. - *</blockquote> - */ - -public class StreamTail extends Task -{ - // Module that acts as the tail of a Stream. - - public int open (Object obj) - { - return 0; - } - - public int close (long l) - { - return 0; - } - - public int svc () - { - return -1; - } - - private int control (MessageBlock mb) - { - IOCntlMsg ioc = (IOCntlMsg) mb.obj (); - int cmd = ioc.cmd (); - - switch (cmd) - { - case IOCntlCmds.SET_LWM: - case IOCntlCmds.SET_HWM: - { - int size = mb.cont ().length (); - - this.waterMarks (cmd, size); - this.sibling ().waterMarks (cmd, size); - ioc.rval (0); - break; - } - default: - mb.msgType (MessageType.MB_IOCNAK); - } - return this.reply (mb, null); - } - - // Perform flush algorithm as though we were the driver - private int canonicalFlush (MessageBlock mb) - { - String s = mb.base (); - long f = (new Long (s)).longValue (); - - if ((f & TaskFlags.ACE_FLUSHW) != 0) - { - this.flush (TaskFlags.ACE_FLUSHALL); - f &= ~TaskFlags.ACE_FLUSHW; - } - if ((f & TaskFlags.ACE_FLUSHR) != 0) - { - this.sibling ().flush (TaskFlags.ACE_FLUSHALL); - return this.reply (mb, null); - } - return 0; - } - - // put the given MessageBlock without a timeout (block forever if - // necessary) - public int put (MessageBlock mb) - { - return this.put (mb, null); - } - - // tv is an absolute time timeout - public int put (MessageBlock mb, TimeValue tv) - { - if (this.isWriter ()) - { - switch (mb.msgType ()) - { - case MessageType.MB_IOCTL: - return this.control (mb); - /* NOTREACHED */ - default: - break; - } - } - - return -1; - } - - public void dump () - { - } - - public int handleTimeout (TimeValue tv, Object obj) - { - return 0; - } - -} diff --git a/java/src/SuspendNode.java b/java/src/SuspendNode.java deleted file mode 100644 index 5b16a368458..00000000000 --- a/java/src/SuspendNode.java +++ /dev/null @@ -1,34 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ServiceConfigurator - * - * = FILENAME - * SuspendNode.java - * - * Used when a service is specified to be suspended based on a line - * in a service configurator file. The actual implementation of the - * service being suspended does the work. - * - *@author Everett Anderson - * - *************************************************/ -package JACE.ServiceConfigurator; - -import java.io.*; -import JACE.OS.*; - -class SuspendNode extends ParseNode -{ - public SuspendNode () - { - } - - public void apply () - { - ACE.DEBUG("Suspend Node apply: " + this.name_); - - if (JACE.ServiceConfigurator.ServiceConfig.suspend(this.name_) == -1) - ACE.ERROR("Error suspending " + this.name_); - } -}; diff --git a/java/src/SvcHandler.java b/java/src/SvcHandler.java deleted file mode 100644 index 17bac41a62d..00000000000 --- a/java/src/SvcHandler.java +++ /dev/null @@ -1,85 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Connection - * - * = FILENAME - * SvcHandler.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Connection; - -import java.io.*; -import java.net.*; -import JACE.SOCK_SAP.*; -import JACE.ASX.*; -import JACE.Reactor.*; - -public abstract class SvcHandler extends Task -{ - - /** - * Do nothing constructor. - */ - public SvcHandler () - { - } - - /** - * Set the stream using the SOCKStream passed in. This sets the - * underlying peer - *@param s SOCK Stream to use for the connection - */ - public void setHandle (SOCKStream s) throws IOException - { - this.stream_ = s; - } - - /** - * Get the underlying peer - *@return the underlying peer - */ - public SOCKStream peer () - { - return this.stream_; - } - - /** - * Abstract method that subclasses must define to allow - * initialization to take place. - */ - public abstract int open (Object obj); - - /** - * Provide a default implementation to simplify ancestors. - *@return 0 - */ - public int close (long flags) - { - return 0; - } - - /** - * Provide a default implementation to simplify ancestors. - *@return -1 - */ - public int put (MessageBlock mb, TimeValue tv) - { - return -1; - } - - /** - * Provide a default implementation to simplify ancestors. - *@param tv Time Value when the event occured - *@param obj An arbitrary object that was passed to the Timer Queue - * (Asynchronous Completion Token) - */ - public int handleTimeout (TimeValue tv, Object obj) - { - return -1; - } - - protected SOCKStream stream_; -} diff --git a/java/src/Task.java b/java/src/Task.java deleted file mode 100644 index 825254e69a8..00000000000 --- a/java/src/Task.java +++ /dev/null @@ -1,439 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * Task.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -import JACE.OS.*; -import JACE.Reactor.*; -import JACE.Concurrency.*; - -public abstract class Task implements Runnable, EventHandler -{ - // = Initialization/termination methods. - - /** - * Initialize a Task. Note, we allocate a message queue ourselves. - */ - public Task () - { - this.msgQueue_ = new MessageQueue (); - this.thrMgr_ = null; - } - - /** - * Initialize a Task. Note, we use the message queue and thread - * manager supplied by the user. - *@param mq Message Queue to hold list of messages on the Task - *@param thrMgr Thread Manager that manages all the spawned threads - */ - public Task (MessageQueue mq, - ThreadManager thrMgr) - { - this.msgQueue_ = mq; - this.thrMgr_ = thrMgr; - } - - /** - * Not meant to be invoked by the user directly!. This needs to be - * in the public interface in order to get invoked by Thread - * class. - */ - public void run () - { - this.svc (); - } - - // = Initialization and termination hooks (note that these *must* be - // defined by subclasses). - - /** - * Hook called to open a Task. - *@param obj used to pass arbitrary information - */ - public abstract int open (Object obj); - - /** - * Hook called to close a Task. - */ - public abstract int close (long flags); - - // = Immediate and deferred processing methods, respectively. - - /** - * Transfer a message into the queue to handle immediate - * processing. - *@param mb Message Block to handle immediately - *@param tv Latest time to wait until (absolute time) - */ - public abstract int put (MessageBlock mb, TimeValue tv); - - /** - * Run by a daemon thread to handle deferred processing. Note, that - * to do anything useful, this method should be overriden by the - * subclass. - *@return default implementation always returns 0. - */ - public int svc () - { - return 0; - } - - /** - * Set the underlying Thread Manager. - *@param t Thread Manager to use - */ - public synchronized void thrMgr (ThreadManager t) - { - this.thrMgr_ = t; - } - - /** - * Get the Thread Manager. - *@return Underlying Thread Manager - */ - public synchronized ThreadManager thrMgr () - { - return this.thrMgr_; - } - - // = Active object method. - - /** - * Turn the task into an active object. That is, having <nThreads> - * separate threads of control that all invoke Task::svc. - *@param flags Task Flags - *@param nThreads number of threads to spawn - *@param forceActive whether to force creation of new threads or not - *@return -1 if failure occurs, 1 if Task is already an active - * object and <forceActive> is false (doesn't *not* create a new - * thread in this case), and 0 if Task was not already an active - * object and a thread is created successfully or thread is an active - * object and <forceActive> is true. - */ - public synchronized int activate (long flags, int nThreads, boolean forceActive) - { - // Create a Thread Manager if we do not already have one - if (this.thrMgr_ == null) - this.thrMgr_ = new ThreadManager (); - - if (this.thrCount () > 0 && forceActive == false) - return 1; // Already active. - this.flags_ = flags; - - if (ACE.BIT_ENABLED (flags, TaskFlags.THR_DAEMON)) - this.thrMgr_.spawnN (nThreads, this, true); // Spawn off all threads as daemon threads - else // Spawn off all threads as normal threads - this.thrMgr_.spawnN (nThreads, this, false); - - return 0; - } - - // = Suspend/resume a Task - - /** - * Suspend a task. - */ - public synchronized void suspend () - { - // Suspend all threads - if (this.thrMgr_ != null) - this.thrMgr_.thrGrp ().suspend (); - } - - /** - * Resume a suspended task. - */ - public synchronized void resume () - { - // Resume all threads - if (this.thrMgr_ != null) - this.thrMgr_.thrGrp ().resume (); - } - - /** - * Get the current group name. - *@return name of the current thread group - */ - public synchronized String grpName () - { - if (this.thrMgr_ != null) - return this.thrMgr_.thrGrp ().getName (); - else - return null; - } - - /** - * Get the message queue associated with this task. - *@return the message queue associated with this task. - */ - public MessageQueue msgQueue () - { - return this.msgQueue_; - } - - /** - * Set the message queue associated with this task. - *@param mq Message Queue to use with this Task. - */ - public void msgQueue (MessageQueue mq) - { - this.msgQueue_ = mq; - } - - /** - * Get the number of threads currently running within the Task. - *@return the number of threads currently running within the Task. - * 0 if we're a passive object, else > 0. - */ - public synchronized int thrCount () - { - if (this.thrMgr_ != null) - return this.thrMgr_.thrGrp ().activeCount (); - else - return 0; - } - - /** - * Set the Task flags - *@param flags Task Flags - */ - public synchronized void flags (long flags) - { - this.flags_ = flags; - } - - /** - * Get the Task flags - *@return Task Flags - */ - public synchronized long flags () - { - return this.flags_; - } - - // = Message queue manipulation methods. - - - /* - * Dump debug information. - */ - public void dump () - { - } - - /** - * Insert a message into the queue, blocking forever if necessary. - *@param mb Message Block to insert - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - protected int putq (MessageBlock mb) throws InterruptedException - { - return this.putq(mb, null); - } - - /** - * Insert message into the message queue. - *@param mb Message Block to insert into the Message Queue - *@param tv time to wait until (absolute time) - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - protected int putq (MessageBlock mb, TimeValue tv) throws InterruptedException - { - return this.msgQueue_.enqueueTail (mb, tv); - } - - /** - * Extract the first message from the queue, blocking forever if - * necessary. - *@return the first Message Block from the Message Queue. - *@exception InterrupteException Interrupted while accessing queue - */ - protected MessageBlock getq() throws InterruptedException - { - return this.getq(null); - } - - /** - * Extract the first message from the queue. Note that the call is blocking. - *@return the first Message Block from the Message Queue. - *@param tv Latest time to wait until (absolute time) - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - protected MessageBlock getq (TimeValue tv) throws InterruptedException - { - return this.msgQueue_.dequeueHead (tv); - } - - /** - * Return a message back to the queue. - *@param mb Message Block to return back to the Message Queue - *@param tv Latest time to wait until (absolute time) - *@exception java.lang.InterruptedException Interrupted while accessing queue - */ - protected int ungetq (MessageBlock mb, TimeValue tv) throws InterruptedException - { - return this.msgQueue_.enqueueHead (mb, tv); - } - - /** - * Transfer message to the adjacent ACETask in an ACEStream. - *@param mb Message Block to transfer to the adjacent Task - *@param tv Latest time to wait until (absolute time) - *@return -1 if there is no adjacent Task, else the return value of - * trying to put the Message Block on that Task's Message Queue. - */ - protected int putNext (MessageBlock mb, TimeValue tv) - { - return this.next_ == null ? -1 : this.next_.put (mb, tv); - } - - /** - * Turn the message back around. Puts the message in the sibling's - * Message Queue. - *@param mb Message Block to put into sibling's Message Queue - *@param tv Latest time to wait until (absolute time) - *@return -1 if there is no adjacent Task to the sibling, else the - * return value of trying to put the Message Block on sibling's - * Message Queue. - */ - protected int reply (MessageBlock mb, TimeValue tv) - { - return this.sibling ().putNext (mb, tv); - } - - // = ACE_Task utility routines to identify names et al. - - /** - * Get the name of the enclosing Module. - *@return the name of the enclosing Module if there's one associated - * with the Task, else null. - */ - protected String name () - { - if (this.mod_ == null) - return null; - else - return this.mod_.name (); - } - - /** - * Get the Task's sibling. - *@return the Task's sibling if there's one associated with the - * Task's Module, else null. - */ - protected Task sibling () - { - if (this.mod_ == null) - return null; - else - return this.mod_.sibling (this); - } - - /** - * Set the Task's module. - *@param mod the Task's Module. - */ - protected void module (Module mod) - { - this.mod_ = mod; - } - - /** - * Get the Task's module. - *@return the Task's Module if there is one, else null. - */ - protected Module module () - { - return this.mod_; - } - - /** - * Check if queue is a reader. - *@return true if queue is a reader, else false. - */ - protected boolean isReader () - { - return (ACE.BIT_ENABLED (this.flags_, TaskFlags.ACE_READER)); - } - - /** - * Check if queue is a writer. - *@return true if queue is a writer, else false. - */ - protected boolean isWriter () - { - return (ACE.BIT_DISABLED (this.flags_, TaskFlags.ACE_READER)); - } - - // = Pointers to next ACE_Queue (if ACE is part of an ACE_Stream). - - /** - * Get next Task pointer. - *@return pointer to the next Task - */ - protected Task next () - { - return this.next_; - } - - /** - * Set next Task pointer. - *@param task next task pointer - */ - protected void next (Task task) - { - this.next_ = task; - } - - // Special routines corresponding to certain message types. - - /** - * Flush the Message Queue - *@return 0 if Message Queue is null, 1 if flush succeeds, -1 if - * ACE_FLUSHALL bit is not enabled in flags. - */ - protected int flush (long flag) - { - if (ACE.BIT_ENABLED (flag, TaskFlags.ACE_FLUSHALL)) - return (this.msgQueue_ == null ? 0 : 1); - else - return -1; - } - - - /** - * Manipulate watermarks. - *@param cmd IOCntlCmd - *@param size watermark - */ - protected void waterMarks (int cmd, int size) - { - if (cmd == IOCntlCmds.SET_LWM) - this.msgQueue_.lowWaterMark (size); - else /* cmd == IOCntlMsg.SET_HWM */ - this.msgQueue_.highWaterMark (size); - } - - private ThreadManager thrMgr_ = null; - // Thread_Manager that manages all the spawned threads - - private long flags_; - // Task flags. - - private MessageQueue msgQueue_; - // List of messages on the Task.. - - private Task next_; - // Adjacent ACE_Task. - - private Module mod_; - // Back-pointer to the enclosing module. -} diff --git a/java/src/TaskFlags.java b/java/src/TaskFlags.java deleted file mode 100644 index 590e514b5e2..00000000000 --- a/java/src/TaskFlags.java +++ /dev/null @@ -1,44 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * TaskFlags.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -public abstract class TaskFlags -{ - /** Identifies a Task as being the "reader" in a Module. */ - public static final int ACE_READER = 01; - - /** Just flush data messages in the queue. */ - public static final int ACE_FLUSHDATA = 02; - - /** Flush all messages in the Queue. */ - public static final int ACE_FLUSHALL = 04; - - /** Flush read queue */ - public static final int ACE_FLUSHR = 010; - - /** Flush write queue */ - public static final int ACE_FLUSHW = 020; - - /** Flush both queues */ - public static final int ACE_FLUSHRW = 030; - - /** Identifies a thread as suspended */ - public static final int THR_SUSPENDED = 0x00000080; - - /** Identifies a thread as a daemon thread */ - public static final int THR_DAEMON = 0x00000100; - - // Default private constructor to avoid instantiation - private TaskFlags () - { - } -} diff --git a/java/src/ThreadManager.java b/java/src/ThreadManager.java deleted file mode 100644 index 5043d26511e..00000000000 --- a/java/src/ThreadManager.java +++ /dev/null @@ -1,109 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * ThreadManager.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Concurrency; - -import java.util.*; -import JACE.OS.*; - -public class ThreadManager -{ - /** - * Default constructor - */ - public ThreadManager () - { - this (ACE.DEFAULT_THREAD_GROUP_NAME); - } - - /** - * Create a Thread Manager. - *@param groupName name of the thread group that the Thread Manager - * will manage - */ - public ThreadManager (String groupName) - { - this.thrGrp_ = new ThreadGroup (groupName); - if (this.thrGrp_ == null) - ACE.ERROR ("Thread group create failed"); - } - - /** - * Create a new thread. - *@param thr the caller whose run method will be invoked when the - * thread has been spawned - *@param daemon flag indicating whether the thread should be - * spawned off as a daemon thread - */ - public void spawn (Runnable thr, - boolean daemon) - { - Thread t = new Thread (this.thrGrp_, thr); - if (daemon) // Set the thread to be a daemon thread - t.setDaemon (true); - t.start (); - } - - /** - * Create a new thread and also give it a name. - *@param thr the caller whose run method will be invoked when the - * thread has been spawned - *@param threadName the name of the new thread - *@param daemon flag indicating whether the thread should be - * spawned off as a daemon thread - */ - public void spawn (Runnable thr, - String threadName, - boolean daemon) - { - Thread t = new Thread (this.thrGrp_, thr, threadName); - if (daemon) // Set the thread to be a daemon thread - t.setDaemon (true); - t.start (); - } - - - /** - * Create <n> new threads. - *@param n the number of threads to spawn - *@param thr the caller whose run method will be invoked by each of - * the <n> threads - *@param daemon flag indicating whether the threads should be - * spawned off as daemon threads - */ - public void spawnN (int n, - Runnable thr, - boolean daemon) - { - // Spawn off all the threads. - for (int i = 0; i < n; i++) - { - this.spawn (thr, daemon); - } - } - - /** - * Get the thread group containing all the threads. Note that the - * thread group can be used to get information regarding number of - * active threads as well as to suspend/resume all the threads in - * the group. - *@return the thread group that contains all the threads managed by - * the Thread Manager - */ - public ThreadGroup thrGrp () - { - return this.thrGrp_; - } - - private ThreadGroup thrGrp_; - // Thread Group that contains all the spawned threads - -} diff --git a/java/src/ThruTask.java b/java/src/ThruTask.java deleted file mode 100644 index aebc8eb1f48..00000000000 --- a/java/src/ThruTask.java +++ /dev/null @@ -1,48 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * ThruTask.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.ASX; - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Standard module that acts as a "no op", simply passing on all - * data to its adjacent neighbor. - *</blockquote> - */ -public class ThruTask extends Task -{ - public int open (Object obj) - { - return 0; - } - - public int close (long flags) - { - return 0; - } - - public int put (MessageBlock msg, TimeValue tv) - { - return this.putNext (msg, tv); - } - - public int svc () - { - return -1; - } - - public int handleTimeout (TimeValue tv, Object obj) - { - return 0; - } -} diff --git a/java/src/TimeValue.java b/java/src/TimeValue.java deleted file mode 100644 index 274fdd8cc3d..00000000000 --- a/java/src/TimeValue.java +++ /dev/null @@ -1,285 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Reactor - * - * = FILENAME - * TimeValue.java - * - *@author Prashant Jain - * - *************************************************/ -//package JACE.Reactor; -package JACE.ASX; - -public class TimeValue -{ - public final static TimeValue zero = new TimeValue (0,0); - - /** - * Default constructor. This creates a TimeValue that is - * equal to TimeValue.zero. - */ - public TimeValue () - { - this (0, 0); - } - - /** - * Constructor - *@param sec seconds - */ - public TimeValue (long sec) - { - this (sec, 0); - } - - /** - * Constructor - *@param sec seconds - *@param nanos nanoseconds - */ - public TimeValue (long sec, int nanos) - { - this.set (sec, nanos); - } - - /** - * Sets the seconds and nanoseconds of Time Value - *@param sec seconds - *@param nanos nanoseconds - */ - public void set (long sec, int nanos) - { - this.millisec_ = sec * 1000; - this.nanos_ = nanos; - this.normalize (); - } - - /** - * Get seconds - *@return Seconds - */ - public long sec () - { - return this.millisec_/1000; - } - - /** - * Get nanoseconds - *@return Nanoseconds - */ - public int nanos () - { - return this.nanos_; - } - - /** - * Get time in milliseconds. - *@return time in milliseconds - */ - public long getMilliTime () - { - return this.millisec_; - } - - /** - * Get a String representation of the Time Value. - *@return String representation of the Time Value - */ - public String toString () - { - return (new Long (this.millisec_/1000)).toString () + ":" + - (new Integer (this.nanos_)).toString (); - } - - /** - * Get current time. - *@return the current system time as a new TimeValue - */ - public static TimeValue getTimeOfDay () - { - return new TimeValue (System.currentTimeMillis ()/1000); - } - - /** - * Return a new TimeValue that represents the current system time - * of day offset by the given number of seconds and nanoseconds. - *@param sec Number of seconds to offset by - *@param nanos Number of nanoseconds to offset by - *@see JACE.ASX.TimeValue - *@return TimeValue for the system time plus the given offset - */ - public static TimeValue relativeTimeOfDay(long sec, int nanos) - { - return new TimeValue ((System.currentTimeMillis() / 1000) + sec, - nanos); - } - - /** - * Return a new TimeValue that represents the current system time - * of day offset by the given TimeValue. - *@param tv TimeValue to offset by - *@see JACE.ASX.TimeValue - *@return TimeValue for the system time plus the given offset - */ - public static TimeValue relativeTimeOfDay(TimeValue offset) - { - return new TimeValue ((System.currentTimeMillis() / 1000) + - offset.sec(), - offset.nanos()); - } - - /** - * Compare two Time Values for equality. - *@param tv Time Value to compare with - *@return true if the two Time Values are equal, false otherwise - */ - public boolean equals (TimeValue tv) - { - return this.millisec_ == (tv.sec () * 1000) && this.nanos_ == tv.nanos (); - } - - /** - * Compare two Time Values for non-equality. - *@param tv Time Value to compare with - *@return true if the two Time Values are not equal, false otherwise - */ - public boolean notEquals (TimeValue tv) - { - return !this.equals (tv); - } - - /** - * Add two Time Values. - *@param tv1 The first Time Value - *@param tv2 The second Time Value - *@return sum of the two Time Values. - */ - public static TimeValue plus (TimeValue tv1, TimeValue tv2) - { - TimeValue tv = new TimeValue (tv1.sec () + tv2.sec (), - tv1.nanos () + tv2.nanos ()); - tv.normalize (); - return tv; - } - - /** - * Subtract two Time Values. - *@param tv1 The first Time Value - *@param tv2 The second Time Value - *@return difference of the two Time Values. - */ - public static TimeValue minus (TimeValue tv1, TimeValue tv2) - { - TimeValue tv = new TimeValue (tv1.sec () - tv2.sec (), - tv1.nanos () - tv2.nanos ()); - tv.normalize (); - return tv; - } - - /** - * Add Time Value to "this". - *@param tv The Time Value to add to this. - */ - public void plusEquals (TimeValue tv) - { - this.set (this.sec () + tv.sec (), - this.nanos () + tv.nanos ()); - this.normalize (); - } - - /** - * Subtract Time Value from "this". - *@param tv The Time Value to subtract from this. - */ - public void minusEquals (TimeValue tv) - { - this.set (this.sec () - tv.sec (), - this.nanos () - tv.nanos ()); - this.normalize (); - } - - /** - * Compare two Time Values for less than. - *@param tv Time Value to compare with - *@return true if "this" is less than tv, false otherwise - */ - public boolean lessThan (TimeValue tv) - { - return tv.greaterThan (this); - } - - /** - * Compare two Time Values for greater than. - *@param tv Time Value to compare with - *@return true if "this" is greater than tv, false otherwise - */ - public boolean greaterThan (TimeValue tv) - { - if (this.sec () > tv.sec ()) - return true; - else if (this.sec () == tv.sec () - && this.nanos () > tv.nanos ()) - return true; - else - return false; - } - - /** - * Compare two Time Values for <=. - *@param tv Time Value to compare with - *@return true if "this" <= tv, false otherwise - */ - public boolean lessThanEqual (TimeValue tv) - { - return tv.greaterThanEqual (this); - } - - /** - * Compare two Time Values for >=. - *@param tv Time Value to compare with - *@return true if "this" >= tv, false otherwise - */ - public boolean greaterThanEqual (TimeValue tv) - { - return this.sec () >= tv.sec () && this.nanos () >= tv.nanos (); - } - - private void normalize () - { - if (this.nanos_ >= ONE_MILLISECOND) - { - do - { - this.millisec_++; - this.nanos_ -= ONE_MILLISECOND; - } - while (this.nanos_ >= ONE_MILLISECOND); - } - else if (this.nanos_ <= -ONE_MILLISECOND) - { - do - { - this.millisec_--; - this.nanos_ += ONE_MILLISECOND; - } - while (this.nanos_ <= -ONE_MILLISECOND); - } - - if (this.millisec_ >= 1 && this.nanos_ < 0) - { - this.millisec_--; - this.nanos_ += ONE_MILLISECOND; - } - else if (this.millisec_ < 0 && this.nanos_ > 0) - { - this.millisec_++; - this.nanos_ -= ONE_MILLISECOND; - } - } - - private long millisec_; - private int nanos_; - private final static int ONE_MILLISECOND = 1000000; -} diff --git a/java/src/TimedWait.java b/java/src/TimedWait.java deleted file mode 100644 index a8f337c086b..00000000000 --- a/java/src/TimedWait.java +++ /dev/null @@ -1,150 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * TimedWait.java - * - *@author Prashant Jain and Doug Schmidt - * - *************************************************/ -package JACE.ASX; - -public abstract class TimedWait -{ - /** - * Default Constructor. Sets "this" to be used for the delegation of - * the wait() call to. - */ - public TimedWait () - { - object_ = this; - } - - /** - * Constructor. Allows subclasses to supply us with an Object that - * is delegated the wait() call. - *@param obj The Object that is delegated the wait() call. - */ - public TimedWait (Object obj) - { - object_ = obj; - } - - /** - * Hook method that needs to be implemented by subclasses. - */ - public abstract boolean condition (); - - /** - * Wait until condition becomes true. Note that the method - * blocks. Also note that this method is final to ensure that no one - * overrides it. - * IMPORTANT: This method assumes it is called with the object_'s - * monitor lock already held. - *@exception InterruptedException Interrupted during wait - */ - public final void timedWait () throws InterruptedException - { - // Acquire the monitor lock. - if (!condition ()) - { - // Only attempt to perform the wait if the condition isn't - // true initially. - for (;;) - { - // Wait until we are notified. - object_.wait (); - - // Recheck the condition. - if (condition ()) - break; // Condition became true. - // else we were falsely notified so go back into wait - } - } - } - - /** - * Template Method that implements the actual timed wait. Note that - * this method is final to ensure that no one overrides it. - * IMPORTANT: This method assumes it is called with the object_'s - * monitor lock already held. - * If the specified wait time is zero, this checks the condition, - * then returns on success or throws a TimeoutException on failure. - *@param tv Absolute time to wait until before throwing an exception - * if the condition isn't satisfied - *@exception java.lang.InterruptedException Interrupted during wait - *@exception JACE.ASX.TimeoutException Reached timeout specified - */ - public final void timedWait (TimeValue tv) - throws InterruptedException, - TimeoutException - { - if (tv == null) { - this.timedWait(); - return; - } - - // Acquire the monitor lock. - if (!condition ()) - { - long start = System.currentTimeMillis(); - long waitTime = tv.getMilliTime() - start; - - // Safety check since there is a possibility that it is now - // exactly the same time as the tv. That would cause - // waitTime to be 0, and since Java's wait(timeout) blocks - // when timeout is 0, it would mean trouble. - if (waitTime < 1) - throw new TimeoutException(); - - for (;;) { - // Wait until we are notified. - object_.wait (waitTime); - - // Recheck the condition. - if (!condition ()) { - - long now = System.currentTimeMillis(); - - // Timed out! - if (now >= tv.getMilliTime ()) - throw new TimeoutException (); - else - // We still have some time left to wait, so adjust the - // wait_time. - waitTime = tv.getMilliTime() - now; - } - else - break; // Condition became true. - } - } - } - - /** - * Notify any one thread waiting on the object_. - * IMPORTANT: This method assumes it is called with the object_'s - * monitor lock already held. - */ - public final void signal () { - object_.notify (); - } - - /** - * Notify all threads waiting on the object_. - * IMPORTANT: This method assumes it is called with the object_'s - * monitor lock already held. - */ - public final void broadcast () { - object_.notifyAll (); - } - - /** - * The object we delegate to. If a subclass gives us a particular - * object, we use that to delegate to, otherwise, we ``delegate'' - * to ourself (i.e., this). - */ - protected Object object_; - -} diff --git a/java/src/TimeoutException.java b/java/src/TimeoutException.java deleted file mode 100644 index b55549938dc..00000000000 --- a/java/src/TimeoutException.java +++ /dev/null @@ -1,34 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.ASX - * - * = FILENAME - * TimeoutException.java - * - *@author Prashant Jain and Doug Schmidt - * - *************************************************/ -package JACE.ASX; - -public class TimeoutException extends Exception -{ - /** - * Default Constructor. - */ - public TimeoutException () - { - super ("Timed Out"); - } - - /** - * Constructor. - *@param timeout The timeout value which expired. - *@param desc Textual description of the exception - */ - public TimeoutException (TimeValue timeout, String desc) - { - super ("Timed Out in " + timeout + ": " + desc); - } - -} diff --git a/java/src/TimerQueue.java b/java/src/TimerQueue.java deleted file mode 100644 index a374a9603cd..00000000000 --- a/java/src/TimerQueue.java +++ /dev/null @@ -1,432 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Reactor - * - * = FILENAME - * TimerQueue.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Reactor; - -import java.util.*; -import JACE.ASX.*; - -import JACE.OS.*; - -class TimerNode -{ - public TimerNode (EventHandler handler, - Object arg, - TimeValue timerValue, - TimeValue interval, - TimerNode next, - int timerId) - { - this.handler_ = handler; - this.arg_ = arg; - this.timerValue_ = timerValue; - this.interval_ = interval; - this.next_ = next; - this.timerId_ = timerId; - } - - public EventHandler handler_; - // Handler to invoke <handleTimeout> on when a timeout occurs. - - public Object arg_; - // Argument to pass to <handleTimeout>. - - public TimeValue timerValue_; - // Time when the timer expires. (absolute time) - - public TimeValue interval_; - // If this is a periodic timer this holds the time until the next - // timeout. - - public TimerNode next_; - // Pointer to next timer. - - public int timerId_; - // Id of this timer (used to cancel timers before they expire). -} - -class WaitObject extends TimedWait -{ - public boolean condition () - { - return this.condition_; - } - - public void condition (boolean c) - { - this.condition_ = c; - } - - private boolean condition_ = false; -} - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Class that provides an interface to timers. - * - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * This is a simple implementation that keeps a linked list of - * absolute timers. It allows multiple timers to be scheduled - * and returns a timer id for each timer scheduled. In addition, - * it allows periodic timers to be scheduled. - *</blockquote> - */ -public class TimerQueue implements Runnable -{ - /** - * Constructor. - *@param createInternalThread flag specifying whether to create an - * internal thread that runs the event loop. If it is true, a thread - * is spawned and it runs the event loop, handling all timeout - * events. If it is false, the caller is then responsible for calling - * handleEvents () to run the event loop. - */ - public TimerQueue (boolean createInternalThread) - { - this.eventLoopRunning_ = false; - if (createInternalThread) - new Thread (this).start (); - } - - /** - * The thread run method. Do *NOT* call this method! It gets called - * automatically. - */ - public void run () - { - this.handleEvents (); - } - - /** - * Handle timeout events. This forms the event loop and takes care - * of all scheduling. This method should only be called if the Timer - * Queue was constructed with the value of createInternalThread as - * false. - */ - public void handleEvents () - { - if (!this.eventLoopRunning_) - { - // Set the flag indicating that the event loop is now running - this.eventLoopRunning_ = true; - - TimeValue timeout = null; - - for (;;) - { - synchronized (this.obj_) - { - timeout = this.earliestTime (); - - try - { - // Extract the earliest time from the queue and do a timed wait - // Note that this does a blocking wait if timeout is null - this.obj_.timedWait (timeout); - - // We have been notified. - if (this.reset_) - { - this.reset_ = false; - this.obj_.condition (false); - // Don't need to change the timer since it's an absolute - // time value. - } - } - catch (TimeoutException e) - { - // Timeout occurred. Call handleTimeout on appropriate - // Event Handlers - this.dispatchHandlers (); - } - catch (InterruptedException e) - { - } - } - } - } - } - - /** - * Check if the queue is empty. - *@return true if queue is empty, else false. - */ - boolean isEmpty () - { - return this.head_ == null; - } - - /** - * Get the node of the earliest node in the TimerQueue. - *@return the time of the earlier node in the TimerQueue. - */ - TimeValue earliestTime () - { - synchronized (this.obj_) - { - if (!this.isEmpty ()) - return this.head_.timerValue_; - else - return null; - } - } - - /** - * Schedule an <EventHandler> that will expire after <delta> amount - * of time. If it expires then <obj> is passed in as the value to - * the <EventHandler>'s <handleTimeout> callback method. This method - * returns a timer id that uniquely identifies the timer and can be - * used to cancel the timer before it expires. - *@param handler Event Handler that is to be scheduled with the timer - *@param obj Object that is passed back to the Event Handler when - * timeout occurs (Asynchronous Completion Token) - *@param delta amount of time for which to schedule the timer (relative time) - *@return id of the timer scheduled - */ - public int scheduleTimer (EventHandler handler, - Object obj, - TimeValue delta) - { - return this.scheduleTimer (handler, obj, delta, TimeValue.zero); - } - - /** - * Schedule an <EventHandler> that will expire after <delta> amount - * of time. If it expires then <obj> is passed in as the value to - * the <EventHandler>'s <handleTimeout> callback method. If - * <interval> is != to <TimeValue.zero> then it is used to - * reschedule the <EventHandler> automatically. This method - * returns a timer id that uniquely identifies the timer and can be - * used to cancel the timer before it expires. - *@param handler Event Handler that is to be scheduled with the timer - *@param arg Object that is passed back to the Event Handler when - * timeout occurs (Asynchronous Completion Token) - *@param delta amount of time for which to schedule the timer (relative time) - *@param interval amount of time to use to reschedule the timer - *@return id of the timer scheduled - */ - public int scheduleTimer (EventHandler handler, - Object arg, - TimeValue delta, - TimeValue interval) - { - - // Increment the sequence number (it will wrap around). - this.timerId_++; - - ACE.DEBUG("scheduleTimer (" + this.timerId_ + "): " + - delta + ", " + interval); - - // futureTime is the current time of day plus the given delta - TimeValue futureTime = TimeValue.relativeTimeOfDay (delta); - - TimerNode node = new TimerNode (handler, - arg, - futureTime, - interval, - null, - this.timerId_); - synchronized (this.obj_) - { - // Check if event loop is running. If it is not, then we can - // just place it at the appropriate place in the queue and - // don't need to do any notification. If event loop is - // running, then check if the node is the first node in the - // queue (either because the queue is empty or because the - // time for the node is earlier than the currently scheduled - // timer node). - if (this.eventLoopRunning_ && - (this.isEmpty () || futureTime.lessThan (this.earliestTime ()))) - { - // Insert the node into (the beginning of) the queue to be - // scheduled. - this.reschedule (node); - - // Notify the waiting thread so that it can reschedule - // using the earliest timeout - this.obj_.notify (); - } - else // Place in the appropriate position in the queue. - { - this.reschedule (node); - } - } - return this.timerId_; - } - - - /** - * Cancel the single timer associated with <timerId>. - *@param timerId id of the timer that needs to be cancelled. - *@return Object that was passed in when timer was scheduled - * (Asynchronous Completion Token). - */ - public Object cancelTimer (int timerId) - { - TimerNode prev = null; - TimerNode curr = null; - - synchronized (this.obj_) - { - // Try to locate the TimerNode that matches the timerId. - for (curr = this.head_; - curr != null && curr.timerId_ != timerId; - curr = curr.next_) - prev = curr; - - if (curr != null) - { - if (prev == null) - this.head_ = curr.next_; - else - prev.next_ = curr.next_; - - return curr.arg_; - } - } - return null; - } - - /** - * Cancel all timers associated with <Event Handler>. - *@param handler Event Handler whose associated timers need to be cancelled. - */ - public void cancelTimer (EventHandler handler) - { - TimerNode prev = null; - TimerNode curr = this.head_; - - synchronized (this.obj_) - { - while (curr != null) - { - if (curr.handler_ == handler) - { - if (prev == null) - { - this.head_ = curr.next_; - curr = this.head_; - } - else - { - prev.next_ = curr.next_; - curr = prev.next_; - } - } - else - { - prev = curr; - curr = curr.next_; - } - } - } - } - - // Call handleTimeout() on all handlers whose timers have expired. - private void dispatchHandlers () - { - TimeValue currentTime = TimeValue.getTimeOfDay (); - - for (;;) - { - if (this.isEmpty () || this.earliestTime ().greaterThan (currentTime)) - break; // There aren't any more timers eligible to expire. - - TimerNode expired = this.head_; - EventHandler handler = expired.handler_; - Object arg = expired.arg_; - int result; - - this.head_ = this.head_.next_; - - // Check whether this is an interval timer. - if (expired.interval_.greaterThan (TimeValue.zero)) - { - // Make sure that we skip past values that have already - // "expired". - do - expired.timerValue_.plusEquals (expired.interval_); - while (expired.timerValue_.lessThanEqual (currentTime)); - - // Since this is an interval timer, we need to reschedule - // it. - this.reschedule (expired); - } - - ACE.DEBUG("handleTimeout " + expired.timerId_); - - // Perform the callback. - result = handler.handleTimeout (currentTime, arg); - - if (result == -1) - this.cancelTimer (handler); - } - } - - // Reschedule a TimerNode by inserting it at the appropriate - // position in the queue. - private void reschedule (TimerNode expired) - { - ACE.DEBUG("reschedule " + expired.timerId_ + " for " + expired.timerValue_); - // *** Shouldn't it use interval here? - - if (this.isEmpty () || - expired.timerValue_.lessThan (this.earliestTime ())) - { - expired.next_ = this.head_; - this.head_ = expired; - // Set the condition to true so that the waiting thread can be - // notified and it can reschedule. - this.obj_.condition (true); - this.reset_ = true; - } - else - { - TimerNode prev = this.head_; - TimerNode after = this.head_.next_; - - // Locate the proper position in the queue. - - while (after != null - && expired.timerValue_.greaterThan (after.timerValue_)) - { - prev = after; - after = after.next_; - } - - expired.next_ = after; - prev.next_ = expired; - } - } - - private WaitObject obj_ = new WaitObject (); - // Synchronization object (as well as object to use to do wait on) - - private TimerNode head_; - // Pointer to linked list of TimerHandles. - - private int timerId_; - // Keeps track of the timer id that uniquely identifies each timer. - // This id can be used to cancel a timer via the <cancel (int)> - // method. - - private boolean reset_; - // Flag indicating whether to start the wait again - - private boolean eventLoopRunning_; - // Flag indicating whether the event loop is running or not -} - diff --git a/java/src/Token.java b/java/src/Token.java deleted file mode 100644 index c112acdb653..00000000000 --- a/java/src/Token.java +++ /dev/null @@ -1,336 +0,0 @@ -/************************************************* - * - * = PACKAGE - * JACE.Concurrency - * - * = FILENAME - * Token.java - * - *@author Prashant Jain - * - *************************************************/ -package JACE.Concurrency; - -import java.util.*; -import JACE.ASX.*; - -class WaitObject extends TimedWait -{ - public boolean condition () - { - return this.condition_; - } - - public void condition (boolean c) - { - this.condition_ = c; - } - - private boolean condition_ = false; -} - -/** - * <hr> - * <h2>SYNOPSIS</h2> - *<blockquote> - * Class that acquires, renews, and releases a synchronization - * token that is serviced in strict FIFO ordering. - * - *</blockquote> - * - * <h2>DESCRIPTION</h2> - *<blockquote> - * This is a general-purpose synchronization mechanism that offers - * several benefits. For example, it implements "recursive mutex" - * semantics, where a thread that owns the token can reacquire it - * without deadlocking. In addition, threads that are blocked - * awaiting the token are serviced in strict FIFO order as other - * threads release the token. The solution makes use of the - * Specific Notification pattern presented by Tom Cargill in - * "Specific Notification for Java Thread Synchronization," PLoP96. - *</blockquote> - */ -public class Token -{ - - /** - * Acquire the token. Note that this will block. The method uses - * synchronized blocks internally to avoid race conditions. It - * ignores thread interrupts. - *@return 0 if acquires without calling <sleepHook> - * 1 if <sleepHook> is called. - * -1 if failure occurs (should never happen) - */ - public int acquire () - { - try - { - return this.acquire (null); - } - catch (TimeoutException e) - { - // This really shouldn't happen since we are supposed to - // block. - return -1; - } - } - - /** - * Acquire the token. Returns failure - * Throws a TimeoutException if the token isn't acquired before the - * given absolute time timeout. - *@param timeout time (TimeValue) to wait until before throwing a - * TimeoutException (unless the token is acquired before that). - * Performs a blocking acquire if the given timeout is null. - *@return 0 if acquires without calling <sleepHook> - * 1 if <sleepHook> is called. - * -1 if failure occurs (timeout) - */ - public int acquire (TimeValue timeout) throws TimeoutException - { - int result = 0; - WaitObject snl = new WaitObject (); - boolean mustWait; - synchronized (snl) - { - synchronized (this) - { - mustWait = !this.snq_.isEmpty (); - - if (mustWait && isOwner ()) - { - // I am the one who has the token. So just increment - // the nesting level - this.nestingLevel_++; - return 0; - } - // Add local lock to the queue - this.snq_.addElement (snl); - } - if (mustWait) - { - result = 1; - sleepHook(); - - while (mustWait) { - try { - snl.timedWait(timeout); - mustWait = false; - } catch (InterruptedException e) { - // must keep waiting - } - } - } - - // Set the owner of the token - setOwner(); - } - return result; - } - - /** - * Try to acquire the token. Implements a non-blocking acquire. - *@return 0 if acquires without calling <sleepHook> - * -1 if failure occurs - */ - public synchronized int tryAcquire () - { - int result = 0; - - if (this.snq_.isEmpty ()) - { - // No one has the token, so acquire it - this.snq_.addElement (new WaitObject ()); - - setOwner(); - } - else if (isOwner()) - { - this.nestingLevel_++; - } - // Someone else has the token. - else - { - // Would have to block to acquire the token, so return - // failure. - result = -1; - } - return result; - } - - /** - * Method that is called before a thread goes to sleep in an - * acquire(). This should be overridden by a subclass to define - * the appropriate behavior before acquire() goes to sleep. - * By default, this is a no-op. - */ - public void sleepHook () - { - } - - /** - * An optimized method that efficiently reacquires the token if no - * other threads are waiting. This is useful for situations where - * you don't want to degrade the quality of service if there are - * other threads waiting to get the token. This blocks until it - * can regain the token. - *@param requeuePosition Position in the queue where to insert the - * lock. If requeuePosition == -1 and there are other threads - * waiting to obtain the token we are queued at the end of the list - * of waiters. If requeuePosition > -1 then it indicates how many - * entries to skip over before inserting our thread into the list of - * waiters (e.g.,requeuePosition == 0 means "insert at front of the - * queue"). - */ - public void renew (int requeuePosition) - { - try - { - this.renew (requeuePosition, null); - } - catch (TimeoutException e) - { - // This really shouldn't happen since we are supposed to - // block. - } - } - - /** - * An optimized method that efficiently reacquires the token if no - * other threads are waiting. This is useful for situations where - * you don't want to degrade the quality of service if there are - * other threads waiting to get the token. If the given TimeValue - * is null, it's the same as calling renew(int requeuePosition). - *@param requeuePosition Position in the queue where to insert the - * lock. If requeuePosition == -1 and there are other threads - * waiting to obtain the token we are queued at the end of the list - * of waiters. If requeuePosition > -1 then it indicates how many - * entries to skip over before inserting our thread into the list of - * waiters (e.g.,requeuePosition == 0 means "insert at front of the - * queue"). - *@param timeout Throw a TimeoutException if the token isn't renewed - * before this absolute time timeout. - *@exception TimeoutException exception if timeout occurs - */ - public void renew (int requeuePosition, TimeValue timeout) - throws TimeoutException - { - WaitObject snl = null; - int saveNestingLevel = 0; - - synchronized (this) - { - // Check if there is a thread waiting to acquire the token. If - // not or if requeuePosition == 0, then we don't do anything - // and we simply keep the token. - if (this.snq_.size () > 1 && requeuePosition != 0) - { - // Save the nesting level - saveNestingLevel = this.nestingLevel_; - this.nestingLevel_ = 0; - - // Reinsert ourselves at requeuePosition in the queue - snl = (WaitObject) this.snq_.firstElement (); - this.snq_.removeElementAt (0); - - if (requeuePosition < 0) - this.snq_.addElement (snl); // Insert at end - else - this.snq_.insertElementAt (snl, Math.min(requeuePosition, - this.snq_.size())); - - synchronized (this.snq_.firstElement ()) - { - // Notify the first waiting thread in the queue - WaitObject obj = (WaitObject) this.snq_.firstElement (); - // Set its condition to be true so that it falls out - // of the for loop - obj.condition (true); - // Now signal the thread - obj.signal (); - } - } - } - - // Check if we reinserted the lock in the queue and therefore need - // to do a wait - if (snl != null) - { - synchronized (snl) - { - // Set the condition to be false so that we can begin the - // wait - snl.condition (false); - // Wait until the given absolute time (or until notified - // if the timeout is null) - boolean mustWait = true; - while (mustWait) { - try { - snl.timedWait (timeout); - mustWait = false; - } catch (InterruptedException e) { - // must keep waiting - } - } - } - // Restore the nesting level and current owner of the lock - this.nestingLevel_ = saveNestingLevel; - - // Set the owner of the token - setOwner(); - } - } - - /** - * Release the token. It is safe for non-owners to call - * this. - */ - public synchronized void release () - { - if (!isOwner()) - return; - - // Check if nestingLevel > 0 and if so, decrement it - if (this.nestingLevel_ > 0) - this.nestingLevel_--; - else - { - this.snq_.removeElementAt (0); - if (!this.snq_.isEmpty ()) - { - synchronized (this.snq_.firstElement ()) - { - // Notify the first waiting thread in the queue - WaitObject obj = (WaitObject) this.snq_.firstElement (); - // Set its condition to be true so that it falls out - // of the for loop - obj.condition (true); - // Now signal the thread - obj.signal (); - } - } - } - } - - // The next two methods allow subclasses to change the behavior of the - // checking and setting the Object owner_ member variable. The default - // is to use the current Thread's toString() as the Object. - protected void setOwner() { - this.owner_ = Thread.currentThread().toString(); - } - - protected boolean isOwner() { - return Thread.currentThread().toString().equals(this.owner_); - } - - private Vector snq_ = new Vector (); - // Vector of lock objects - - private int nestingLevel_ = 0; - // Current Nesting Level - - private Object owner_ = null; - // Current owner of the token. The setOwner() and isOwner() - // methods provide subclasses with the ability to change the - // behavior. The default is to use the Thread.toString(). -} diff --git a/java/tests/ASX/BufferStreamTest.dsp b/java/tests/ASX/BufferStreamTest.dsp deleted file mode 100644 index 6a6b5107a4d..00000000000 --- a/java/tests/ASX/BufferStreamTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="BufferStreamTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=BufferStreamTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "BufferStreamTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "BufferStreamTest.mak"\
- CFG="BufferStreamTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "BufferStreamTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "BufferStreamTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "BufferStreamTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "BufferStreamTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "BufferStreamTest - Java Virtual Machine Release"
-# Name "BufferStreamTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\BufferStreamTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/ASX/BufferStreamTest.java b/java/tests/ASX/BufferStreamTest.java deleted file mode 100644 index c61f94f281e..00000000000 --- a/java/tests/ASX/BufferStreamTest.java +++ /dev/null @@ -1,185 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.ASX -// -// = FILENAME -// BufferStreamTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.ASX; - -import java.io.*; -import JACE.OS.*; -import JACE.ASX.*; - -// This short program copies stdin to stdout via the use of an ASX -// STREAM. It illustrates an implementation of the classic "bounded -// buffer" program using an ASX STREAM containing two Modules. Each -// Module contains two Tasks. - -class CommonTask extends Task -{ - // ACE_Task hooks - public int open (Object obj) - { - if (this.activate (0, 1, false) == -1) - ACE.ERROR ("spawn"); - return 0; - } - - public int close (long exitStatus) - { - ACE.DEBUG (Thread.currentThread () + " thread is exiting with status " + - exitStatus + " in module " + this.name () + "\n"); - return 0; - } - - public int put (MessageBlock mb, TimeValue tv) - { - return 0; - } - - public int handleTimeout (TimeValue tv, Object obj) - { - return 0; - } -} - -// Define the Producer interface. - -class Producer extends CommonTask -{ - // Read data from stdin and pass to consumer. - // The Consumer reads data from the stdin stream, creates a message, - // and then queues the message in the message list, where it is - // removed by the consumer thread. A 0-sized message is enqueued when - // there is no more data to read. The consumer uses this as a flag to - // know when to exit. - - public int svc () - { - // Keep reading stdin, until we reach EOF. - - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - - String msg = null; - try - { - while (true) - { - System.out.print ("Enter input: "); - System.out.flush (); - msg = in.readLine (); - if (msg == null) - { - // Send a shutdown message to the other thread and exit. - if (this.putNext (new MessageBlock (0), new TimeValue ()) == -1) - ACE.ERROR ("putNext"); - break; - } - else - { - // Send the message to the other thread. - if (this.putNext (new MessageBlock (msg), new TimeValue ()) == -1) - ACE.ERROR ("putNext"); - } - } - } - catch (IOException e) - { - } - return 0; - } -} - -class Consumer extends CommonTask - // = TITLE - // Define the Consumer interface. -{ - // Enqueue the message on the MessageQueue for subsequent - // handling in the svc() method. - public int put (MessageBlock mb, TimeValue tv) - { - try - { - return this.putq (mb, tv); - } - catch (InterruptedException e) - { - } - return 0; - } - - // The consumer dequeues a message from the ACE_Message_Queue, writes - // the message to the stderr stream, and deletes the message. The - // Consumer sends a 0-sized message to inform the consumer to stop - // reading and exit. - - public int svc () - { - MessageBlock mb = null; - - // Keep looping, reading a message out of the queue, until we - // timeout or get a message with a length == 0, which signals us to - // quit. - try - { - while (true) - { - // Wait for upto 4 seconds - mb = this.getq (new TimeValue (4)); - - if (mb == null) - break; - - int length = mb.length (); - - if (length > 0) - System.out.println ("\n" + mb.base ()); - - if (length == 0) - break; - } - } - catch (InterruptedException e) - { - } - if (mb == null) - { - ACE.ERROR ("timed out waiting for message"); - System.exit (1); - } - return 0; - } -} - -// Spawn off a new thread. - -public class BufferStreamTest -{ - public static void main (String args[]) - { - // Control hierachically-related active objects - Stream stream = new Stream (); - Module pm = new Module ("Consumer", new Consumer (), null, null); - Module cm = new Module ("Producer", new Producer (), null, null); - - // Create Producer and Consumer Modules and push them onto the - // STREAM. All processing is performed in the STREAM. - - if (stream.push (pm) == -1) - { - ACE.ERROR ("push"); - return; - } - else if (stream.push (cm) == -1) - { - ACE.ERROR ("push"); - return; - } - } -} diff --git a/java/tests/ASX/Makefile b/java/tests/ASX/Makefile deleted file mode 100644 index d097cbb0850..00000000000 --- a/java/tests/ASX/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -# Makefile - -.SUFFIXES: .java .class - -JACE_WRAPPER = ../.. -CLASSDIR = $(JACE_WRAPPER)/classes - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - - -files = MessageQueueTest.java \ - TaskTest.java \ - PriorityBufferTest.java \ - ThreadPoolTest.java \ - BufferStreamTest.java - -packages = tests.ASX - -realclean: - find ${JACE_WRAPPER}/classes/tests/ASX -name '*.class' -print | xargs ${RM} - diff --git a/java/tests/ASX/MessageQueueTest.dsp b/java/tests/ASX/MessageQueueTest.dsp deleted file mode 100644 index 806ea9208c0..00000000000 --- a/java/tests/ASX/MessageQueueTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="MessageQueueTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=MessageQueueTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "MessageQueueTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "MessageQueueTest.mak"\
- CFG="MessageQueueTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "MessageQueueTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "MessageQueueTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "MessageQueueTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "MessageQueueTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "MessageQueueTest - Java Virtual Machine Release"
-# Name "MessageQueueTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\MessageQueueTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/ASX/MessageQueueTest.java b/java/tests/ASX/MessageQueueTest.java deleted file mode 100644 index c22d2cf041d..00000000000 --- a/java/tests/ASX/MessageQueueTest.java +++ /dev/null @@ -1,50 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.ASX -// -// = FILENAME -// MessageQueueTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.ASX; - -import java.io.*; -import JACE.OS.*; -import JACE.ASX.*; - -public class MessageQueueTest -{ - public static void main (String args[]) - { - try - { - MessageBlock conMb; - MessageQueue msgQueue = new MessageQueue (); - MessageBlock mb1 = new MessageBlock ("hello"); - MessageBlock mb2 = new MessageBlock ("world"); - mb1.msgPriority (5); - mb2.msgPriority (7); - - // Enqueue in priority order. - if (msgQueue.enqueue (mb1) == -1) - ACE.ERROR ("put_next"); - - if (msgQueue.enqueue (mb2) == -1) - ACE.ERROR ("put_next"); - - // Now try to dequeue - if ((conMb = msgQueue.dequeueHead ()) == null) - ACE.ERROR ("dequeueHead"); - else - ACE.DEBUG ("Consumer: removed item " + conMb.base () + " of priority " + conMb.msgPriority ()); - } - catch (InterruptedException e) - { - } - } -} - diff --git a/java/tests/ASX/PriorityBufferTest.dsp b/java/tests/ASX/PriorityBufferTest.dsp deleted file mode 100644 index 844e281b1b1..00000000000 --- a/java/tests/ASX/PriorityBufferTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="PriorityBufferTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=PriorityBufferTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "PriorityBufferTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "PriorityBufferTest.mak"\
- CFG="PriorityBufferTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "PriorityBufferTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "PriorityBufferTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "PriorityBufferTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "PriorityBufferTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "PriorityBufferTest - Java Virtual Machine Release"
-# Name "PriorityBufferTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\PriorityBufferTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/ASX/PriorityBufferTest.java b/java/tests/ASX/PriorityBufferTest.java deleted file mode 100644 index 5cce32fa3b1..00000000000 --- a/java/tests/ASX/PriorityBufferTest.java +++ /dev/null @@ -1,116 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.ASX -// -// = FILENAME -// PriorityBufferTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.ASX; - -import java.io.*; -import JACE.OS.*; -import JACE.ASX.*; - -class consumer extends Thread -{ - public void run () - { - MessageBlock mb = null; - long curPriority = 0; - int length = 0; - - try - { - // Keep looping, reading a message out of the queue, until we - // get a message with a length == 0, which signals us to quit. - for (;;) - { - if ((mb = PriorityBufferTest.msgQueue.dequeueHead ()) == null) - break; - - length = mb.length (); - curPriority = mb.msgPriority (); - - if (length > 0) - ACE.DEBUG ("Consumer: removed item \"" + mb.base () + "\" of priority: " + curPriority); - - if (length == 0) - break; - } - } - catch (InterruptedException e) - { - } - } -} - -class producer extends Thread -{ - producer (int delay) - { - this.delay_ = delay; - } - - public void run () - { - try - { - long count = 0; - for (char c = 'a'; c <= 'z'; c++) - { - count++; - // Allocate a new message - MessageBlock mb = new MessageBlock (new Character (c).toString ()); - // Set the priority - mb.msgPriority (count); - - // Enqueue in priority order. - if (PriorityBufferTest.msgQueue.enqueue (mb) == -1) - ACE.ERROR ("put_next"); - else - { - ACE.DEBUG ("Producer: inserted item \"" + mb.base () + "\" of priority: " + count); - if (this.delay_ > 0) - this.sleep (this.delay_); - } - } - - // Now send a 0-sized shutdown message to the other thread - if (PriorityBufferTest.msgQueue.enqueueTail (new MessageBlock (0)) == -1) - ACE.ERROR ("put_next"); - } - catch (InterruptedException e) - { - } - } - - private int delay_; -} - -public class PriorityBufferTest -{ - public static MessageQueue msgQueue = new MessageQueue (); - - public static void main (String args[]) - { - int delay = 0; - if (args.length == 1) - { - try - { - delay = Integer.parseInt (args[0]); - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - } - new producer (delay).start (); - new consumer ().start (); - } -} diff --git a/java/tests/ASX/TaskTest.dsp b/java/tests/ASX/TaskTest.dsp deleted file mode 100644 index 072a92b8847..00000000000 --- a/java/tests/ASX/TaskTest.dsp +++ /dev/null @@ -1,72 +0,0 @@ -# Microsoft Developer Studio Project File - Name="TaskTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=TaskTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "TaskTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "TaskTest.mak" CFG="TaskTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "TaskTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "TaskTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "TaskTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "TaskTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "TaskTest - Java Virtual Machine Release"
-# Name "TaskTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\TaskTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/ASX/TaskTest.java b/java/tests/ASX/TaskTest.java deleted file mode 100644 index b26b48ea148..00000000000 --- a/java/tests/ASX/TaskTest.java +++ /dev/null @@ -1,86 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.ASX -// -// = FILENAME -// TaskTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.ASX; - -import java.io.*; -import JACE.OS.*; -import JACE.ASX.*; -import JACE.Reactor.*; - -public class TaskTest extends Task -{ - int nThreads_; - int nIterations_; - - public TaskTest (int nThreads, int nIterations) - { - this.nIterations_ = nIterations; - this.nThreads_ = nThreads; - if (this.activate (0, nThreads, true) == -1) - ACE.ERROR ("activate failed"); - } - - public int open (Object obj) - { - return 0; - } - - public int close (long flags) - { - return 0; - } - - public int put (MessageBlock mb, TimeValue tv) - { - return 0; - } - - public int handleTimeout (TimeValue tv, Object obj) - { - return 0; - } - - public int svc () - { - for (int i = 1; i <= this.nIterations_; i++) - { - ACE.DEBUG (Thread.currentThread ().toString () + " in iteration " + i); - // Allow other threads to run - Thread.yield (); - } - return 0; - } - - public static void main (String args[]) - { - int nThreads = 1; - int nIterations = 1; - try - { - if (args.length == 2) - { - nThreads = Integer.parseInt (args[0]); - nIterations = Integer.parseInt (args[1]); - } - else if (args.length == 1) - { - nThreads = Integer.parseInt (args[0]); - } - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - TaskTest tt = new TaskTest (nThreads, nIterations); - } -} diff --git a/java/tests/ASX/ThreadPoolTest.dsp b/java/tests/ASX/ThreadPoolTest.dsp deleted file mode 100644 index 466c198ae14..00000000000 --- a/java/tests/ASX/ThreadPoolTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="ThreadPoolTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=ThreadPoolTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "ThreadPoolTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "ThreadPoolTest.mak"\
- CFG="ThreadPoolTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "ThreadPoolTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "ThreadPoolTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "ThreadPoolTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "ThreadPoolTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "ThreadPoolTest - Java Virtual Machine Release"
-# Name "ThreadPoolTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\ThreadPoolTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/ASX/ThreadPoolTest.java b/java/tests/ASX/ThreadPoolTest.java deleted file mode 100644 index cfb20f87adb..00000000000 --- a/java/tests/ASX/ThreadPoolTest.java +++ /dev/null @@ -1,185 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.ASX -// -// = FILENAME -// ThreadPoolTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.ASX; - -import java.io.*; -import JACE.OS.*; -import JACE.ASX.*; -import JACE.Reactor.*; - -public class ThreadPoolTest extends Task -{ - int nThreads_; - int nIterations_; - - public static int MAX_MB_SIZE = 1024; - - public ThreadPoolTest (int nThreads, int nIterations) - { - this.nIterations_ = nIterations; - this.nThreads_ = nThreads; - if (this.activate (0, nThreads, true) == -1) - ACE.ERROR ("activate failed"); - } - - public int handleTimeout (TimeValue tv, Object obj) - { - return 0; - } - - public int open (Object obj) - { - return 0; - } - - public int close (long flags) - { - return 0; - } - - public int put (MessageBlock mb, TimeValue tv) - { - try - { - return this.putq (mb, tv); - } - catch (InterruptedException e) - { - } - return 0; - } - - public int svc () - { - int result = 0; - int count = 1; - - // Keep looping, reading a message out of the queue, until we get a - // message with a length == 0, which signals us to quit. - try - { - for (;; count++) - { - MessageBlock mb = this.getq (new TimeValue ()); - if (mb == null) - { - ACE.ERROR (Thread.currentThread ().toString () + " in iteration " + count + ", got result -1, exiting"); - break; - } - int length = mb.length (); - - if (length > 0) - ACE.DEBUG (Thread.currentThread ().toString () + - " in iteration " + count + ", length = " + - length + ", text = \"" + mb.base () + "\""); - - if (length == 0) - { - ACE.DEBUG (Thread.currentThread ().toString () + - " in iteration " + count + - ", got NULL message, exiting"); - break; - } - Thread.yield (); - } - } - catch (InterruptedException e) - { - } - return 0; - } - - public static void produce (ThreadPoolTest threadPool, int nIterations) - { - int count = 0; - for (int n = 0;;) - { - // Allocate a new message. - MessageBlock mb = new MessageBlock (new Integer (count).toString ()); - - if (count == nIterations) - n = 1; // Indicate that we need to shut down. - else - count++; - - if (count == 0 || (count % 20 == 0)) - { - try - { - Thread.sleep (1); - } - catch (InterruptedException e) - { - } - } - if (n != 1) - { - ACE.DEBUG ("Producing..."); - // Pass the message to the Thread_Pool. - if (threadPool.put (mb, new TimeValue ()) == -1) - ACE.ERROR ("put"); - } - else - { - // Send a shutdown message to the waiting threads and exit. - ACE.DEBUG ("start loop, dump of task"); - - for (int i = threadPool.thrCount (); i > 0; i--) - { - ACE.DEBUG (Thread.currentThread ().toString () + - "EOF, enqueueing NULL block for thread " + i); - - // Enqueue a NULL message to flag each consumer to - // shutdown. - if (threadPool.put (new MessageBlock (0), new TimeValue ()) == -1) - ACE.ERROR ("put"); - } - - break; - } - } - } - - public static void main (String args[]) - { - int nThreads = 1; - int nIterations = 100; - try - { - if (args.length == 2) - { - nThreads = Integer.parseInt (args[0]); - nIterations = Integer.parseInt (args[1]); - } - else if (args.length == 1) - { - nThreads = Integer.parseInt (args[0]); - } - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - ACE.DEBUG ("Threads = " + nThreads + " Iterations = " + nIterations); - - // Create the worker tasks. - ThreadPoolTest threadPool = new ThreadPoolTest (nThreads, - nIterations); - - // Create work for the worker tasks to process in their own threads. - produce (threadPool, nIterations); - ACE.DEBUG ("exiting..."); - } -} - - diff --git a/java/tests/Concurrency/Condition/Condition.dsp b/java/tests/Concurrency/Condition/Condition.dsp deleted file mode 100644 index e6d28e19c9a..00000000000 --- a/java/tests/Concurrency/Condition/Condition.dsp +++ /dev/null @@ -1,88 +0,0 @@ -# Microsoft Developer Studio Project File - Name="Condition" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=Condition - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "Condition.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "Condition.mak" CFG="Condition - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "Condition - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "Condition - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "Condition - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "Condition - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "Condition - Java Virtual Machine Release"
-# Name "Condition - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\Consumer.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\JoinableThreadGroup.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\Producer.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\QueueTest.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\SimpleMessageQueue.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/Concurrency/Condition/Consumer.java b/java/tests/Concurrency/Condition/Consumer.java deleted file mode 100644 index ff4f5ff4a4b..00000000000 --- a/java/tests/Concurrency/Condition/Consumer.java +++ /dev/null @@ -1,73 +0,0 @@ -//File: Consumer.java -//Seth Widoff 8/8/96 -//This class attempts at random intervals to dequeue random elements -//from a queue. If the queue is empty the thread waits until an element -//has been enqueued and another thread has invoked the notify() method. - -package tests.Concurrency.Condition; - -import JACE.ASX.TimeValue; -import java.util.Random; - -public class Consumer implements Runnable -{ - //Maximum pause between dequeues (in milliseconds) - private static final int MAX_PAUSE = 1000; - - private SimpleMessageQueue queue_; - private boolean stop_requested_ = false; - private String name_; - private int iterations_; - private TimeValue timeout_; - - public Consumer(String name, - SimpleMessageQueue queue, - int iterations, - TimeValue timeout) - { - name_ = "Consumer " + name; - queue_ = queue; - iterations_ = iterations; - timeout_ = timeout; - } - - public void run() - { - //Set the random number generator seed to the current time in - //milliseconds. - - Random random = new Random(System.currentTimeMillis()); - Integer element; - - for (int i = 0; i < iterations_; ) - { - try - { - element = (Integer)queue_.dequeue(timeout_); - if (element != null) - { - - System.out.print("Consumer::run() " + name_ + " dequeued " + element.toString()); - System.out.println(" Queue size: " + queue_.size()); - - Thread.sleep(random.nextLong() % MAX_PAUSE); - } - else - { - System.out.println ("Null"); - } - i++; - } - catch(Exception excp) - { - System.out.print ("Consumer::run() Exception: "); - System.out.println(excp); - } - } - } - - public void requestStop() - { - stop_requested_ = true; - } -} diff --git a/java/tests/Concurrency/Condition/JoinableThreadGroup.java b/java/tests/Concurrency/Condition/JoinableThreadGroup.java deleted file mode 100644 index c878eb026d3..00000000000 --- a/java/tests/Concurrency/Condition/JoinableThreadGroup.java +++ /dev/null @@ -1,24 +0,0 @@ -package tests.Concurrency.Condition; - -public class JoinableThreadGroup extends ThreadGroup -{ - public JoinableThreadGroup(String name) - { - super(name); - } - - public JoinableThreadGroup(ThreadGroup parent, String name) - { - super(parent, name); - } - - public void join() throws InterruptedException - { - Thread list[] = new Thread[activeCount()]; - - enumerate(list, true); - - for (int i = 0; i < list.length; i++) - list[i].join(); - } -} diff --git a/java/tests/Concurrency/Condition/Makefile b/java/tests/Concurrency/Condition/Makefile deleted file mode 100644 index fd1e6a93677..00000000000 --- a/java/tests/Concurrency/Condition/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -# Makefile - -.SUFFIXES: .java .class - -JACE_WRAPPER = ../../.. -CLASSDIR = $(JACE_WRAPPER)/classes - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - -files = \ - QueueTest.java \ - JoinableThreadGroup.java \ - SimpleMessageQueue.java \ - Producer.java \ - Consumer.java - -packages = tests.Concurrency.Condition; - -realclean: - find ${JACE_WRAPPER}/classes/tests/Concurrency/Condition -name '*.class' -print | xargs ${RM} diff --git a/java/tests/Concurrency/Condition/Producer.java b/java/tests/Concurrency/Condition/Producer.java deleted file mode 100644 index ed6da2251ba..00000000000 --- a/java/tests/Concurrency/Condition/Producer.java +++ /dev/null @@ -1,67 +0,0 @@ -//File: Producer.java -//Seth Widoff 8/8/96 -//This class attempts at random intervals to enqueue random elements -//into a queue. If the queue is full the thread waits until an element -//has been dequeued and another thread has invoked the notify() method. - -package tests.Concurrency.Condition; - -import JACE.ASX.TimeValue; -import java.util.Random; - -public class Producer implements Runnable -{ - //Maximum pause between enqueues (in milliseconds) - private static final int MAX_PAUSE = 1000; - - private SimpleMessageQueue queue_; - private boolean stop_requested_ = false; - private String name_; - private int iterations_; - private TimeValue timeout_; - - public Producer(String name, - SimpleMessageQueue queue, - int iterations, - TimeValue timeout) - { - name_ = "Producer " + name; - queue_ = queue; - iterations_ = iterations; - timeout_ = timeout; - } - - public void run() - { - //Set the random number generator seed to the current time in milliseconds. - Random random = new Random(System.currentTimeMillis()); - int element = 1; - - for (int i = 0; i < iterations_; ) - { - try - { - // element = random.nextInt(); - - queue_.enqueue((Object)new Integer(element), timeout_); - System.out.print("Producer::run() " + name_ + " enqueued " + element); - System.out.println(" Queue size: " + queue_.size()); - - Thread.sleep(random.nextLong() % MAX_PAUSE); - i++; - element++; - } - catch(Exception excp) - { - System.out.print("Producer::run() Exception: "); - System.out.println(excp); - } - } - } - - public void requestStop() - { - stop_requested_ = true; - } -} - diff --git a/java/tests/Concurrency/Condition/QueueTest.java b/java/tests/Concurrency/Condition/QueueTest.java deleted file mode 100644 index 87e7d57bbbd..00000000000 --- a/java/tests/Concurrency/Condition/QueueTest.java +++ /dev/null @@ -1,64 +0,0 @@ -//File: QueueTest.java -//Seth Widoff, 8/8/96 -//This class is a test method for the Producer and Consumer classes. -//The main method takes as arguments the number of producers, the -//number of consumers and the number of elements in the queue. It then -//spawn the specified threads and starts them. - -package tests.Concurrency.Condition; - -import JACE.ASX.TimeValue; - -public class QueueTest -{ - public static void main(String[] args) - { - if (args.length < 5) - { - System.out.println("Usage: java QueueTest <# producers> <# consumers> <# elements> <#iterations> <#timeout secs> <#timeout nano secs>"); - System.exit(1); - } - - int num_producers = Integer.parseInt(args[0]), - num_consumers = Integer.parseInt(args[1]), - num_elements = Integer.parseInt(args[2]), - num_iterations = Integer.parseInt(args[3]), - num_timeout_secs = Integer.parseInt(args[4]), - num_timeout_nano_secs = Integer.parseInt(args[5]); - - if (num_elements < 1 - || num_consumers < 1 - || num_producers < 1) - { - System.out.println("All the parameters must be larger than zero."); - System.exit(1); - } - - SimpleMessageQueue queue = new SimpleMessageQueue(num_elements); - Consumer[] consumers = new Consumer[num_consumers]; - Producer[] producers = new Producer[num_producers]; - JoinableThreadGroup thread_group = new JoinableThreadGroup("Producer Consumer"); - - for (int i = 0; i < num_producers; i++) - { - producers[i] = new Producer("Number " + (i + 1), queue, num_iterations, new TimeValue (num_timeout_secs, num_timeout_nano_secs)); - new Thread(thread_group, producers[i]).start(); - } - - for (int i = 0; i < num_consumers; i++) - { - consumers[i] = new Consumer("Number " + (i + 1), queue, num_iterations, new TimeValue (num_timeout_secs, num_timeout_nano_secs)); - new Thread(thread_group, consumers[i]).start(); - } - - try - { - thread_group.join(); - } - catch(InterruptedException excp) - { - System.out.println("QueueTest::main"); - System.out.println(excp); - } - } -} diff --git a/java/tests/Concurrency/Condition/SimpleMessageQueue.java b/java/tests/Concurrency/Condition/SimpleMessageQueue.java deleted file mode 100644 index bb703516858..00000000000 --- a/java/tests/Concurrency/Condition/SimpleMessageQueue.java +++ /dev/null @@ -1,86 +0,0 @@ -package tests.Concurrency.Condition; - -import JACE.ASX.TimeoutException; -import JACE.ASX.TimeValue; -import JACE.Concurrency.*; - -public class SimpleMessageQueue -{ - private int num_items_ = 0; - private int head_ = 0, tail_ = 0; - private Object[] queue_; - - private Mutex lock_ = new Mutex (); - private Condition notFull_ = new Condition (lock_); - private Condition notEmpty_ = new Condition (lock_); - - public SimpleMessageQueue(int size) - { - queue_ = new Object[size]; - } - - public void enqueue(Object element, TimeValue timeout) - throws TimeoutException, InterruptedException - { - try - { - lock_.acquire (); - while (this.isFull ()) - notFull_.Wait (timeout); - - if (tail_ == queue_.length) - tail_ = 0; - queue_[tail_] = element; - tail_++; - - num_items_++; - notEmpty_.signal (); - } - finally - { - lock_.release (); - } - } - - public Object dequeue (TimeValue timeout) - throws TimeoutException, InterruptedException - { - Object return_value = null; - - try - { - lock_.acquire (); - while (this.isEmpty ()) - notEmpty_.Wait (timeout); - - return_value = queue_[head_]; - head_++; - if (head_ == queue_.length) - head_ = 0; - - num_items_--; - notFull_.signal (); - } - finally - { - lock_.release (); - } - return return_value; - } - - public boolean isEmpty() - { - return num_items_ == 0; - } - - public boolean isFull() - { - return num_items_ == queue_.length; - } - - public int size() - { - return num_items_; - } -} - diff --git a/java/tests/Concurrency/Makefile b/java/tests/Concurrency/Makefile deleted file mode 100644 index f967dffb92f..00000000000 --- a/java/tests/Concurrency/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -# Makefile - -.SUFFIXES: .java .class - -JACE_WRAPPER = ../.. -CLASSDIR = $(JACE_WRAPPER)/classes - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - -files = MutexTest.java \ - SemaphoreTest.java \ - RWMutexTest.java \ - TokenTest.java - -packages = tests.Concurrency - -realclean: - find ${JACE_WRAPPER}/classes/tests/Concurrency -name '*.class' -print | xargs ${RM} diff --git a/java/tests/Concurrency/MutexTest.dsp b/java/tests/Concurrency/MutexTest.dsp deleted file mode 100644 index b430b5f7998..00000000000 --- a/java/tests/Concurrency/MutexTest.dsp +++ /dev/null @@ -1,72 +0,0 @@ -# Microsoft Developer Studio Project File - Name="MutexTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=MutexTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "MutexTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "MutexTest.mak" CFG="MutexTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "MutexTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "MutexTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "MutexTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "MutexTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "MutexTest - Java Virtual Machine Release"
-# Name "MutexTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\MutexTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/Concurrency/MutexTest.java b/java/tests/Concurrency/MutexTest.java deleted file mode 100644 index 680266ef071..00000000000 --- a/java/tests/Concurrency/MutexTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/************************************************* - * - * = PACKAGE - * tests.Concurrency - * - * = FILENAME - * MutexTest.java - * - *@author Prashant Jain - * - *************************************************/ -package tests.Concurrency; - -import java.io.*; -import JACE.OS.*; -import JACE.Concurrency.*; - -class MutexReader extends Thread -{ - MutexReader (int nIterations, Mutex mutex) - { - this.nIterations_ = nIterations; - this.mutex_ = mutex; - } - - public void run () - { - for (int i = 1; i <= this.nIterations_; i++) - { - // Acquire the mutex (will block until it gets it) - try - { - this.mutex_.acquire (); - } - catch (InterruptedException e) - { - ACE.ERROR (e); - } - - MutexTest.count++; - ACE.DEBUG (Thread.currentThread ().toString () + - " reader acquired mutex in iteration " + i + - ", count = " + MutexTest.count); - - try - { - Thread.sleep (1); - } - catch (InterruptedException e) - { - } - // Release the mutex - this.mutex_.release (); - try - { - Thread.sleep (1); - } - catch (InterruptedException e) - { - } - - } - } - - int nIterations_; - Mutex mutex_; -} - -class MutexWriter extends Thread -{ - MutexWriter (int nIterations, Mutex mutex) - { - this.nIterations_ = nIterations; - this.mutex_ = mutex; - } - - public void run () - { - for (int i = 1; i <= this.nIterations_; i++) - { - // Acquire the mutex (will block until it gets it) - try - { - this.mutex_.acquire (); - } - catch (InterruptedException e) - { - ACE.ERROR (e); - } - - MutexTest.count++; - ACE.DEBUG (Thread.currentThread ().toString () + - " writer acquired mutex in iteration " + i + - ", count = " + MutexTest.count); - - try - { - Thread.sleep (1); - } - catch (InterruptedException e) - { - } - - // Release the mutex - this.mutex_.release (); - try - { - Thread.sleep (1); - } - catch (InterruptedException e) - { - } - - } - } - - int nIterations_; - Mutex mutex_; -} - -public class MutexTest -{ - public static void main (String args[]) - { - int nReaders = 1; - int nWriters = 1; - int nIterations = 100; - int i; - try - { - if (args.length == 3) - { - nReaders = Integer.parseInt (args[0]); - nWriters = Integer.parseInt (args[1]); - nIterations = Integer.parseInt (args[2]); - } - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - - // Create a lock - Mutex mutex = new Mutex (); - - // Now spawn off the readers and writers - for (i = 0; i < nReaders; i++) - new MutexReader (nIterations, mutex).start (); - - for (i = 0; i < nWriters; i++) - new MutexWriter (nIterations, mutex).start (); - } - public static int count; -} diff --git a/java/tests/Concurrency/RWMutexTest.dsp b/java/tests/Concurrency/RWMutexTest.dsp deleted file mode 100644 index 96a88a32208..00000000000 --- a/java/tests/Concurrency/RWMutexTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="RWMutexTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=RWMutexTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "RWMutexTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "RWMutexTest.mak"\
- CFG="RWMutexTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "RWMutexTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "RWMutexTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "RWMutexTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "RWMutexTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "RWMutexTest - Java Virtual Machine Release"
-# Name "RWMutexTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\RWMutexTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/Concurrency/RWMutexTest.java b/java/tests/Concurrency/RWMutexTest.java deleted file mode 100644 index ab28c9a83fd..00000000000 --- a/java/tests/Concurrency/RWMutexTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/************************************************* - * - * = PACKAGE - * tests.Concurrency - * - * = FILENAME - * RWMutexTest.java - * - *@author Ross Dargahi (rossd@krinfo.com) - * - *************************************************/ -package tests.Concurrency; - -import JACE.OS.*; -import JACE.Concurrency.*; - -class TestThread extends Thread -{ - TestThread(String name, - boolean writer, - RWMutex lock) - { - super (name); - mWriter = writer; - mLock = lock; - } - - public void run() - { - for (int i = 0; i < 10; i++) - { - try - { - if (!mWriter) - { - mLock.acquireRead(); - ACE.DEBUG (getName() + ": Acquired Read Lock"); - - int sleepTime = i * 100; - sleep (sleepTime); - - mLock.release (); - ACE.DEBUG (getName () + ": Released Read Lock"); - } - else - { - mLock.acquireWrite (); - ACE.DEBUG (getName () + ": Acquired Write Lock"); - - int sleepTime = i * 100; - sleep (sleepTime); - - mLock.release (); - ACE.DEBUG (getName () + ": Released Write Lock"); - } - } - catch (InterruptedException ex) - { - ACE.ERROR ("InterruptedException"); - } - } - } - - RWMutex mLock; - boolean mWriter; -} - -public class RWMutexTest -{ - public static void main(String [] args) - { - RWMutex lock = new RWMutex(); - - TestThread t1 = new TestThread ("1", false, lock); - TestThread t2 = new TestThread ("2", false, lock); - TestThread t3 = new TestThread ("3", false, lock); - TestThread t4 = new TestThread ("4", true, lock); - TestThread t5 = new TestThread ("5", false, lock); - TestThread t6 = new TestThread ("6", false, lock); - TestThread t7 = new TestThread ("7", false, lock); - TestThread t8 = new TestThread ("8", true, lock); - - t1.start (); - t2.start (); - t3.start (); - t4.start (); - t5.start (); - t6.start (); - t7.start (); - t8.start (); - } -} - diff --git a/java/tests/Concurrency/SemaphoreTest.dsp b/java/tests/Concurrency/SemaphoreTest.dsp deleted file mode 100644 index 2bc61986361..00000000000 --- a/java/tests/Concurrency/SemaphoreTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="SemaphoreTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=SemaphoreTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "SemaphoreTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "SemaphoreTest.mak"\
- CFG="SemaphoreTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "SemaphoreTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "SemaphoreTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "SemaphoreTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "SemaphoreTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "SemaphoreTest - Java Virtual Machine Release"
-# Name "SemaphoreTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\SemaphoreTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/Concurrency/SemaphoreTest.java b/java/tests/Concurrency/SemaphoreTest.java deleted file mode 100644 index b45929daa55..00000000000 --- a/java/tests/Concurrency/SemaphoreTest.java +++ /dev/null @@ -1,102 +0,0 @@ -/************************************************* - * - * = PACKAGE - * tests.Concurrency - * - * = FILENAME - * SemaphoreTest.java - * - *@author Prashant Jain - * - *************************************************/ -package tests.Concurrency; - -import java.io.*; -import JACE.OS.*; -import JACE.Concurrency.*; - -class SemaphoreWriter extends Thread -{ - SemaphoreWriter (int nIterations, Semaphore s) - { - this.nIterations_ = nIterations; - this.s_ = s; - } - - public void run () - { - for (int i = 1; i <= this.nIterations_; i++) - { - // Acquire the semaphore (will block until it gets it) - try - { - this.s_.acquire (); - } - catch (InterruptedException e) - { - ACE.ERROR (e); - } - - SemaphoreTest.counter++; - ACE.DEBUG (Thread.currentThread ().toString () + - " acquired semaphore in iteration " + i + - ", counter = " + SemaphoreTest.counter); - - try - { - Thread.sleep (1); - } - catch (InterruptedException e) - { - } - - // Release the semaphore - this.s_.release (); - ACE.DEBUG (Thread.currentThread ().toString () + - " released semaphore in iteration " + i); - try - { - Thread.sleep (1); - } - catch (InterruptedException e) - { - } - - } - } - - int nIterations_; - Semaphore s_; -} - -public class SemaphoreTest -{ - public static void main (String args[]) - { - int nThreads = 1; - int count = 1; - int nIterations = 100; - int i; - try - { - if (args.length == 3) - { - nThreads = Integer.parseInt (args[0]); - count = Integer.parseInt (args[1]); - nIterations = Integer.parseInt (args[2]); - } - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - - // Create a lock - Semaphore s = new Semaphore (count); - - // Spawn off n_threads - for (i = 0; i < nThreads; i++) - new SemaphoreWriter (nIterations, s).start (); - } - public static int counter; -} diff --git a/java/tests/Concurrency/TokenTest.dsp b/java/tests/Concurrency/TokenTest.dsp deleted file mode 100644 index f0a1f87345e..00000000000 --- a/java/tests/Concurrency/TokenTest.dsp +++ /dev/null @@ -1,72 +0,0 @@ -# Microsoft Developer Studio Project File - Name="TokenTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=TokenTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "TokenTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "TokenTest.mak" CFG="TokenTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "TokenTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "TokenTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "TokenTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "TokenTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "TokenTest - Java Virtual Machine Release"
-# Name "TokenTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\TokenTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/Concurrency/TokenTest.java b/java/tests/Concurrency/TokenTest.java deleted file mode 100644 index ededed9fed9..00000000000 --- a/java/tests/Concurrency/TokenTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/************************************************* - * - * = PACKAGE - * tests.Concurrency - * - * = FILENAME - * TokenTest.java - * - *@author Prashant Jain - * - *************************************************/ -package tests.Concurrency; - -import java.io.*; -import JACE.OS.*; -import JACE.Concurrency.*; - -class MyToken extends Token -{ - public void sleepHook () - { - ACE.DEBUG (Thread.currentThread () + " blocking, sleepHook called"); - } -} - -public class TokenTest implements Runnable -{ - public void run () - { - try - { - this.token_.acquire (); - ACE.DEBUG (Thread.currentThread () + " acquired token"); - this.token_.acquire (); - ACE.DEBUG (Thread.currentThread () + " acquired token"); - Thread.sleep (100); - - this.token_.renew (1); - - this.token_.release (); - ACE.DEBUG (Thread.currentThread () + " released token"); - this.token_.release (); - ACE.DEBUG (Thread.currentThread () + " released token"); - } - catch (InterruptedException e) - { - this.token_.release (); - } - } - - public static void main (String args []) - { - ThreadManager tm = new ThreadManager (); - int n = 1; - try - { - if (args.length == 1) - { - n = Integer.parseInt (args[0]); - } - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - - tm.spawnN (n, - new TokenTest (), - false); - } - - private MyToken token_ = new MyToken (); -} diff --git a/java/tests/Connection/AcceptorTest.dsp b/java/tests/Connection/AcceptorTest.dsp deleted file mode 100644 index c4295c34732..00000000000 --- a/java/tests/Connection/AcceptorTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="AcceptorTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=AcceptorTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "AcceptorTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "AcceptorTest.mak"\
- CFG="AcceptorTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "AcceptorTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "AcceptorTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "AcceptorTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "AcceptorTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "AcceptorTest - Java Virtual Machine Release"
-# Name "AcceptorTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\AcceptorTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/Connection/AcceptorTest.java b/java/tests/Connection/AcceptorTest.java deleted file mode 100644 index 0f8877f52d9..00000000000 --- a/java/tests/Connection/AcceptorTest.java +++ /dev/null @@ -1,79 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.Connection -// -// = FILENAME -// AcceptorTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.Connection.*; - -public class AcceptorTest -{ - void print_usage_and_die () - { - System.out.println ("Usage: test_server [<port>]"); - System.exit (0); - } - - public void init (int port) - { - try - { - Acceptor acceptor = new Acceptor (Class.forName ("tests.Connection.ServerHandler")); - acceptor.open (port); - while (true) - { - acceptor.accept (); - } - } - catch (ClassNotFoundException e) - { - ACE.ERROR (e); - } - catch (SocketException e) - { - ACE.ERROR ("Socket Exception: " + e); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR ("Dang!" + e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - } - - public static void main (String [] args) - { - int port = ACE.DEFAULT_SERVER_PORT; - AcceptorTest acceptorTest = new AcceptorTest (); - - if (args.length == 1) - { - try - { - port = Integer.parseInt (args[0]); - } - catch (NumberFormatException e) - { - acceptorTest.print_usage_and_die (); - } - } - acceptorTest.init (port); - } -} diff --git a/java/tests/Connection/ClientHandler.dsp b/java/tests/Connection/ClientHandler.dsp deleted file mode 100644 index e9bf0f6fc4d..00000000000 --- a/java/tests/Connection/ClientHandler.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="ClientHandler" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=ClientHandler - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "ClientHandler.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "ClientHandler.mak"\
- CFG="ClientHandler - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "ClientHandler - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "ClientHandler - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "ClientHandler - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "ClientHandler - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "ClientHandler - Java Virtual Machine Release"
-# Name "ClientHandler - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\ClientHandler.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/Connection/ClientHandler.java b/java/tests/Connection/ClientHandler.java deleted file mode 100644 index a18f7740cce..00000000000 --- a/java/tests/Connection/ClientHandler.java +++ /dev/null @@ -1,77 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.Connection -// -// = FILENAME -// ClientHandler.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.Connection.*; - -public class ClientHandler extends SvcHandler -{ - public ClientHandler () - { - } - - public int open (Object obj) - { - new Thread (this).start (); - return 0; - } - - public void run () - { - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - - String msg; - StringBuffer ack = new StringBuffer (); - int ack_len; - try - { - while (true) - { - System.out.print ("Enter input: "); - System.out.flush (); - msg = in.readLine (); - if (msg == null) - break; - this.peer ().send (new StringBuffer (msg)); - System.out.println ("Waiting for ack..."); - ack_len = this.peer ().recv (ack); - if (ack_len == 0) - break; - else - System.out.println (ack); - } - } - catch (NullPointerException e) - { - ACE.ERROR ("connection reset by peer"); - } - catch (IOException e) - { - ACE.ERROR (e); - } - finally - { - try - { - this.peer ().close (); - } - catch (IOException e) - { - } - } - - } -} diff --git a/java/tests/Connection/ConnectorTest.dsp b/java/tests/Connection/ConnectorTest.dsp deleted file mode 100644 index 221581c72fe..00000000000 --- a/java/tests/Connection/ConnectorTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="ConnectorTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=ConnectorTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "ConnectorTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "ConnectorTest.mak"\
- CFG="ConnectorTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "ConnectorTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "ConnectorTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "ConnectorTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "ConnectorTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "ConnectorTest - Java Virtual Machine Release"
-# Name "ConnectorTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\ConnectorTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/Connection/ConnectorTest.java b/java/tests/Connection/ConnectorTest.java deleted file mode 100644 index 605d5e7a400..00000000000 --- a/java/tests/Connection/ConnectorTest.java +++ /dev/null @@ -1,76 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.Connection -// -// = FILENAME -// ConnectorTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.Connection.*; - -public class ConnectorTest -{ - void print_usage_and_die () - { - System.out.println ("Usage: test_Connector <hostname> [<port>]"); - System.exit (0); - } - - public void init (String hostname, int port) - { - try - { - Connector connector = new Connector (); - connector.open (hostname, port); - connector.connect (new ClientHandler ()); - } - catch (UnknownHostException e) - { - ACE.ERROR (e); - } - catch (SocketException e) - { - ACE.ERROR ("Connection refused"); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - } - - public static void main (String [] args) - { - int port = ACE.DEFAULT_SERVER_PORT; - ConnectorTest connectorTest = new ConnectorTest (); - - if (args.length == 2) - { - try - { - port = Integer.parseInt (args[1]); - } - catch (NumberFormatException e) - { - connectorTest.print_usage_and_die (); - } - } - connectorTest.init (args[0], port); - } -} diff --git a/java/tests/Connection/HTTPHelperTest.java b/java/tests/Connection/HTTPHelperTest.java deleted file mode 100644 index 02a16d838af..00000000000 --- a/java/tests/Connection/HTTPHelperTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package tests.Connection; - -import java.io.*; -import JACE.Connection.*; - -public class HTTPHelperTest -{ - public static void main(String args[]) - { - // This is just a quick test to confirm that the Base 64 encoding and decoding work - // (tests the example given in the HTTP 1.1 RFC) - - String secret = "Aladdin:open sesame"; - - String encoded = JACE.Connection.HTTPHelper.EncodeBase64(secret); - - System.err.println("Encoding string: " + secret); - - System.err.println("Result: " + encoded); - - System.err.println("Is this right? " + (encoded.equals("QWxhZGRpbjpvcGVuIHNlc2FtZQ==") ? "Yes" : "No")); - - // Decode should also be tested - // - } -}; - diff --git a/java/tests/Connection/Makefile b/java/tests/Connection/Makefile deleted file mode 100644 index f58878033e0..00000000000 --- a/java/tests/Connection/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -# Makefile -# $Id$ - -.SUFFIXES: .java .class - -JACE_WRAPPER = ../.. -CLASSDIR = $(JACE_WRAPPER)/classes - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - - -files = ServerHandler.java \ - ClientHandler.java \ - ConnectorTest.java \ - AcceptorTest.java \ - HTTPHelperTest.java - -packages = tests.Connection - -realclean: - find ${JACE_WRAPPER}/classes/tests/Connection -name '*.class' -print | xargs ${RM} diff --git a/java/tests/Connection/ServerHandler.dsp b/java/tests/Connection/ServerHandler.dsp deleted file mode 100644 index 13aff2843e3..00000000000 --- a/java/tests/Connection/ServerHandler.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="ServerHandler" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=ServerHandler - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "ServerHandler.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "ServerHandler.mak"\
- CFG="ServerHandler - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "ServerHandler - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "ServerHandler - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "ServerHandler - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "ServerHandler - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "ServerHandler - Java Virtual Machine Release"
-# Name "ServerHandler - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\ServerHandler.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/Connection/ServerHandler.java b/java/tests/Connection/ServerHandler.java deleted file mode 100644 index 7cdd50d7d37..00000000000 --- a/java/tests/Connection/ServerHandler.java +++ /dev/null @@ -1,68 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.Connection -// -// = FILENAME -// ServerHandler.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.Connection; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.Connection.*; - -public class ServerHandler extends SvcHandler -{ - public ServerHandler () - { - } - - public int open (Object obj) - { - new Thread (this).start (); - return 0; - } - - public void run () - { - int msg_len; - System.out.println ("Waiting for messages..."); - try - { - while (true) - { - StringBuffer msg = new StringBuffer (); - msg_len = this.peer ().recv (msg); - if (msg_len == 0) - break; - System.out.println ("Received: " + msg); - this.peer ().send (new StringBuffer ("Got it!")); - } - } - catch (NullPointerException e) - { - ACE.ERROR ("connection reset by peer"); - } - catch (IOException e) - { - ACE.ERROR (e); - } - finally - { - try - { - this.peer ().close (); - } - catch (IOException e) - { - } - } - - } -} diff --git a/java/tests/Misc/Makefile b/java/tests/Misc/Makefile deleted file mode 100644 index 2ea3d10fba5..00000000000 --- a/java/tests/Misc/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -# Makefile - -.SUFFIXES: .java .class - -JACE_WRAPPER = ../.. -CLASSDIR = $(JACE_WRAPPER)/classes - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - - -files = ParseArgsTest.java - -packages = tests.Misc - -realclean: - find ${JACE_WRAPPER}/classes/tests/Misc -name '*.class' -print | xargs ${RM} diff --git a/java/tests/Misc/ParseArgsTest.dsp b/java/tests/Misc/ParseArgsTest.dsp deleted file mode 100644 index 8befbaf1911..00000000000 --- a/java/tests/Misc/ParseArgsTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="ParseArgsTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=ParseArgsTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "ParseArgsTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "ParseArgsTest.mak"\
- CFG="ParseArgsTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "ParseArgsTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "ParseArgsTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "ParseArgsTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "ParseArgsTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "ParseArgsTest - Java Virtual Machine Release"
-# Name "ParseArgsTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\ParseArgsTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/Misc/ParseArgsTest.java b/java/tests/Misc/ParseArgsTest.java deleted file mode 100644 index 5baddd2745d..00000000000 --- a/java/tests/Misc/ParseArgsTest.java +++ /dev/null @@ -1,45 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.Misc -// -// = FILENAME -// ParseArgsTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.Misc; - -import JACE.OS.*; -import JACE.Misc.*; - -public class ParseArgsTest -{ - public static void main (String args[]) - { - String s; - GetOpt opt = new GetOpt (args, "p:rs:"); - for (int c; (c = opt.next ()) != -1; ) - { - switch (c) - { - case 'p': - s = opt.optarg (); - ACE.DEBUG ("Option <p> selected with argument " + s); - break; - case 'r': - ACE.DEBUG ("Option <r> selected"); - break; - case 's': - s = opt.optarg (); - ACE.DEBUG ("Option <s> selected with argument " + s); - break; - default: - ACE.DEBUG ("Usage: java tests.Misc.ParseArgsTest [-p arg1] [-r] [-s arg2]"); - break; - } - } - } -} diff --git a/java/tests/Reactor/Makefile b/java/tests/Reactor/Makefile deleted file mode 100644 index f55573a89cb..00000000000 --- a/java/tests/Reactor/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -# Makefile - -.SUFFIXES: .java .class - -JACE_WRAPPER = ../.. -CLASSDIR = $(JACE_WRAPPER)/classes - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - - -files = TimeValueTest.java \ - TimerQueueTest.java - -packages = tests.Reactor - -realclean: - find ${JACE_WRAPPER}/classes/tests/Reactor -name '*.class' -print | xargs ${RM} diff --git a/java/tests/Reactor/TimeValueTest.dsp b/java/tests/Reactor/TimeValueTest.dsp deleted file mode 100644 index 5a957758046..00000000000 --- a/java/tests/Reactor/TimeValueTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="TimeValueTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=TimeValueTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "TimeValueTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "TimeValueTest.mak"\
- CFG="TimeValueTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "TimeValueTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "TimeValueTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "TimeValueTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "TimeValueTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "TimeValueTest - Java Virtual Machine Release"
-# Name "TimeValueTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\TimeValueTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/Reactor/TimeValueTest.java b/java/tests/Reactor/TimeValueTest.java deleted file mode 100644 index b4f3e420ae1..00000000000 --- a/java/tests/Reactor/TimeValueTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/************************************************* - * - * = PACKAGE - * ACE.Reactor - * - * = FILENAME - * TimeValueTest.java - * - *@author Prashant Jain - * - *************************************************/ -package tests.Reactor; - -import JACE.OS.*; -import JACE.ASX.*; - -public class TimeValueTest -{ - public void ASSERT (boolean expression, int i) - { - if (!expression) - ACE.DEBUG ("ASSERT failed for " + i); - } - - public void runTest () - { - TimeValue tv1 = new TimeValue (); - TimeValue tv2 = new TimeValue (2); - TimeValue tv3 = new TimeValue (100); - TimeValue tv4 = new TimeValue (1, 1000000000); - TimeValue tv5 = new TimeValue (2); - TimeValue tv6 = new TimeValue (1, -1000000000); - - this.ASSERT (tv1.equals (new TimeValue (0)), 1); - this.ASSERT (tv2.lessThan (tv3), 2); - this.ASSERT (tv2.lessThanEqual (tv2), 3); - this.ASSERT (tv2.greaterThanEqual (tv4), 4); - this.ASSERT (tv5.greaterThanEqual (tv6), 5); - this.ASSERT (tv2.equals (new TimeValue (1, 1000000000)), 6); - this.ASSERT (tv5.equals (tv4), 7); - this.ASSERT (tv2.equals (tv4), 8); - this.ASSERT (tv1.notEquals (tv2), 9); - this.ASSERT (tv6.equals (tv1), 10); - } - - public static void main (String [] args) - { - new TimeValueTest ().runTest (); - } -} diff --git a/java/tests/Reactor/TimerQueueTest.dsp b/java/tests/Reactor/TimerQueueTest.dsp deleted file mode 100644 index 35f52adbea0..00000000000 --- a/java/tests/Reactor/TimerQueueTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="TimerQueueTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=TimerQueueTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "TimerQueueTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "TimerQueueTest.mak"\
- CFG="TimerQueueTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "TimerQueueTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "TimerQueueTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "TimerQueueTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "TimerQueueTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "TimerQueueTest - Java Virtual Machine Release"
-# Name "TimerQueueTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\TimerQueueTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/Reactor/TimerQueueTest.java b/java/tests/Reactor/TimerQueueTest.java deleted file mode 100644 index d34439dcf9b..00000000000 --- a/java/tests/Reactor/TimerQueueTest.java +++ /dev/null @@ -1,80 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.Reactor -// -// = FILENAME -// TimerQueueTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.Reactor; - -import JACE.OS.*; -import JACE.ASX.*; -import JACE.Reactor.*; - -public class TimerQueueTest implements EventHandler -{ - public int handleTimeout (TimeValue tv, Object obj) - { - ACE.DEBUG ("handleTimeout: " + tv.toString () + " " + (String) obj); - return 0; - } - - public static void main (String args []) - { - TimerQueue tq = new TimerQueue (true); - TimerQueueTest th1 = new TimerQueueTest (); - int n = 5; - - try - { - if (args.length == 1) - { - n = Integer.parseInt (args[0]); - } - } - catch (NumberFormatException e) - { - ACE.ERROR ("Illegal argument."); - } - - // Set a periodic timer - int id= tq.scheduleTimer (th1, - "periodic", - new TimeValue (2), - new TimeValue (3)); - - int i; - // Set a bunch of single timers - for (i=1; i <= n; i++) - { - tq.scheduleTimer (th1, - "A-timer-" + new Integer (i), - new TimeValue (i*2)); - } - - TimerQueueTest th2 = new TimerQueueTest (); - for (i=1; i <= n; i++) - { - tq.scheduleTimer (th2, - "B-timer-" + new Integer (i), - new TimeValue (i*3)); - } - // Cancel all timers associated with this handler - tq.cancelTimer (th2); - - try - { - Thread.sleep (30000); - } - catch (InterruptedException e) - { - } - tq.cancelTimer (id); - System.exit (0); - } -} diff --git a/java/tests/SOCK_SAP/Makefile b/java/tests/SOCK_SAP/Makefile deleted file mode 100644 index 1481d8e566f..00000000000 --- a/java/tests/SOCK_SAP/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -# Makefile - -.SUFFIXES: .java .class - -JACE_WRAPPER = ../.. -CLASSDIR = $(JACE_WRAPPER)/classes - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - - -files = SOCKConnectorTest.java \ - SOCKAcceptorTest.java - -packages = tests.SOCK_SAP - -realclean: - find ${JACE_WRAPPER}/classes/tests/SOCK_SAP -name '*.class' -print | xargs ${RM} diff --git a/java/tests/SOCK_SAP/SOCKAcceptorTest.dsp b/java/tests/SOCK_SAP/SOCKAcceptorTest.dsp deleted file mode 100644 index e49c3a8e7ff..00000000000 --- a/java/tests/SOCK_SAP/SOCKAcceptorTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="SOCKAcceptorTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=SOCKAcceptorTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "SOCKAcceptorTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "SOCKAcceptorTest.mak"\
- CFG="SOCKAcceptorTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "SOCKAcceptorTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "SOCKAcceptorTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "SOCKAcceptorTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "SOCKAcceptorTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "SOCKAcceptorTest - Java Virtual Machine Release"
-# Name "SOCKAcceptorTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\SOCKAcceptorTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/SOCK_SAP/SOCKAcceptorTest.java b/java/tests/SOCK_SAP/SOCKAcceptorTest.java deleted file mode 100644 index 34ab8ecb6c9..00000000000 --- a/java/tests/SOCK_SAP/SOCKAcceptorTest.java +++ /dev/null @@ -1,108 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.SOCK_SAP -// -// = FILENAME -// SOCKAcceptorTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.SOCK_SAP; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.SOCK_SAP.*; - -class TestHandler extends Thread -{ - public TestHandler (SOCKStream stream) - { - this.stream_ = stream; - this.start (); - } - - public void run () - { - int msgLen; - System.out.println ("Waiting for messages..."); - try - { - while (true) - { - StringBuffer msg = new StringBuffer (); - msgLen = this.stream_.recv (msg); - if (msgLen == 0) - break; - ACE.DEBUG ("Received: " + msg); - this.stream_.send ("Got it!"); - } - } - catch (NullPointerException e) - { - ACE.ERROR ("connection reset by peer"); - } - catch (IOException e) - { - ACE.ERROR (e); - } - finally - { - try - { - this.stream_.close (); - } - catch (IOException e) - { - } - } - } - SOCKStream stream_; -} - -public class SOCKAcceptorTest -{ - void print_usage_and_die () - { - ACE.DEBUG ("Usage: SOCKAcceptorTest [<port>]"); - System.exit (0); - } - - public void init (int port) - { - try - { - SOCKAcceptor acceptor = new SOCKAcceptor (port); - while (true) - { - SOCKStream stream = new SOCKStream (); - acceptor.accept (stream); - TestHandler handler = new TestHandler (stream); - } - } - catch (IOException e) - { - } - } - - public static void main (String [] args) - { - int port = ACE.DEFAULT_SERVER_PORT; - SOCKAcceptorTest server = new SOCKAcceptorTest (); - if (args.length == 1) - { - try - { - port = Integer.parseInt (args[0]); - } - catch (NumberFormatException e) - { - server.print_usage_and_die (); - } - } - server.init (port); - } -} diff --git a/java/tests/SOCK_SAP/SOCKConnectorTest.dsp b/java/tests/SOCK_SAP/SOCKConnectorTest.dsp deleted file mode 100644 index a075359a071..00000000000 --- a/java/tests/SOCK_SAP/SOCKConnectorTest.dsp +++ /dev/null @@ -1,73 +0,0 @@ -# Microsoft Developer Studio Project File - Name="SOCKConnectorTest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=SOCKConnectorTest - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "SOCKConnectorTest.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "SOCKConnectorTest.mak"\
- CFG="SOCKConnectorTest - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "SOCKConnectorTest - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "SOCKConnectorTest - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "SOCKConnectorTest - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "SOCKConnectorTest - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "SOCKConnectorTest - Java Virtual Machine Release"
-# Name "SOCKConnectorTest - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\SOCKConnectorTest.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/SOCK_SAP/SOCKConnectorTest.java b/java/tests/SOCK_SAP/SOCKConnectorTest.java deleted file mode 100644 index d1fdacc48a4..00000000000 --- a/java/tests/SOCK_SAP/SOCKConnectorTest.java +++ /dev/null @@ -1,95 +0,0 @@ -// ============================================================================ -// -// = PACKAGE -// tests.SOCK_SAP -// -// = FILENAME -// SOCKConnectorTest.java -// -// = AUTHOR -// Prashant Jain -// -// ============================================================================ -package tests.SOCK_SAP; - -import java.io.*; -import java.net.*; -import JACE.OS.*; -import JACE.SOCK_SAP.*; - -public class SOCKConnectorTest -{ - static void print_usage_and_die () - { - System.out.println ("Usage: SOCKConnectorTest <hostname> [<port>]"); - System.exit (0); - } - - void processRequests (SOCKStream stream) throws IOException - { - // 1.0 JDK DataInputStream in = new DataInputStream (System.in); - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - String msg; - int ack_len; - - while (true) - { - StringBuffer ack = new StringBuffer (); - ACE.DEBUG ("Enter input: "); - ACE.FLUSH (); - msg = in.readLine (); - if (msg == null) - break; - stream.send (msg); - ACE.DEBUG ("Waiting for ack..."); - ack_len = stream.recv (ack); - if (ack_len == 0) - break; - else - ACE.DEBUG (ack.toString ()); - } - } - - public void init (String host, int port) - { - SOCKStream stream = new SOCKStream (); - SOCKConnector connector = new SOCKConnector (); - try - { - connector.connect (stream, - host, - port); - processRequests (stream); - } - catch (IOException e) - { - ACE.ERROR (e); - } - } - - public static void main (String [] args) - { - int port = ACE.DEFAULT_SERVER_PORT; - SOCKConnectorTest client = new SOCKConnectorTest (); - - // check arg count - if (args.length == 0 || args.length > 2) - print_usage_and_die(); - - if (args.length == 2) - { - try - { - port = Integer.parseInt (args[1]); - } - catch (NumberFormatException e) - { - client.print_usage_and_die (); - } - } - client.init (args[0], port); - - - } -} - diff --git a/java/tests/ServiceConfigurator/Makefile b/java/tests/ServiceConfigurator/Makefile deleted file mode 100644 index b4e62f70997..00000000000 --- a/java/tests/ServiceConfigurator/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -# Makefile - -.SUFFIXES: .java .class - -JACE_WRAPPER = ../.. -CLASSDIR = $(JACE_WRAPPER)/classes - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - - -files = TestService.java \ - reloadTest.java \ - suspendTest.java - -packages = tests.Service_Configurator - -realclean: - find ${JACE_WRAPPER}/classes/tests/ServiceConfigurator -name '*.class' -print | xargs ${RM} - - diff --git a/java/tests/ServiceConfigurator/ServiceConfigurator.dsp b/java/tests/ServiceConfigurator/ServiceConfigurator.dsp deleted file mode 100644 index ab006d72da8..00000000000 --- a/java/tests/ServiceConfigurator/ServiceConfigurator.dsp +++ /dev/null @@ -1,81 +0,0 @@ -# Microsoft Developer Studio Project File - Name="ServiceConfigurator" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Java Virtual Machine Java Project" 0x0809
-
-CFG=ServiceConfigurator - Java Virtual Machine Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE
-!MESSAGE NMAKE /f "ServiceConfigurator.mak".
-!MESSAGE
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE
-!MESSAGE NMAKE /f "ServiceConfigurator.mak"\
- CFG="ServiceConfigurator - Java Virtual Machine Debug"
-!MESSAGE
-!MESSAGE Possible choices for configuration are:
-!MESSAGE
-!MESSAGE "ServiceConfigurator - Java Virtual Machine Release" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE "ServiceConfigurator - Java Virtual Machine Debug" (based on\
- "Java Virtual Machine Java Project")
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-JAVA=jvc.exe
-
-!IF "$(CFG)" == "ServiceConfigurator - Java Virtual Machine Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\classes-r"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /O
-# ADD JAVA /O
-
-!ELSEIF "$(CFG)" == "ServiceConfigurator - Java Virtual Machine Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir ""
-# PROP BASE Intermediate_Dir ""
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "..\..\classes"
-# PROP Intermediate_Dir ""
-# PROP Target_Dir ""
-# ADD BASE JAVA /g
-# ADD JAVA /g
-
-!ENDIF
-
-# Begin Target
-
-# Name "ServiceConfigurator - Java Virtual Machine Release"
-# Name "ServiceConfigurator - Java Virtual Machine Debug"
-# Begin Source File
-
-SOURCE=.\reloadTest.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\suspendTest.java
-# End Source File
-# Begin Source File
-
-SOURCE=.\TestService.java
-# End Source File
-# End Target
-# End Project
diff --git a/java/tests/ServiceConfigurator/TestService.java b/java/tests/ServiceConfigurator/TestService.java deleted file mode 100644 index 7b34c181c60..00000000000 --- a/java/tests/ServiceConfigurator/TestService.java +++ /dev/null @@ -1,52 +0,0 @@ -/************************************************* - * - * = PACKAGE - * tests.ServiceConfigurator - * - * = FILENAME - * TestService.java - * - *@author Prashant Jain - * - *************************************************/ -package tests.ServiceConfigurator; - -import JACE.ServiceConfigurator.*; -import JACE.OS.*; - -public class TestService extends ServiceObject -{ - public int init (String [] args) - { - System.out.println("TestService init with arguments: "); - - if (args != null) - for (int i = 0; i < args.length; i++) - ACE.DEBUG (args[i]); - - return 0; - } - - public int suspend() - { - System.out.println("TestService suspend ----"); - - return 0; - } - - public int resume() - { - System.out.println("TestService resume ----"); - - return 0; - } - - public int fini() - { - System.out.println("TestService remove ----"); - - return 0; - } - -} - diff --git a/java/tests/ServiceConfigurator/reloadTest.java b/java/tests/ServiceConfigurator/reloadTest.java deleted file mode 100644 index 27806890239..00000000000 --- a/java/tests/ServiceConfigurator/reloadTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/************************************************* - * - * = PACKAGE - * tests.ServiceConfigurator - * - * = FILENAME - * mainTest.java - * - *@author Prashant Jain, Everett Anderson - * - *************************************************/ -package tests.ServiceConfigurator; - -import JACE.ServiceConfigurator.*; -import JACE.OS.*; -import java.io.*; - -public class reloadTest -{ - - public static void main (String args []) - { - ServiceConfig daemon = new ServiceConfig (); - try - { - daemon.open (args); - Thread.sleep (10000); - - daemon.remove("TimeService"); - - daemon.open (args); - } - catch (InterruptedException e) - { - ACE.ERROR (e); - } - catch (FileNotFoundException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - catch (ClassNotFoundException e) - { - ACE.ERROR (e + "foo"); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - - System.err.println("End of reloadTest"); - } - -} diff --git a/java/tests/ServiceConfigurator/suspendTest.java b/java/tests/ServiceConfigurator/suspendTest.java deleted file mode 100644 index ab12d06f2f5..00000000000 --- a/java/tests/ServiceConfigurator/suspendTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/************************************************* - * - * = PACKAGE - * tests.ServiceConfigurator - * - * = FILENAME - * mainTest.java - * - *@author Prashant Jain, Everett Anderson - * - *************************************************/ -package tests.ServiceConfigurator; - -import JACE.ServiceConfigurator.*; -import JACE.OS.*; -import java.io.*; - -public class suspendTest -{ - - public static void main (String args []) - { - ServiceConfig daemon = new ServiceConfig (); - ACE.enableDebugging(); - - try - { - String args1 = "-f suspendTest1.conf"; - String[] argv1 = OS.createStringArray(args1, " "); - - daemon.open (argv1); - - Thread.sleep (10000); - - - System.err.println("Suspending"); - String args2 = "-f suspendTest2.conf"; - String[] argv2 = OS.createStringArray(args2, " "); - - daemon.open (argv2); - - Thread.sleep (10000); - - System.err.println("Resuming"); - String args3 = "-f suspendTest3.conf"; - String[] argv3 = OS.createStringArray(args3, " "); - - daemon.open (argv3); - - Thread.sleep(10000); - } - catch (InterruptedException e) - { - ACE.ERROR (e); - } - catch (FileNotFoundException e) - { - ACE.ERROR (e); - } - catch (IOException e) - { - ACE.ERROR (e); - } - catch (ClassNotFoundException e) - { - ACE.ERROR (e + "foo"); - } - catch (IllegalAccessException e) - { - ACE.ERROR (e); - } - catch (InstantiationException e) - { - ACE.ERROR (e); - } - - System.err.println("End of suspendTest"); - } - -} diff --git a/java/tests/ServiceConfigurator/suspendTest1.conf b/java/tests/ServiceConfigurator/suspendTest1.conf deleted file mode 100644 index 983af3234c1..00000000000 --- a/java/tests/ServiceConfigurator/suspendTest1.conf +++ /dev/null @@ -1 +0,0 @@ -load TestService tests.ServiceConfigurator.TestService ServiceObject "-p 10002" diff --git a/java/tests/ServiceConfigurator/suspendTest2.conf b/java/tests/ServiceConfigurator/suspendTest2.conf deleted file mode 100644 index 5cd6cd0fc77..00000000000 --- a/java/tests/ServiceConfigurator/suspendTest2.conf +++ /dev/null @@ -1 +0,0 @@ -suspend TestService diff --git a/java/tests/ServiceConfigurator/suspendTest3.conf b/java/tests/ServiceConfigurator/suspendTest3.conf deleted file mode 100644 index 71250c3acd7..00000000000 --- a/java/tests/ServiceConfigurator/suspendTest3.conf +++ /dev/null @@ -1 +0,0 @@ -resume TestService diff --git a/java/tests/ServiceConfigurator/svc.conf b/java/tests/ServiceConfigurator/svc.conf deleted file mode 100644 index 983af3234c1..00000000000 --- a/java/tests/ServiceConfigurator/svc.conf +++ /dev/null @@ -1 +0,0 @@ -load TestService tests.ServiceConfigurator.TestService ServiceObject "-p 10002" diff --git a/java/tests/Tests.dsw b/java/tests/Tests.dsw deleted file mode 100644 index 5e540af6a72..00000000000 --- a/java/tests/Tests.dsw +++ /dev/null @@ -1,257 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00
-# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
-
-###############################################################################
-
-Project: "AcceptorTest"=.\Connection\AcceptorTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "BufferStreamTest"=.\ASX\BufferStreamTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "ClientHandler"=.\Connection\ClientHandler.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "Condition"=.\Concurrency\Condition\Condition.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "ConnectorTest"=.\Connection\ConnectorTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "MessageQueueTest"=.\ASX\MessageQueueTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "MutexTest"=.\Concurrency\MutexTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "ParseArgsTest"=.\Misc\ParseArgsTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "PriorityBufferTest"=.\ASX\PriorityBufferTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "RWMutexTest"=.\Concurrency\RWMutexTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "SOCKAcceptorTest"=.\SOCK_SAP\SOCKAcceptorTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "SOCKConnectorTest"=.\SOCK_SAP\SOCKConnectorTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "SemaphoreTest"=.\Concurrency\SemaphoreTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "ServerHandler"=.\Connection\ServerHandler.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "ServiceConfigurator"=.\ServiceConfigurator\ServiceConfigurator.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "TaskTest"=.\ASX\TaskTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "ThreadPoolTest"=.\ASX\ThreadPoolTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "TimeValueTest"=.\Reactor\TimeValueTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "TimerQueueTest"=.\Reactor\TimerQueueTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "TokenTest"=.\Concurrency\TokenTest.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Global:
-
-Package=<5>
-{{{
-}}}
-
-Package=<3>
-{{{
-}}}
-
-###############################################################################
-
diff --git a/java/tests/netsvcs/Logger/LoggerTest.java b/java/tests/netsvcs/Logger/LoggerTest.java deleted file mode 100644 index 40ac903a1d3..00000000000 --- a/java/tests/netsvcs/Logger/LoggerTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/************************************************* - * - * = FILENAME - * LoggerTest.java - * - *@author Everett Anderson - * - *************************************************/ -package tests.netsvcs.Logger; - -import JACE.SOCK_SAP.*; -import java.io.*; -import java.net.*; -import JACE.OS.*; -import netsvcs.Logger.LogRecord; - -/** - * - * <p><h2>DESCRIPTION</h2> - * - * <blockquote> - * This is a simple test log client very similar to the direct_logging client of - * C++ ACE. The logging service should correctly receive messages from both - * the C++ and Java version. - * </blockquote> - * - * @see netsvcs.Logger.ServerLoggingAcceptor, netsvcs.Logger.LogRecord - */ -public class LoggerTest { - - /** Command line: <hostname> [<port>] - * - * Creates a "hello world" log message and sends it to the server logging service. - * If no command line arguments are given, it uses ACE.DEFAULT_SERVER_PORT, and the - * current machine for the service location. - * - */ - public static void main(String args[]) - { - if (args.length < 1) { - System.err.println("Use: LoggerTest <host name> [<port>]"); - System.exit(0); - } - - // Set the port - int port = args.length > 1 ? (new Integer(args[1])).intValue() : ACE.DEFAULT_SERVER_PORT; - - SOCKStream cli_stream = new SOCKStream(); - INETAddr remote_addr; - String host; - - // Try to find the host - try { - - host = args[0]; - - remote_addr = new INETAddr(port, host); - - } catch (UnknownHostException uhe) { - ACE.ERROR("UnknownHostException " + uhe); - return; - } - - System.out.println("Connecting to " + host + " on port " + port); - - SOCKConnector con = new SOCKConnector(); - - try { - - // Connect to the service - con.connect(cli_stream, remote_addr); - - } catch (SocketException se) { - - ACE.ERROR("Socket Exception " + se); - return; - - } catch (IOException ie) { - - ACE.ERROR("IOException " + ie); - return; - } - - - // Send a message with priority 4, the current time, - // and 0 for the process ID. - LogRecord record = new LogRecord(4, - System.currentTimeMillis(), - 0); - - // Set the text of the message - record.msgData("hello world"); - - try { - - // Get a transmission system from the socket - OutputStream os = cli_stream.socket().getOutputStream(); - DataOutputStream dos = new DataOutputStream(os); - - // Send it - record.streamOutTo(dos); - - // Close the socket - cli_stream.close(); - - } catch (IOException ie) { - - ACE.ERROR("IOException, loop: " + ie); - return; - } - } -}; - - - - - - - - - - diff --git a/java/tests/netsvcs/Logger/Makefile b/java/tests/netsvcs/Logger/Makefile deleted file mode 100644 index b61b785232a..00000000000 --- a/java/tests/netsvcs/Logger/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -# $Id$ - -.SUFFIXES: .java .class - -JACE_WRAPPER = $(ACE_ROOT)/java - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - -files = LoggerTest.java - -packages = netsvcs \ - netsvcs.Logger - -realclean: - /bin/rm -rf ${JACE_WRAPPER}/classes/tests/netsvcs/Logger - diff --git a/java/tests/netsvcs/Naming/ClientTest.java b/java/tests/netsvcs/Naming/ClientTest.java deleted file mode 100644 index c1189fecd7f..00000000000 --- a/java/tests/netsvcs/Naming/ClientTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package tests.netsvcs.Naming; - -import java.io.*; -import java.net.*; -import java.util.*; -import JACE.OS.*; -import JACE.Connection.*; -import JACE.SOCK_SAP.*; -import netsvcs.Naming.*; - -public class ClientTest -{ - void print_usage_and_die () - { - System.out.println ("Usage: ClientTest <hostname> [<port>]"); - System.exit (0); - } - - public SOCKStream init (SOCKStream socket, String hostname, int port) - { - try - { - SOCKConnector sc = new SOCKConnector(socket, hostname, port); - } - catch (UnknownHostException e) - { - ACE.ERROR (e); - System.exit(0); - } - catch (SocketException e) - { - ACE.ERROR ("Connection refused"); - System.exit(0); - } - catch (IOException e) - { - ACE.ERROR (e); - System.exit(0); - } - - return socket; - } - - public static void main (String [] args) - { - SOCKStream socket; - int port = ACE.DEFAULT_SERVER_PORT; - ClientTest clientTest = new ClientTest (); - - if (args.length == 2) - { - try - { - port = Integer.parseInt (args[1]); - } - catch (NumberFormatException e) - { - clientTest.print_usage_and_die (); - } - } - System.out.println("Trying to open port " + port + " on " + args[0]); - - socket = clientTest.init (new SOCKStream(), args[0], port); - - NameProxy proxy = new NameProxy(socket); - - System.out.println("---- Beginning tests ----"); - - try { - - System.out.println("Binding (five, six, seven): " + proxy.bind("five", "six", "seven")); - System.out.println("Binding (filth, rat, eats): " + proxy.bind("filth", "rat", "eats")); - - Vector res = proxy.resolve("five"); - - System.out.println("Resolve (five) : " + (String)res.elementAt(1) + " " - + (String)res.elementAt(2)); - - System.out.println("Binding (fish, words, him): " + proxy.bind("fish", "words", "him")); - - System.out.println("Unbind (five, six, seven): " + proxy.unbind("five")); - - res = proxy.resolve("five"); - - System.out.println("Resolve (five) : " + (String)res.elementAt(1) + " " - + (String)res.elementAt(2)); - System.out.println("Binding (fiction, us, you): " + proxy.bind("fiction", "us", "you")); - - System.out.println("\nGetting all records whose names begin with fi:\n"); - Vector res2 = proxy.listNameEntries("fi"); - - Enumeration iter = res2.elements(); - - while (iter.hasMoreElements()) { - Vector res3 = (Vector)(iter.nextElement()); - - System.out.println((String)res3.elementAt(0) + "\t" + (String)res3.elementAt(1) - + "\t" + (String)res3.elementAt(2)); - } - - } catch (IOException e) - { - ACE.ERROR("" + e); - } - finally - { - try { - socket.close(); - } catch (IOException e) { - ACE.ERROR("" + e); - } - } - - } - -}; - diff --git a/java/tests/netsvcs/Naming/Makefile b/java/tests/netsvcs/Naming/Makefile deleted file mode 100644 index be6e9c45848..00000000000 --- a/java/tests/netsvcs/Naming/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -# Makefile - -.SUFFIXES: .java .class - -JACE_WRAPPER = ../../.. -CLASSDIR = $(JACE_WRAPPER)/classes - -CLASSPATH := $(CLASSDIR):$(CLASSPATH) - -all: - javac -d ${JACE_WRAPPER}/classes $(files) -doc: - javadoc -d ${JACE_WRAPPER}/doc $(files) $(packages) - - -files = ClientTest.java - -packages = tests.netsvcs.Naming - -realclean: - find ${JACE_WRAPPER}/classes/tests/netsvcs/Naming -name '*.class' -print | xargs ${RM} |