diff --git a/README.txt b/README.txt deleted file mode 100644 index c84bde52..00000000 --- a/README.txt +++ /dev/null @@ -1,93 +0,0 @@ -This is the README file for version 1.2 of Helma Object Publisher. - -============================ -ABOUT HELMA OBJECT PUBLISHER -============================ - -Helma Object Publisher is a web application server. - -With Helma Object Publisher (sometimes simply refered to as Helma or -Hop) you can define Objects and map them to a relational database -table. These so-called HopObjects can be created, modified and deleted -using a comfortable object/container model. Hence, no manual fiddling -around with database code is necessary. - -HopObjects are extended JavaScript objects which can be scripted using -server-side JavaScript. Beyond the common JavaScript features, Helma -provides special "skin" and template functionalities which facilitate -the rendering of objects via a web interface. - -Thanks to Helma's relational database mapping technology, HopObjects -create a hierarchical structure, the Url space of a Helma site. The -parts between slashes in a Helma Url represent HopObjects (similar to -the document tree in static sites). The Helma Url space can be thought -of as an analogy to the Document Object Model (Dom) in client-side -JavaScript. - - -=================== -SYSTEM REQUIREMENTS -=================== - -Windows: 1) On Windows Helma won't run with Microsoft's version of -Java (jview). You can get a compatible Java runtime from Sun or IBM: -http://java.sun.com/j2se/1.3/jre/download-windows.html -http://www.ibm.com/java/jdk/download/ 2) In the Windows start script -I've hardcoded c:\java\lib\classes.zip in the CLASSPATH argument. Not -good. - -Macintosh: 1) If you are using the Mac version you should own a G3 CPU -and/or have MRJ 2.2 (http://www.apple.com/java) installed. Other -platforms have less frustration potential. The Mac OS version -currently is not up-to-date (version 0.1). - -Linux: The recomended virtual machine for running Helma on Linux is -Blackdown's port of JDK 1.2.2 RC4 -(http://www.blackdown.org/java-linux/mirrors.html). JDK 1.1.7v3 will -work, but much slower and show a lot of CPU activity even when the -Helma is idle. IBM's version of JDK 1.1.8 also works well, but this -JVM has some problems of its own with thread handling. - - -============================ -INSTALLING AND RUNNING HELMA -============================ - -Simply unzip the contents of the archive file into any place on your -hard disk. Start Helma by opening the file hop.bat or hop.sh, -respectively. - -If you manage to get it running you should be able to connect your -browser to http://127.0.0.1:8080/ (port 8080, that is). - -This version is set up to use its own embedded Web server and a very -basic embedded object database. For this reason it is able to run -virtually without installation on any platform with a Java 1.1 virtual -machine. - -On the other hand, the embedded Web server and object db are meant for -development work and not ready for prime time deployment. For that -you'd probably use an external relational database, the Berkeley DB -package and a full featured Web server like Apache. - - -===================================== -DOCUMENTATION AND FURTHER INFORMATION -===================================== - -Currently, a documentation-in-progress is available online only. -Please refer to http://helma.org/docs/. - -For further information http://helma.org generally is a good place. -There is also a mailing-list about Helma-related stuff available at -http://helma.org/lists/listinfo/hop. - -For questions, comments or suggestions feel free to contact -tobi@helma.at. - - - --- - -This document was last modified on Friday 22 June 2001 by -tobi@helma.at \ No newline at end of file diff --git a/apps.properties b/apps.properties deleted file mode 100644 index 27dd7cfd..00000000 --- a/apps.properties +++ /dev/null @@ -1,9 +0,0 @@ -# List of apps to start. - -base=self -manage=self - -bloggerapi -himp -lillebror -hopblog diff --git a/build/README b/build/README deleted file mode 100644 index 510af89d..00000000 --- a/build/README +++ /dev/null @@ -1,67 +0,0 @@ -This is the README file for the Helma build files as part of the Helma Object Publisher. It is included in the current distribution (version 1.2pre as of 8 November 2001) downloadable at . - -The build directory consists of the following files: - - ant.jar - build.bat - build.sh - build.xml - crimson.jar - jaxp.jar - README - - -PREREQUISITES -============= - -The Helma build script is using a software called Ant. Ant is a build system that was developed for the Jakarta Tomcat project. For more information about Ant, see . - -To run Ant, you also need JDK 1.3 or higher . - -For checking out the source files from Helma's CVS you also need a local installation of a CVS command-line client. More information about CVS at . - - -STARTING BUILD -============== - -The build system is started by invoking the shell script appropriate to your platform, ie. build.sh for *nix (Linux, NetBSD etc.) and build.bat for Windows systems. - -The generic syntax is - - ./build target - -The parameter "target" specifies one of the following build targets. - - -BUILD TARGETS -============= - -checkout - Fetches (or updates, resp.) the Helma source files from the CVS and copies them into the src/ directory (which will be created if necessary). - -compile - Compiles the source files contained in the src/ directory into the class/ directory (which will be created if necessary). - -jar - Stuffs the files in class/ together and saves them as .jar archive in the build directory. The file is named helma-yyyymmdd.jar. - -javadoc - Creates the Java API documentation for the Helma classes. The resulting files are saved into the docs/apidocs/ directory (which will be created if necessary). - -package - Builds all previous targets (checkout, compile, jar, javadoc) and saves the created files in the directory helma-1.x/ (with 1.x being the version number). All directories will be created if necessary. - -package-zip - Same as "package". Additionally, the files in the output directory will be compressed as .zip file. - -package-tgz - Same as "package". Additionall, the file in the output directory will be compressed as .tar.gz file. - -package-all - Builds all previous targets. The result is a complete and up-to-date (as in the CVS) installation of Helma, the API documentation, source and build files as well as compressed packages for *nix and Windows systems including all the files. - - --- - -This README was last updated on 8 November 2001 by tobi@helma.org. - diff --git a/build/ant.jar b/build/ant.jar deleted file mode 100644 index 8ad84e34..00000000 Binary files a/build/ant.jar and /dev/null differ diff --git a/build/antclick/README.txt b/build/antclick/README.txt deleted file mode 100644 index c84bde52..00000000 --- a/build/antclick/README.txt +++ /dev/null @@ -1,93 +0,0 @@ -This is the README file for version 1.2 of Helma Object Publisher. - -============================ -ABOUT HELMA OBJECT PUBLISHER -============================ - -Helma Object Publisher is a web application server. - -With Helma Object Publisher (sometimes simply refered to as Helma or -Hop) you can define Objects and map them to a relational database -table. These so-called HopObjects can be created, modified and deleted -using a comfortable object/container model. Hence, no manual fiddling -around with database code is necessary. - -HopObjects are extended JavaScript objects which can be scripted using -server-side JavaScript. Beyond the common JavaScript features, Helma -provides special "skin" and template functionalities which facilitate -the rendering of objects via a web interface. - -Thanks to Helma's relational database mapping technology, HopObjects -create a hierarchical structure, the Url space of a Helma site. The -parts between slashes in a Helma Url represent HopObjects (similar to -the document tree in static sites). The Helma Url space can be thought -of as an analogy to the Document Object Model (Dom) in client-side -JavaScript. - - -=================== -SYSTEM REQUIREMENTS -=================== - -Windows: 1) On Windows Helma won't run with Microsoft's version of -Java (jview). You can get a compatible Java runtime from Sun or IBM: -http://java.sun.com/j2se/1.3/jre/download-windows.html -http://www.ibm.com/java/jdk/download/ 2) In the Windows start script -I've hardcoded c:\java\lib\classes.zip in the CLASSPATH argument. Not -good. - -Macintosh: 1) If you are using the Mac version you should own a G3 CPU -and/or have MRJ 2.2 (http://www.apple.com/java) installed. Other -platforms have less frustration potential. The Mac OS version -currently is not up-to-date (version 0.1). - -Linux: The recomended virtual machine for running Helma on Linux is -Blackdown's port of JDK 1.2.2 RC4 -(http://www.blackdown.org/java-linux/mirrors.html). JDK 1.1.7v3 will -work, but much slower and show a lot of CPU activity even when the -Helma is idle. IBM's version of JDK 1.1.8 also works well, but this -JVM has some problems of its own with thread handling. - - -============================ -INSTALLING AND RUNNING HELMA -============================ - -Simply unzip the contents of the archive file into any place on your -hard disk. Start Helma by opening the file hop.bat or hop.sh, -respectively. - -If you manage to get it running you should be able to connect your -browser to http://127.0.0.1:8080/ (port 8080, that is). - -This version is set up to use its own embedded Web server and a very -basic embedded object database. For this reason it is able to run -virtually without installation on any platform with a Java 1.1 virtual -machine. - -On the other hand, the embedded Web server and object db are meant for -development work and not ready for prime time deployment. For that -you'd probably use an external relational database, the Berkeley DB -package and a full featured Web server like Apache. - - -===================================== -DOCUMENTATION AND FURTHER INFORMATION -===================================== - -Currently, a documentation-in-progress is available online only. -Please refer to http://helma.org/docs/. - -For further information http://helma.org generally is a good place. -There is also a mailing-list about Helma-related stuff available at -http://helma.org/lists/listinfo/hop. - -For questions, comments or suggestions feel free to contact -tobi@helma.at. - - - --- - -This document was last modified on Friday 22 June 2001 by -tobi@helma.at \ No newline at end of file diff --git a/build/antclick/db.properties b/build/antclick/db.properties deleted file mode 100644 index 9dc57b94..00000000 --- a/build/antclick/db.properties +++ /dev/null @@ -1,16 +0,0 @@ -# This is where you specify relational data sources to -# map Helma types to relational databases. -# -# If you want to define a data source just for one -# application, simply copy the db.properties file to -# the application directory. -# -# The actual mapping of types is done in the -# type.properties file in the prototype directories. -# - -# Properties of JDBC data sources -myDataSource.url = jdbc:mysql://db.domain.com/space -myDataSource.driver = org.gjt.mm.mysql.Driver -myDataSource.user = username -myDataSource.password = xyz diff --git a/build/antclick/license.txt b/build/antclick/license.txt deleted file mode 100644 index 70584794..00000000 --- a/build/antclick/license.txt +++ /dev/null @@ -1,50 +0,0 @@ - Copyright (c) 1999-2001 Helma Project. 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. - - 3. The end-user documentation included with the redistribution, - if any, must include the following acknowledgment: - "This product includes software developed by the Helma Project - for use in the Helma Object Publisher (http://www.helma.org/)." - Alternately, this acknowledgment may appear in the software itself, - if and wherever such third-party acknowledgments normally appear. - - 4. The names "Helma" and "Hop" must not be used to endorse or - promote products derived from this software without prior written - permission. For written permission, please contact - helma@helma.org. - - 5. Products derived from this software may not be called "Helma" - or "Hop", nor may "Helma" or "Hop" appear in their name, without - prior written permission of the Helma Project Group. - - 6. We ask you to give credit to the Helma Project for sites which build - upon Helma. This would normally consist of a text or graphic link - to http://helma.org/ with the line "Powered by Helma" somewhere on the - site. While it is not a breach of this license to omit this, it's a - great way for you to make help the Helma Project to continue - to flourish and grow. - - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 HELMA PROJECT OR ITS - 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. diff --git a/build/antclick/server.properties b/build/antclick/server.properties deleted file mode 100644 index 203e09ef..00000000 --- a/build/antclick/server.properties +++ /dev/null @@ -1,33 +0,0 @@ -# The SMTP server to use for sending mails. Set and -# uncomment this line before trying to send mails from -# Helma applications. -# -# smtp=mail.yourdomain.com - - -# Some examples for server-wide locale settings -# (please refer to http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html -# for country codes, resp. http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt -# for language codes). -# -# country = AT -# language = de -# -# country = UK -# language = en -# -# country = FR -# language = fr -# -# country = CZ -# language = cs - -# list ip addresses for admin-application here: -allowAdmin=127.0.0.1, 192.168.0.1 - -# md5-encrypted username and password for admin-app -# the default is test/test -adminUsername=098f6bcd4621d373cade4e832627b4f6 -adminPassword=098f6bcd4621d373cade4e832627b4f6 - - diff --git a/build/build.bat b/build/build.bat deleted file mode 100644 index 1987d986..00000000 --- a/build/build.bat +++ /dev/null @@ -1,47 +0,0 @@ -@echo off - - -REM -------------------------------------------- -REM Defualt == jar -REM "checkout" target gets sources from helma.org -REM "compile" target compiles java sources -REM "jar" target compiles and builds jar -REM "javadoc" target builds the javadoc -REM "package" target builds core + jar + javadoc + distribution -REM -------------------------------------------- -set TARGET=%1% - - -REM -------------------------------------------- -REM No need to edit anything past here -REM -------------------------------------------- -set BUILDFILE=build.xml -if "%TARGET%" == "" goto setdist -goto final - -:setdist -set TARGET=jar -goto final - -:final - -if "%JAVA_HOME%" == "" goto javahomeerror - -set CP=%CLASSPATH%;ant.jar;jaxp.jar;crimson.jar -if exist %JAVA_HOME%\lib\tools.jar set CP=%CP%;%JAVA_HOME%\lib\tools.jar - -echo Classpath: %CP% -echo JAVA_HOME: %JAVA_HOME% - -%JAVA_HOME%\bin\java.exe -classpath "%CP%" org.apache.tools.ant.Main -buildfile %BUILDFILE% %TARGET% - -goto end - - -REM -----------ERROR------------- -:javahomeerror -echo "ERROR: JAVA_HOME not found in your environment." -echo "Please, set the JAVA_HOME variable in your environment to match the" -echo "location of the Java Virtual Machine you want to use." - -:end diff --git a/build/build.sh b/build/build.sh deleted file mode 100755 index 4891d8f6..00000000 --- a/build/build.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/sh - -# -------------------------------------------- -# Default == jar -# "checkout" target gets sources from helma.org -# "compile" target compiles java sources -# "jar" target compiles and builds jar -# "javadoc" target builds the javadoc -# "package" target builds core + jar + javadoc + distribution -# -------------------------------------------- -TARGET=${1} - -# export JAVA_HOME=/usr/lib/java - -export CVSHOME=:pserver:anonymous@coletta.helma.at:/opt/cvs - -# comment this out to log in to CVS server -# cvs -d :pserver:anonymous@coletta.helma.at:/opt/cvs login - -#-------------------------------------------- -# No need to edit anything past here -#-------------------------------------------- -if test -z "${JAVA_HOME}" ; then - echo "ERROR: JAVA_HOME not found in your environment." - echo "Please, set the JAVA_HOME variable in your environment to match the" - echo "location of the Java Virtual Machine you want to use." - exit -fi - -if test -z "${TARGET}" ; then -TARGET=jar -fi - -if test -f ${JAVA_HOME}/lib/tools.jar ; then - CLASSPATH=${CLASSPATH}:${JAVA_HOME}/lib/tools.jar -fi - -echo "Now building ${TARGET}..." - -CP=${CLASSPATH}:ant.jar:jaxp.jar:crimson.jar:../lib/netcomponents.jar - -echo "Classpath: ${CP}" -echo "JAVA_HOME: ${JAVA_HOME}" - -BUILDFILE=build.xml - -${JAVA_HOME}/bin/java -classpath ${CP} org.apache.tools.ant.Main -buildfile ${BUILDFILE} ${TARGET} - - diff --git a/build/build.xml b/build/build.xml deleted file mode 100644 index 36a1b397..00000000 --- a/build/build.xml +++ /dev/null @@ -1,264 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/build/crimson.jar b/build/crimson.jar deleted file mode 100644 index 2ad58524..00000000 Binary files a/build/crimson.jar and /dev/null differ diff --git a/build/jaxp.jar b/build/jaxp.jar deleted file mode 100644 index b881783e..00000000 Binary files a/build/jaxp.jar and /dev/null differ diff --git a/build/main/apps.properties b/build/main/apps.properties deleted file mode 100644 index 27dd7cfd..00000000 --- a/build/main/apps.properties +++ /dev/null @@ -1,9 +0,0 @@ -# List of apps to start. - -base=self -manage=self - -bloggerapi -himp -lillebror -hopblog diff --git a/build/main/db.properties b/build/main/db.properties deleted file mode 100644 index 9dc57b94..00000000 --- a/build/main/db.properties +++ /dev/null @@ -1,16 +0,0 @@ -# This is where you specify relational data sources to -# map Helma types to relational databases. -# -# If you want to define a data source just for one -# application, simply copy the db.properties file to -# the application directory. -# -# The actual mapping of types is done in the -# type.properties file in the prototype directories. -# - -# Properties of JDBC data sources -myDataSource.url = jdbc:mysql://db.domain.com/space -myDataSource.driver = org.gjt.mm.mysql.Driver -myDataSource.user = username -myDataSource.password = xyz diff --git a/build/main/db/hopblog/0 b/build/main/db/hopblog/0 deleted file mode 100644 index 39e7347a..00000000 Binary files a/build/main/db/hopblog/0 and /dev/null differ diff --git a/build/main/db/hopblog/1 b/build/main/db/hopblog/1 deleted file mode 100644 index 7c75ade1..00000000 Binary files a/build/main/db/hopblog/1 and /dev/null differ diff --git a/build/main/db/hopblog/2 b/build/main/db/hopblog/2 deleted file mode 100644 index d019446a..00000000 Binary files a/build/main/db/hopblog/2 and /dev/null differ diff --git a/build/main/db/hopblog/3 b/build/main/db/hopblog/3 deleted file mode 100644 index f42ddfda..00000000 Binary files a/build/main/db/hopblog/3 and /dev/null differ diff --git a/build/main/db/hopblog/4 b/build/main/db/hopblog/4 deleted file mode 100644 index 8f8c8b25..00000000 Binary files a/build/main/db/hopblog/4 and /dev/null differ diff --git a/build/main/db/hopblog/idgen b/build/main/db/hopblog/idgen deleted file mode 100644 index cde493d2..00000000 Binary files a/build/main/db/hopblog/idgen and /dev/null differ diff --git a/build/main/hop.bat b/build/main/hop.bat deleted file mode 100755 index d10bb016..00000000 --- a/build/main/hop.bat +++ /dev/null @@ -1,13 +0,0 @@ -@echo off - -rem Batch file for starting Hop with a JDK-like virtual machine. - -set JARS=lib\helma.jar;lib\berkeley.jar;lib\village.jar;lib\jsdk.jar;lib\openxml.jar -set JARS=%JARS%;lib\sax.jar;lib\regexp.jar;lib\netcomponents.jar;lib\jimi.jar -set JARS=%JARS%;lib\mail.jar;lib\activation.jar;lib\mysql.jar;lib\jdom.jar;lib\minml.jar - -set HOP_PORT=8080 - -echo Starting Web server on port %HOP_PORT% - -java -classpath c:\winnt\java\packages\rmi.zip;%JARS% helma.main.Server -w %HOP_PORT% diff --git a/build/main/hop.sh b/build/main/hop.sh deleted file mode 100644 index 451ca1eb..00000000 --- a/build/main/hop.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/sh -# Stupid shell script for starting Hop with a JDK-like virtual machine. -# Presumes that you have your classpath set. - -export HOP_PORT=8080 - -export JARS=lib/helma.jar:lib/berkeley.jar:lib/village.jar:lib/jsdk.jar:lib/openxml.jar -export JARS=$JARS:lib/sax.jar:lib/regexp.jar:lib/netcomponents.jar:lib/jimi.jar -export JARS=$JARS:lib/mail.jar:lib/activation.jar:lib/mysql.jar:lib/jdom.jar:lib/minml.jar - -java -classpath $CLASSPATH:$JARS helma.main.Server -w $HOP_PORT diff --git a/build/main/license.txt b/build/main/license.txt deleted file mode 100644 index 70584794..00000000 --- a/build/main/license.txt +++ /dev/null @@ -1,50 +0,0 @@ - Copyright (c) 1999-2001 Helma Project. 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. - - 3. The end-user documentation included with the redistribution, - if any, must include the following acknowledgment: - "This product includes software developed by the Helma Project - for use in the Helma Object Publisher (http://www.helma.org/)." - Alternately, this acknowledgment may appear in the software itself, - if and wherever such third-party acknowledgments normally appear. - - 4. The names "Helma" and "Hop" must not be used to endorse or - promote products derived from this software without prior written - permission. For written permission, please contact - helma@helma.org. - - 5. Products derived from this software may not be called "Helma" - or "Hop", nor may "Helma" or "Hop" appear in their name, without - prior written permission of the Helma Project Group. - - 6. We ask you to give credit to the Helma Project for sites which build - upon Helma. This would normally consist of a text or graphic link - to http://helma.org/ with the line "Powered by Helma" somewhere on the - site. While it is not a breach of this license to omit this, it's a - great way for you to make help the Helma Project to continue - to flourish and grow. - - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 HELMA PROJECT OR ITS - 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. diff --git a/build/main/server.properties b/build/main/server.properties deleted file mode 100644 index 203e09ef..00000000 --- a/build/main/server.properties +++ /dev/null @@ -1,33 +0,0 @@ -# The SMTP server to use for sending mails. Set and -# uncomment this line before trying to send mails from -# Helma applications. -# -# smtp=mail.yourdomain.com - - -# Some examples for server-wide locale settings -# (please refer to http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html -# for country codes, resp. http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt -# for language codes). -# -# country = AT -# language = de -# -# country = UK -# language = en -# -# country = FR -# language = fr -# -# country = CZ -# language = cs - -# list ip addresses for admin-application here: -allowAdmin=127.0.0.1, 192.168.0.1 - -# md5-encrypted username and password for admin-app -# the default is test/test -adminUsername=098f6bcd4621d373cade4e832627b4f6 -adminPassword=098f6bcd4621d373cade4e832627b4f6 - - diff --git a/build/main/static/himp/original.jpg b/build/main/static/himp/original.jpg deleted file mode 100644 index d8e24618..00000000 Binary files a/build/main/static/himp/original.jpg and /dev/null differ diff --git a/db.properties b/db.properties deleted file mode 100644 index 9dc57b94..00000000 --- a/db.properties +++ /dev/null @@ -1,16 +0,0 @@ -# This is where you specify relational data sources to -# map Helma types to relational databases. -# -# If you want to define a data source just for one -# application, simply copy the db.properties file to -# the application directory. -# -# The actual mapping of types is done in the -# type.properties file in the prototype directories. -# - -# Properties of JDBC data sources -myDataSource.url = jdbc:mysql://db.domain.com/space -myDataSource.driver = org.gjt.mm.mysql.Driver -myDataSource.user = username -myDataSource.password = xyz diff --git a/hop.bat b/hop.bat deleted file mode 100755 index d10bb016..00000000 --- a/hop.bat +++ /dev/null @@ -1,13 +0,0 @@ -@echo off - -rem Batch file for starting Hop with a JDK-like virtual machine. - -set JARS=lib\helma.jar;lib\berkeley.jar;lib\village.jar;lib\jsdk.jar;lib\openxml.jar -set JARS=%JARS%;lib\sax.jar;lib\regexp.jar;lib\netcomponents.jar;lib\jimi.jar -set JARS=%JARS%;lib\mail.jar;lib\activation.jar;lib\mysql.jar;lib\jdom.jar;lib\minml.jar - -set HOP_PORT=8080 - -echo Starting Web server on port %HOP_PORT% - -java -classpath c:\winnt\java\packages\rmi.zip;%JARS% helma.main.Server -w %HOP_PORT% diff --git a/hop.sh b/hop.sh deleted file mode 100755 index 451ca1eb..00000000 --- a/hop.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/sh -# Stupid shell script for starting Hop with a JDK-like virtual machine. -# Presumes that you have your classpath set. - -export HOP_PORT=8080 - -export JARS=lib/helma.jar:lib/berkeley.jar:lib/village.jar:lib/jsdk.jar:lib/openxml.jar -export JARS=$JARS:lib/sax.jar:lib/regexp.jar:lib/netcomponents.jar:lib/jimi.jar -export JARS=$JARS:lib/mail.jar:lib/activation.jar:lib/mysql.jar:lib/jdom.jar:lib/minml.jar - -java -classpath $CLASSPATH:$JARS helma.main.Server -w $HOP_PORT diff --git a/lib/activation.jar b/lib/activation.jar deleted file mode 100644 index db4b1fb5..00000000 Binary files a/lib/activation.jar and /dev/null differ diff --git a/lib/berkeley.jar b/lib/berkeley.jar deleted file mode 100644 index 54aa6774..00000000 Binary files a/lib/berkeley.jar and /dev/null differ diff --git a/lib/gnu-regexp.jar b/lib/gnu-regexp.jar deleted file mode 100644 index 09ed033a..00000000 Binary files a/lib/gnu-regexp.jar and /dev/null differ diff --git a/lib/jdom.jar b/lib/jdom.jar deleted file mode 100644 index 93e77a4a..00000000 Binary files a/lib/jdom.jar and /dev/null differ diff --git a/lib/jimi.jar b/lib/jimi.jar deleted file mode 100644 index 8bed0837..00000000 Binary files a/lib/jimi.jar and /dev/null differ diff --git a/lib/jsdk.jar b/lib/jsdk.jar deleted file mode 100644 index c26210c1..00000000 Binary files a/lib/jsdk.jar and /dev/null differ diff --git a/lib/mail.jar b/lib/mail.jar deleted file mode 100644 index d87d02a8..00000000 Binary files a/lib/mail.jar and /dev/null differ diff --git a/lib/minml.jar b/lib/minml.jar deleted file mode 100644 index 046f6e93..00000000 Binary files a/lib/minml.jar and /dev/null differ diff --git a/lib/mysql.jar b/lib/mysql.jar deleted file mode 100644 index 8354fc21..00000000 Binary files a/lib/mysql.jar and /dev/null differ diff --git a/lib/netcomponents.jar b/lib/netcomponents.jar deleted file mode 100644 index 21ce702d..00000000 Binary files a/lib/netcomponents.jar and /dev/null differ diff --git a/lib/openxml.jar b/lib/openxml.jar deleted file mode 100644 index 22b385b7..00000000 Binary files a/lib/openxml.jar and /dev/null differ diff --git a/lib/regexp.jar b/lib/regexp.jar deleted file mode 100644 index 3c21d4ed..00000000 Binary files a/lib/regexp.jar and /dev/null differ diff --git a/lib/sax.jar b/lib/sax.jar deleted file mode 100644 index f52382bf..00000000 Binary files a/lib/sax.jar and /dev/null differ diff --git a/lib/village.jar b/lib/village.jar deleted file mode 100644 index 74545253..00000000 Binary files a/lib/village.jar and /dev/null differ diff --git a/license.txt b/license.txt deleted file mode 100644 index 70584794..00000000 --- a/license.txt +++ /dev/null @@ -1,50 +0,0 @@ - Copyright (c) 1999-2001 Helma Project. 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. - - 3. The end-user documentation included with the redistribution, - if any, must include the following acknowledgment: - "This product includes software developed by the Helma Project - for use in the Helma Object Publisher (http://www.helma.org/)." - Alternately, this acknowledgment may appear in the software itself, - if and wherever such third-party acknowledgments normally appear. - - 4. The names "Helma" and "Hop" must not be used to endorse or - promote products derived from this software without prior written - permission. For written permission, please contact - helma@helma.org. - - 5. Products derived from this software may not be called "Helma" - or "Hop", nor may "Helma" or "Hop" appear in their name, without - prior written permission of the Helma Project Group. - - 6. We ask you to give credit to the Helma Project for sites which build - upon Helma. This would normally consist of a text or graphic link - to http://helma.org/ with the line "Powered by Helma" somewhere on the - site. While it is not a breach of this license to omit this, it's a - great way for you to make help the Helma Project to continue - to flourish and grow. - - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 HELMA PROJECT OR ITS - 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. diff --git a/server.properties b/server.properties deleted file mode 100644 index 203e09ef..00000000 --- a/server.properties +++ /dev/null @@ -1,33 +0,0 @@ -# The SMTP server to use for sending mails. Set and -# uncomment this line before trying to send mails from -# Helma applications. -# -# smtp=mail.yourdomain.com - - -# Some examples for server-wide locale settings -# (please refer to http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html -# for country codes, resp. http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt -# for language codes). -# -# country = AT -# language = de -# -# country = UK -# language = en -# -# country = FR -# language = fr -# -# country = CZ -# language = cs - -# list ip addresses for admin-application here: -allowAdmin=127.0.0.1, 192.168.0.1 - -# md5-encrypted username and password for admin-app -# the default is test/test -adminUsername=098f6bcd4621d373cade4e832627b4f6 -adminPassword=098f6bcd4621d373cade4e832627b4f6 - - diff --git a/src/Acme/Fmt.java b/src/Acme/Fmt.java deleted file mode 100644 index cba4bf2e..00000000 --- a/src/Acme/Fmt.java +++ /dev/null @@ -1,613 +0,0 @@ -// Fmt - some simple single-arg sprintf-like routines -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme; - -/// Some simple single-arg sprintf-like routines. -//

-// It is apparently impossible to declare a Java method that accepts -// variable numbers of any type of argument. You can declare it to take -// Objects, but numeric variables and constants are not in fact Objects. -//

-// However, using the built-in string concatenation, it's almost as -// convenient to make a series of single-argument formatting routines. -//

-// Fmt can format the following types: -//

-// byte short int long float double char String Object -//
-// For each type there is a set of overloaded methods, each returning -// a formatted String. There's the plain formatting version: -//
-// Fmt.fmt( x )
-// 
-// There's a version specifying a minimum field width: -//
-// Fmt.fmt( x, minWidth )
-// 
-// And there's a version that takes flags: -//
-// Fmt.fmt( x, minWidth, flags )
-// 
-// Currently available flags are: -//
-// Fmt.ZF - zero-fill
-// Fmt.LJ - left justify
-// Fmt.HX - hexadecimal
-// Fmt.OC - octal
-// 
-// The HX and OC flags imply unsigned output. -//

-// For doubles and floats, there's a significant-figures parameter before -// the flags: -//

-// Fmt.fmt( d )
-// Fmt.fmt( d, minWidth )
-// Fmt.fmt( d, minWidth, sigFigs )
-// Fmt.fmt( d, minWidth, sigFigs, flags )
-// 
-//

-// Fetch the software.
-// Fetch the entire Acme package. -//


-// Similar classes: -//
    -//
  • Andrew Scherpbier's FormatString -// Tries to allow variable numbers of arguments by -// supplying overloaded routines with different combinations of parameters, -// but doesn't actually supply that many. The floating point conversion -// is described as "very incomplete". -//
  • Core Java's Format. -// The design seems a little weird. They want you to create an instance, -// passing the format string to the constructor, and then call an instance -// method with your data to do the actual formatting. The extra steps are -// pointless; better to just use static methods. -//
- -public class Fmt - { - - // Flags. - /// Zero-fill. - public static final int ZF = 1; - /// Left justify. - public static final int LJ = 2; - /// Hexadecimal. - public static final int HX = 4; - /// Octal. - public static final int OC = 8; - // Was a number - internal use. - private static final int WN = 16; - - // byte - public static String fmt( byte b ) - { - return fmt( b, 0, 0 ); - } - public static String fmt( byte b, int minWidth ) - { - return fmt( b, minWidth, 0 ); - } - public static String fmt( byte b, int minWidth, int flags ) - { - boolean hexadecimal = ( ( flags & HX ) != 0 ); - boolean octal = ( ( flags & OC ) != 0 ); - if ( hexadecimal ) - return fmt( Integer.toString( b & 0xff, 16 ), minWidth, flags|WN ); - else if ( octal ) - return fmt( Integer.toString( b & 0xff, 8 ), minWidth, flags|WN ); - else - return fmt( Integer.toString( b & 0xff ), minWidth, flags|WN ); - } - - // short - public static String fmt( short s ) - { - return fmt( s, 0, 0 ); - } - public static String fmt( short s, int minWidth ) - { - return fmt( s, minWidth, 0 ); - } - public static String fmt( short s, int minWidth, int flags ) - { - boolean hexadecimal = ( ( flags & HX ) != 0 ); - boolean octal = ( ( flags & OC ) != 0 ); - if ( hexadecimal ) - return fmt( - Integer.toString( s & 0xffff, 16 ), minWidth, flags|WN ); - else if ( octal ) - return fmt( - Integer.toString( s & 0xffff, 8 ), minWidth, flags|WN ); - else - return fmt( Integer.toString( s ), minWidth, flags|WN ); - } - - // int - public static String fmt( int i ) - { - return fmt( i, 0, 0 ); - } - public static String fmt( int i, int minWidth ) - { - return fmt( i, minWidth, 0 ); - } - public static String fmt( int i, int minWidth, int flags ) - { - boolean hexadecimal = ( ( flags & HX ) != 0 ); - boolean octal = ( ( flags & OC ) != 0 ); - if ( hexadecimal ) - return fmt( - Long.toString( i & 0xffffffffL, 16 ), minWidth, flags|WN ); - else if ( octal ) - return fmt( - Long.toString( i & 0xffffffffL, 8 ), minWidth, flags|WN ); - else - return fmt( Integer.toString( i ), minWidth, flags|WN ); - } - - // long - public static String fmt( long l ) - { - return fmt( l, 0, 0 ); - } - public static String fmt( long l, int minWidth ) - { - return fmt( l, minWidth, 0 ); - } - public static String fmt( long l, int minWidth, int flags ) - { - boolean hexadecimal = ( ( flags & HX ) != 0 ); - boolean octal = ( ( flags & OC ) != 0 ); - if ( hexadecimal ) - { - if ( ( l & 0xf000000000000000L ) != 0 ) - return fmt( - Long.toString( l >>> 60, 16 ) + - fmt( l & 0x0fffffffffffffffL, 15, HX|ZF ), - minWidth, flags|WN ); - else - return fmt( Long.toString( l, 16 ), minWidth, flags|WN ); - } - else if ( octal ) - { - if ( ( l & 0x8000000000000000L ) != 0 ) - return fmt( - Long.toString( l >>> 63, 8 ) + - fmt( l & 0x7fffffffffffffffL, 21, OC|ZF ), - minWidth, flags|WN ); - else - return fmt( Long.toString( l, 8 ), minWidth, flags|WN ); - } - else - return fmt( Long.toString( l ), minWidth, flags|WN ); - } - - // float - public static String fmt( float f ) - { - return fmt( f, 0, 0, 0 ); - } - public static String fmt( float f, int minWidth ) - { - return fmt( f, minWidth, 0, 0 ); - } - public static String fmt( float f, int minWidth, int sigFigs ) - { - return fmt( f, minWidth, sigFigs, 0 ); - } - public static String fmt( float f, int minWidth, int sigFigs, int flags ) - { - if ( sigFigs != 0 ) - return fmt( - sigFigFix( Float.toString( f ), sigFigs ), minWidth, - flags|WN ); - else - return fmt( Float.toString( f ), minWidth, flags|WN ); - } - - // double - public static String fmt( double d ) - { - return fmt( d, 0, 0, 0 ); - } - public static String fmt( double d, int minWidth ) - { - return fmt( d, minWidth, 0, 0 ); - } - public static String fmt( double d, int minWidth, int sigFigs ) - { - return fmt( d, minWidth, sigFigs, 0 ); - } - public static String fmt( double d, int minWidth, int sigFigs, int flags ) - { - if ( sigFigs != 0 ) - return fmt( - sigFigFix( doubleToString( d ), sigFigs ), minWidth, - flags|WN ); - else - return fmt( doubleToString( d ), minWidth, flags|WN ); - } - - // char - public static String fmt( char c ) - { - return fmt( c, 0, 0 ); - } - public static String fmt( char c, int minWidth ) - { - return fmt( c, minWidth, 0 ); - } - public static String fmt( char c, int minWidth, int flags ) - { - // return fmt( Character.toString( c ), minWidth, flags ); - // Character currently lacks a static toString method. Workaround - // is to make a temporary instance and use the instance toString. - return fmt( new Character( c ).toString(), minWidth, flags ); - } - - // Object - public static String fmt( Object o ) - { - return fmt( o, 0, 0 ); - } - public static String fmt( Object o, int minWidth ) - { - return fmt( o, minWidth, 0 ); - } - public static String fmt( Object o, int minWidth, int flags ) - { - return fmt( o.toString(), minWidth, flags ); - } - - // String - public static String fmt( String s ) - { - return fmt( s, 0, 0 ); - } - public static String fmt( String s, int minWidth ) - { - return fmt( s, minWidth, 0 ); - } - public static String fmt( String s, int minWidth, int flags ) - { - int len = s.length(); - boolean zeroFill = ( ( flags & ZF ) != 0 ); - boolean leftJustify = ( ( flags & LJ ) != 0 ); - boolean hexadecimal = ( ( flags & HX ) != 0 ); - boolean octal = ( ( flags & OC ) != 0 ); - boolean wasNumber = ( ( flags & WN ) != 0 ); - if ( ( hexadecimal || octal || zeroFill ) && ! wasNumber ) - throw new InternalError( "Acme.Fmt: number flag on a non-number" ); - if ( zeroFill && leftJustify ) - throw new InternalError( "Acme.Fmt: zero-fill left-justify is silly" ); - if ( hexadecimal && octal ) - throw new InternalError( "Acme.Fmt: can't do both hex and octal" ); - if ( len >= minWidth ) - return s; - int fillWidth = minWidth - len; - StringBuffer fill = new StringBuffer( fillWidth ); - for ( int i = 0; i < fillWidth; ++i ) - if ( zeroFill ) - fill.append( '0' ); - else - fill.append( ' ' ); - if ( leftJustify ) - return s + fill; - else if ( zeroFill && s.startsWith( "-" ) ) - return "-" + fill + s.substring( 1 ); - else - return fill + s; - } - - - // Internal routines. - - private static String sigFigFix( String s, int sigFigs ) - { - // First dissect the floating-point number string into sign, - // integer part, fraction part, and exponent. - String sign; - String unsigned; - if ( s.startsWith( "-" ) || s.startsWith( "+" ) ) - { - sign = s.substring( 0, 1 ); - unsigned = s.substring( 1 ); - } - else - { - sign = ""; - unsigned = s; - } - String mantissa; - String exponent; - int eInd = unsigned.indexOf( 'e' ); - if ( eInd == -1 ) // it may be 'e' or 'E' - eInd = unsigned.indexOf( 'E' ); - if ( eInd == -1 ) - { - mantissa = unsigned; - exponent = ""; - } - else - { - mantissa = unsigned.substring( 0, eInd ); - exponent = unsigned.substring( eInd ); - } - StringBuffer number, fraction; - int dotInd = mantissa.indexOf( '.' ); - if ( dotInd == -1 ) - { - number = new StringBuffer( mantissa ); - fraction = new StringBuffer( "" ); - } - else - { - number = new StringBuffer( mantissa.substring( 0, dotInd ) ); - fraction = new StringBuffer( mantissa.substring( dotInd + 1 ) ); - } - - int numFigs = number.length(); - int fracFigs = fraction.length(); - if ( ( numFigs == 0 || number.equals( "0" ) ) && fracFigs > 0 ) - { - // Don't count leading zeros in the fraction. - numFigs = 0; - for ( int i = 0; i < fraction.length(); ++i ) - { - if ( fraction.charAt( i ) != '0' ) - break; - --fracFigs; - } - } - int mantFigs = numFigs + fracFigs; - if ( sigFigs > mantFigs ) - { - // We want more figures; just append zeros to the fraction. - for ( int i = mantFigs; i < sigFigs; ++i ) - fraction.append( '0' ); - } - else if ( sigFigs < mantFigs && sigFigs >= numFigs ) - { - // Want fewer figures in the fraction; chop. - fraction.setLength( - fraction.length() - ( fracFigs - ( sigFigs - numFigs ) ) ); - // Round? - } - else if ( sigFigs < numFigs ) - { - // Want fewer figures in the number; turn them to zeros. - fraction.setLength( 0 ); // should already be zero, but make sure - for ( int i = sigFigs; i < numFigs; ++i ) - number.setCharAt( i, '0' ); - // Round? - } - // Else sigFigs == mantFigs, which is fine. - - if ( fraction.length() == 0 ) - return sign + number + exponent; - else - return sign + number + "." + fraction + exponent; - } - - - /// Improved version of Double.toString(), returns more decimal places. - //

- // The JDK 1.0.2 version of Double.toString() returns only six decimal - // places on some systems. In JDK 1.1 full precision is returned on - // all platforms. - // @deprecated - // @see java.lang.Double#toString - public static String doubleToString( double d ) - { - // Handle special numbers first, to avoid complications. - if ( Double.isNaN( d ) ) - return "NaN"; - if ( d == Double.NEGATIVE_INFINITY ) - return "-Inf"; - if ( d == Double.POSITIVE_INFINITY ) - return "Inf"; - - // Grab the sign, and then make the number positive for simplicity. - boolean negative = false; - if ( d < 0.0D ) - { - negative = true; - d = -d; - } - - // Get the native version of the unsigned value, as a template. - String unsStr = Double.toString( d ); - - // Dissect out the exponent. - String mantStr, expStr; - int exp; - int eInd = unsStr.indexOf( 'e' ); - if ( eInd == -1 ) // it may be 'e' or 'E' - eInd = unsStr.indexOf( 'E' ); - if ( eInd == -1 ) - { - mantStr = unsStr; - expStr = ""; - exp = 0; - } - else - { - mantStr = unsStr.substring( 0, eInd ); - expStr = unsStr.substring( eInd + 1 ); - if ( expStr.startsWith( "+" ) ) - exp = Integer.parseInt( expStr.substring( 1 ) ); - else - exp = Integer.parseInt( expStr ); - } - - // Dissect out the number part. - String numStr; - int dotInd = mantStr.indexOf( '.' ); - if ( dotInd == -1 ) - numStr = mantStr; - else - numStr = mantStr.substring( 0, dotInd ); - long num; - if ( numStr.length() == 0 ) - num = 0; - else - num = Integer.parseInt( numStr ); - - // Build the new mantissa. - StringBuffer newMantBuf = new StringBuffer( numStr + "." ); - double p = Math.pow( 10, exp ); - double frac = d - num * p; - String digits = "0123456789"; - int nDigits = 16 - numStr.length(); // about 16 digits in a double - for ( int i = 0; i < nDigits; ++i ) - { - p /= 10.0D; - int dig = (int) ( frac / p ); - if ( dig < 0 ) dig = 0; - if ( dig > 9 ) dig = 9; - newMantBuf.append( digits.charAt( dig ) ); - frac -= dig * p; - } - - if ( (int) ( frac / p + 0.5D ) == 1 ) - { - // Round up. - boolean roundMore = true; - for ( int i = newMantBuf.length() - 1; i >= 0; --i ) - { - int dig = digits.indexOf( newMantBuf.charAt( i ) ); - if ( dig == -1 ) - continue; - ++dig; - if ( dig == 10 ) - { - newMantBuf.setCharAt( i, '0' ); - continue; - } - newMantBuf.setCharAt( i, digits.charAt( dig ) ); - roundMore = false; - break; - } - if ( roundMore ) - { - // If this happens, we need to prepend a 1. But I haven't - // found a test case yet, so I'm leaving it out for now. - // But if you get this message, please let me know! - newMantBuf.append( "ROUNDMORE" ); - } - } - - // Chop any trailing zeros. - int len = newMantBuf.length(); - while ( newMantBuf.charAt( len - 1 ) == '0' ) - newMantBuf.setLength( --len ); - // And chop a trailing dot, if any. - if ( newMantBuf.charAt( len - 1 ) == '.' ) - newMantBuf.setLength( --len ); - - // Done. - return ( negative ? "-" : "" ) + - newMantBuf + - ( expStr.length() != 0 ? ( "e" + expStr ) : "" ); - } - - -/****************************************************************************** - /// Test program. - public static void main( String[] args ) - { - System.out.println( "Starting tests." ); - show( Fmt.fmt( "Hello there." ) ); - show( Fmt.fmt( 123 ) ); - show( Fmt.fmt( 123, 10 ) ); - show( Fmt.fmt( 123, 10, Fmt.ZF ) ); - show( Fmt.fmt( 123, 10, Fmt.LJ ) ); - show( Fmt.fmt( -123 ) ); - show( Fmt.fmt( -123, 10 ) ); - show( Fmt.fmt( -123, 10, Fmt.ZF ) ); - show( Fmt.fmt( -123, 10, Fmt.LJ ) ); - show( Fmt.fmt( (byte) 0xbe, 22, Fmt.OC ) ); - show( Fmt.fmt( (short) 0xbabe, 22, Fmt.OC ) ); - show( Fmt.fmt( 0xcafebabe, 22, Fmt.OC ) ); - show( Fmt.fmt( 0xdeadbeefcafebabeL, 22, Fmt.OC ) ); - show( Fmt.fmt( 0x8000000000000000L, 22, Fmt.OC ) ); - show( Fmt.fmt( (byte) 0xbe, 16, Fmt.HX ) ); - show( Fmt.fmt( (short) 0xbabe, 16, Fmt.HX ) ); - show( Fmt.fmt( 0xcafebabe, 16, Fmt.HX ) ); - show( Fmt.fmt( 0xdeadbeefcafebabeL, 16, Fmt.HX ) ); - show( Fmt.fmt( 0x8000000000000000L, 16, Fmt.HX ) ); - show( Fmt.fmt( 'c' ) ); - show( Fmt.fmt( new java.util.Date() ) ); - show( Fmt.fmt( 123.456F ) ); - show( Fmt.fmt( 123456000000000000.0F ) ); - show( Fmt.fmt( 123.456F, 0, 8 ) ); - show( Fmt.fmt( 123.456F, 0, 7 ) ); - show( Fmt.fmt( 123.456F, 0, 6 ) ); - show( Fmt.fmt( 123.456F, 0, 5 ) ); - show( Fmt.fmt( 123.456F, 0, 4 ) ); - show( Fmt.fmt( 123.456F, 0, 3 ) ); - show( Fmt.fmt( 123.456F, 0, 2 ) ); - show( Fmt.fmt( 123.456F, 0, 1 ) ); - show( Fmt.fmt( 123456000000000000.0F, 0, 4 ) ); - show( Fmt.fmt( -123.456F, 0, 4 ) ); - show( Fmt.fmt( -123456000000000000.0F, 0, 4 ) ); - show( Fmt.fmt( 123.0F ) ); - show( Fmt.fmt( 123.0D ) ); - show( Fmt.fmt( 1.234567890123456789F ) ); - show( Fmt.fmt( 1.234567890123456789D ) ); - show( Fmt.fmt( 1234567890123456789F ) ); - show( Fmt.fmt( 1234567890123456789D ) ); - show( Fmt.fmt( 0.000000000000000000001234567890123456789F ) ); - show( Fmt.fmt( 0.000000000000000000001234567890123456789D ) ); - show( Fmt.fmt( 12300.0F ) ); - show( Fmt.fmt( 12300.0D ) ); - show( Fmt.fmt( 123000.0F ) ); - show( Fmt.fmt( 123000.0D ) ); - show( Fmt.fmt( 1230000.0F ) ); - show( Fmt.fmt( 1230000.0D ) ); - show( Fmt.fmt( 12300000.0F ) ); - show( Fmt.fmt( 12300000.0D ) ); - show( Fmt.fmt( Float.NaN ) ); - show( Fmt.fmt( Float.POSITIVE_INFINITY ) ); - show( Fmt.fmt( Float.NEGATIVE_INFINITY ) ); - show( Fmt.fmt( Double.NaN ) ); - show( Fmt.fmt( Double.POSITIVE_INFINITY ) ); - show( Fmt.fmt( Double.NEGATIVE_INFINITY ) ); - show( Fmt.fmt( 1.0F / 8.0F ) ); - show( Fmt.fmt( 1.0D / 8.0D ) ); - System.out.println( "Done with tests." ); - } - - private static void show( String str ) - { - System.out.println( "#" + str + "#" ); - } -******************************************************************************/ - - } diff --git a/src/Acme/IntHashtable.java b/src/Acme/IntHashtable.java deleted file mode 100644 index a4dcae34..00000000 --- a/src/Acme/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 Acme; - -import java.util.*; - -/// A Hashtable that uses ints as the keys. -//

-// 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. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @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/src/Acme/JPM/Decoders/ImageDecoder.java b/src/Acme/JPM/Decoders/ImageDecoder.java deleted file mode 100644 index 01dec95c..00000000 --- a/src/Acme/JPM/Decoders/ImageDecoder.java +++ /dev/null @@ -1,314 +0,0 @@ -// ImageDecoder - abstract class for reading in an image -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Decoders; - -import java.util.*; -import java.io.*; -import java.awt.image.*; - -/// Abstract class for reading in an image. -//

-// A framework for classes that read in and decode an image in -// a particular file format. -//

-// This provides a very simplified rendition of the ImageProducer interface. -// It requires the decoder to read the image a row at a time. It requires -// use of the RGBdefault color model. -// If you want more flexibility you can always implement ImageProducer -// directly. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see PpmDecoder -// @see Acme.JPM.Encoders.ImageEncoder - -public abstract class ImageDecoder implements ImageProducer - { - - private InputStream in; - private int width, height; - private boolean[] rowsRead; - private int[][] rgbPixels; - private boolean startedRead = false; - private boolean gotSize = false; - private boolean err = false; - private boolean producing = false; - private Vector consumers = new Vector(); - private static final ColorModel model = ColorModel.getRGBdefault(); - - - /// Constructor. - // @param in The stream to read the bytes from. - public ImageDecoder( InputStream in ) - { - this.in = in; - } - - - // Methods that subclasses implement. - - /// Subclasses implement this to read in enough of the image stream - // to figure out the width and height. - abstract void readHeader( InputStream in ) throws IOException; - - /// Subclasses implement this to return the width, or -1 if not known. - abstract int getWidth(); - - /// Subclasses implement this to return the height, or -1 if not known. - abstract int getHeight(); - - /// Subclasses implement this to read pixel data into the rgbRow - // array, an int[width]. One int per pixel, no offsets or padding, - // RGBdefault (AARRGGBB) color model. - abstract void readRow( InputStream in, int row, int[] rgbRow ) throws IOException; - - - // Our own methods. - - void readImage() - { - try - { - readHeader( in ); - width = getWidth(); - height = getHeight(); - if ( width == -1 || height == -1 ) - err = true; - else - { - rowsRead = new boolean[height]; - for ( int row = 0; row < height; ++row ) - rowsRead[row] = false; - gotSize = true; - notifyThem(); - rgbPixels = new int[height][width]; - for ( int row = 0; row < height; ++row ) - { - readRow( in, row, rgbPixels[row] ); - rowsRead[row] = true; - notifyThem(); - } - } - } - catch ( IOException e ) - { - err = true; - width = -1; - height = -1; - rowsRead = null; - rgbPixels = null; - } - } - - private synchronized void notifyThem() - { - notifyAll(); - } - - void sendImage() - { - // Grab the list of consumers, in case it changes while we're sending. - ImageConsumer[] c = new ImageConsumer[consumers.size()]; - int i; - for ( i = 0; i < c.length; ++i ) - c[i] = (ImageConsumer) consumers.elementAt( i ); - // Try to be as parallel as possible. - waitForSize(); - for ( i = 0; i < c.length; ++i ) - sendHead( c[i] ); - for ( int row = 0; row < height; ++row ) - for ( i = 0; i < c.length; ++i ) - sendPixelRow( c[i], row ); - for ( i = 0; i < c.length; ++i ) - sendTail( c[i] ); - producing = false; - } - - private synchronized void waitForSize() - { - while ( ( ! err ) && ( ! gotSize )) - { - try - { - wait(); - } - catch ( InterruptedException ignore ) {} - } - } - - private synchronized void waitForRow( int row ) - { - while ( ( ! err ) && ( ! rowsRead[row] ) ) - { - try - { - wait(); - } - catch ( InterruptedException ignore ) {} - } - } - - private void sendHead( ImageConsumer ic ) - { - if ( err ) - return; - ic.setDimensions( width, height ); - ic.setColorModel( model ); - ic.setHints( - ImageConsumer.TOPDOWNLEFTRIGHT | ImageConsumer.COMPLETESCANLINES | - ImageConsumer.SINGLEPASS | ImageConsumer.SINGLEFRAME ); - } - - private void sendPixelRow( ImageConsumer ic, int row ) - { - if ( err ) - return; - waitForRow( row ); - if ( err ) - return; - ic.setPixels( 0, row, width, 1, model, rgbPixels[row], 0, width ); - } - - private void sendTail( ImageConsumer ic ) - { - if ( err ) - ic.imageComplete( ImageConsumer.IMAGEERROR ); - else - ic.imageComplete( ImageConsumer.STATICIMAGEDONE ); - - } - - - // Methods from ImageProducer. - - /// This method is used to register an ImageConsumer with the - // ImageProducer for access to the image data during a later - // reconstruction of the Image. The ImageProducer may, at its - // discretion, start delivering the image data to the consumer - // using the ImageConsumer interface immediately, or when the - // next available image reconstruction is triggered by a call - // to the startProduction method. - // @see #startProduction - public void addConsumer( ImageConsumer ic ) - { - if ( ic != null && ! isConsumer( ic ) ) - consumers.addElement( ic ); - } - - /// This method determines if a given ImageConsumer object - // is currently registered with this ImageProducer as one - // of its consumers. - public boolean isConsumer( ImageConsumer ic ) - { - return consumers.contains( ic ); - } - - /// This method removes the given ImageConsumer object - // from the list of consumers currently registered to - // receive image data. It is not considered an error - // to remove a consumer that is not currently registered. - // The ImageProducer should stop sending data to this - // consumer as soon as is feasible. - public void removeConsumer( ImageConsumer ic ) - { - consumers.removeElement( ic ); - } - - /// This method both registers the given ImageConsumer object - // as a consumer and starts an immediate reconstruction of - // the image data which will then be delivered to this - // consumer and any other consumer which may have already - // been registered with the producer. This method differs - // from the addConsumer method in that a reproduction of - // the image data should be triggered as soon as possible. - // @see #addConsumer - public void startProduction( ImageConsumer ic ) - { - addConsumer( ic ); - if ( ! startedRead ) - { - startedRead = true; - new ImageDecoderRead( this ); - } - if ( ! producing ) - { - producing = true; - sendImage(); - } - } - - /// This method is used by an ImageConsumer to request that - // the ImageProducer attempt to resend the image data one - // more time in TOPDOWNLEFTRIGHT order so that higher - // quality conversion algorithms which depend on receiving - // pixels in order can be used to produce a better output - // version of the image. The ImageProducer is free to - // ignore this call if it cannot resend the data in that - // order. If the data can be resent, then the ImageProducer - // should respond by executing the following minimum set of - // ImageConsumer method calls: - //

-    //     ic.setHints( TOPDOWNLEFTRIGHT | [otherhints] );
-    //     ic.setPixels( [...] );    // as many times as needed
-    //     ic.imageComplete( [status] );
-    // 
- // @see ImageConsumer#setHints - public void requestTopDownLeftRightResend( ImageConsumer ic ) - { - addConsumer( ic ); - waitForSize(); - sendHead( ic ); - for ( int row = 0; row < height; ++row ) - sendPixelRow( ic, row ); - sendTail( ic ); - } - - } - - -class ImageDecoderRead extends Thread - { - - private ImageDecoder parent; - - public ImageDecoderRead( ImageDecoder parent ) - { - this.parent = parent; - start(); - } - - // Methods from Runnable. - - public void run() - { - parent.readImage(); - } - - } diff --git a/src/Acme/JPM/Decoders/PpmDecoder.java b/src/Acme/JPM/Decoders/PpmDecoder.java deleted file mode 100644 index 8c39f9ce..00000000 --- a/src/Acme/JPM/Decoders/PpmDecoder.java +++ /dev/null @@ -1,267 +0,0 @@ -// PpmDecoder - read in a PPM image -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Decoders; - -import java.io.*; -import java.awt.image.*; - -/// Read in a PPM image. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see Acme.JPM.Encoders.PpmEncoder - -public class PpmDecoder extends ImageDecoder - { - - /// Constructor. - // @param in The stream to read the bytes from. - public PpmDecoder( InputStream in ) - { - super( in ); - } - - - private int type; - private static final int PBM_ASCII = 1; - private static final int PGM_ASCII = 2; - private static final int PPM_ASCII = 3; - private static final int PBM_RAW = 4; - private static final int PGM_RAW = 5; - private static final int PPM_RAW = 6; - - private int width = -1, height = -1; - private int maxval; - - /// Subclasses implement this to read in enough of the image stream - // to figure out the width and height. - void readHeader( InputStream in ) throws IOException - { - char c1, c2; - - c1 = (char) readByte( in ); - c2 = (char) readByte( in ); - - if ( c1 != 'P' ) - throw new IOException( "not a PBM/PGM/PPM file" ); - switch ( c2 ) - { - case '1': - type = PBM_ASCII; - break; - case '2': - type = PGM_ASCII; - break; - case '3': - type = PPM_ASCII; - break; - case '4': - type = PBM_RAW; - break; - case '5': - type = PGM_RAW; - break; - case '6': - type = PPM_RAW; - break; - default: - throw new IOException( "not a standard PBM/PGM/PPM file" ); - } - width = readInt( in ); - height = readInt( in ); - if ( type != PBM_ASCII && type != PBM_RAW ) - maxval = readInt( in ); - } - - /// Subclasses implement this to return the width, or -1 if not known. - int getWidth() - { - return width; - } - - /// Subclasses implement this to return the height, or -1 if not known. - int getHeight() - { - return height; - } - - /// Subclasses implement this to read pixel data into the rgbRow - // array, an int[width]. One int per pixel, no offsets or padding, - // RGBdefault (AARRGGBB) color model - void readRow( InputStream in, int row, int[] rgbRow ) throws IOException - { - int col, r, g, b; - int rgb = 0; - char c; - - for ( col = 0; col < width; ++col ) - { - switch ( type ) - { - case PBM_ASCII: - c = readChar( in ); - if ( c == '1' ) - rgb = 0xff000000; - else if ( c == '0' ) - rgb = 0xffffffff; - else - throw new IOException( "illegal PBM bit" ); - break; - case PGM_ASCII: - g = readInt( in ); - rgb = makeRgb( g, g, g ); - break; - case PPM_ASCII: - r = readInt( in ); - g = readInt( in ); - b = readInt( in ); - rgb = makeRgb( r, g, b ); - break; - case PBM_RAW: - if ( readBit( in ) ) - rgb = 0xff000000; - else - rgb = 0xffffffff; - break; - case PGM_RAW: - g = readByte( in ); - if ( maxval != 255 ) - g = fixDepth( g ); - rgb = makeRgb( g, g, g ); - break; - case PPM_RAW: - r = readByte( in ); - g = readByte( in ); - b = readByte( in ); - if ( maxval != 255 ) - { - r = fixDepth( r ); - g = fixDepth( g ); - b = fixDepth( b ); - } - rgb = makeRgb( r, g, b ); - break; - } - rgbRow[col] = rgb; - } - } - - /// Utility routine to read a byte. Instead of returning -1 on - // EOF, it throws an exception. - private static int readByte( InputStream in ) throws IOException - { - int b = in.read(); - if ( b == -1 ) - throw new EOFException(); - return b; - } - - private int bitshift = -1; - private int bits; - - /// Utility routine to read a bit, packed eight to a byte, big-endian. - private boolean readBit( InputStream in ) throws IOException - { - if ( bitshift == -1 ) - { - bits = readByte( in ); - bitshift = 7; - } - boolean bit = ( ( ( bits >> bitshift ) & 1 ) != 0 ); - --bitshift; - return bit; - } - - /// Utility routine to read a character, ignoring comments. - private static char readChar( InputStream in ) throws IOException - { - char c; - - c = (char) readByte( in ); - if ( c == '#' ) - { - do - { - c = (char) readByte( in ); - } - while ( c != '\n' && c != '\r' ); - } - - return c; - } - - /// Utility routine to read the first non-whitespace character. - private static char readNonwhiteChar( InputStream in ) throws IOException - { - char c; - - do - { - c = readChar( in ); - } - while ( c == ' ' || c == '\t' || c == '\n' || c == '\r' ); - - return c; - } - - /// Utility routine to read an ASCII integer, ignoring comments. - private static int readInt( InputStream in ) throws IOException - { - char c; - int i; - - c = readNonwhiteChar( in ); - if ( c < '0' || c > '9' ) - throw new IOException( "junk in file where integer should be" ); - - i = 0; - do - { - i = i * 10 + c - '0'; - c = readChar( in ); - } - while ( c >= '0' && c <= '9' ); - - return i; - } - - /// Utility routine to rescale a pixel value from a non-eight-bit maxval. - private int fixDepth( int p ) - { - return ( p * 255 + maxval / 2 ) / maxval; - } - - /// Utility routine make an RGBdefault pixel from three color values. - private static int makeRgb( int r, int g, int b ) - { - return 0xff000000 | ( r << 16 ) | ( g << 8 ) | b; - } - - } diff --git a/src/Acme/JPM/Encoders/GifEncoder.java b/src/Acme/JPM/Encoders/GifEncoder.java deleted file mode 100644 index 18022542..00000000 --- a/src/Acme/JPM/Encoders/GifEncoder.java +++ /dev/null @@ -1,691 +0,0 @@ -// GifEncoder - write out an image as a GIF -// -// Transparency handling and variable bit size courtesy of Jack Palevich. -// -// Copyright (C)1996,1998 by Jef Poskanzer . 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 Acme.JPM.Encoders; - -import java.util.*; -import java.io.*; -import java.awt.Image; -import java.awt.image.*; - -/// Write out an image as a GIF. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @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 ); - - } - - Acme.IntHashtable colorHash; - - void encodeDone() throws IOException - { - int transparentIndex = -1; - int transparentRgb = -1; - // Put all the pixels into a hash table. - colorHash = new Acme.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 - { - byte[] buf = str.getBytes(); - out.write( buf ); - } - - // Adapted from ppmtogif, which is based on GIFENCOD by David - // Rowley . 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/src/Acme/JPM/Encoders/ImageEncoder.java b/src/Acme/JPM/Encoders/ImageEncoder.java deleted file mode 100644 index 9b5e8e56..00000000 --- a/src/Acme/JPM/Encoders/ImageEncoder.java +++ /dev/null @@ -1,271 +0,0 @@ -// ImageEncoder - abstract class for writing out an image -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Encoders; - -import java.util.*; -import java.io.*; -import java.awt.Image; -import java.awt.image.*; - -/// Abstract class for writing out an image. -//

-// A framework for classes that encode and write out an image in -// a particular file format. -//

-// 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. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @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/src/Acme/JPM/Encoders/JpegEncoder.java b/src/Acme/JPM/Encoders/JpegEncoder.java deleted file mode 100644 index 8f434d2b..00000000 --- a/src/Acme/JPM/Encoders/JpegEncoder.java +++ /dev/null @@ -1,448 +0,0 @@ -// JpegEncoder - write out an image as a JPEG -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Encoders; - -import java.util.*; -import java.io.*; -import java.awt.Image; -import java.awt.image.*; - -/// Write out an image as a JPEG. -// DOESN'T WORK YET. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see ToJpeg - -public class JpegEncoder extends ImageEncoder - { - - /// Constructor. - // @param img The image to encode. - // @param out The stream to write the JPEG to. - public JpegEncoder( Image img, OutputStream out ) throws IOException - { - super( img, out ); - } - - /// Constructor. - // @param prod The ImageProducer to encode. - // @param out The stream to write the JPEG to. - public JpegEncoder( ImageProducer prod, OutputStream out ) throws IOException - { - super( prod, out ); - } - - int qfactor = 100; - - /// Set the Q-factor. - public void setQfactor( int qfactor ) - { - this.qfactor = qfactor; - } - - 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 ); - - } - - void encodeDone() throws IOException - { - writeJfifHuffHeader(); - // !!! - } - - - // Some of the following code is derived from the Berkeley Continuous - // Media Toolkit (http://bmrc.berkeley.edu/projects/cmt/), which is - // Copyright (c) 1996 The Regents of the University of California. - // All rights reserved. - // - // IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR - // DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING - // OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE - // UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH - // DAMAGE. - // - // THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, - // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - // AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS - // ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION - // TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. - - - // This array represents the default JFIF header for quality = 100 and - // size = 640x480, with Huffman tables. The values are adjusted when a - // file is generated. - private static byte[] jfifHuff100Header = { - // SOI - (byte) 0xFF, (byte) 0xD8, - - // JFIF header - (byte) 0xFF, (byte) 0xE0, // Marker - (byte) 0x00, (byte) 0x10, // Length = 16 bytes - (byte) 0x4A, (byte) 0x46, (byte) 0x49, (byte) 0x46, // "JFIF" - (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00, - (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, - - // Start of frame (section B.2.2) - (byte) 0xFF, (byte) 0xC0, // Baseline DCT - (byte) 0x00, (byte) 0x11, // Length = 17 bytes - (byte) 0x08, // Sample precision - (byte) 0x01, (byte) 0xE0, // Height - (byte) 0x02, (byte) 0x80, // Width - (byte) 0x03, // Number of components = 3 - // Scan 1: 2:1 horiz, (byte) 1:1 vertical, (byte) use QT 0 - (byte) 0x01, (byte) 0x21, (byte) 0x00, - // Scan 2: 1:1 horiz, (byte) 1:1 vertical, (byte) use QT 1 - (byte) 0x02, (byte) 0x11, (byte) 0x01, - // Scan 3: 1:1 horiz, (byte) 1:1 vertical, (byte) use QT 1 - (byte) 0x03, (byte) 0x11, (byte) 0x01, - - // Define Quant table (section B.2.4.1) - (byte) 0xFF, (byte) 0xDB, // Marker - (byte) 0x00, (byte) 0x84, // Length (both tables) - (byte) 0x00, // 8 bit values, (byte) table 0 - (byte) 0x10, (byte) 0x0B, (byte) 0x0C, (byte) 0x0E, (byte) 0x0C, - (byte) 0x0A, (byte) 0x10, (byte) 0x0E, (byte) 0x0D, (byte) 0x0E, - (byte) 0x12, (byte) 0x11, (byte) 0x10, (byte) 0x13, (byte) 0x18, - (byte) 0x28, (byte) 0x1A, (byte) 0x18, (byte) 0x16, (byte) 0x16, - (byte) 0x18, (byte) 0x31, (byte) 0x23, (byte) 0x25, (byte) 0x1D, - (byte) 0x28, (byte) 0x3A, (byte) 0x33, (byte) 0x3D, (byte) 0x3C, - (byte) 0x39, (byte) 0x33, (byte) 0x38, (byte) 0x37, (byte) 0x40, - (byte) 0x48, (byte) 0x5C, (byte) 0x4E, (byte) 0x40, (byte) 0x44, - (byte) 0x57, (byte) 0x45, (byte) 0x37, (byte) 0x38, (byte) 0x50, - (byte) 0x6D, (byte) 0x51, (byte) 0x57, (byte) 0x5F, (byte) 0x62, - (byte) 0x67, (byte) 0x68, (byte) 0x67, (byte) 0x3E, (byte) 0x4D, - (byte) 0x71, (byte) 0x79, (byte) 0x70, (byte) 0x64, (byte) 0x78, - (byte) 0x5C, (byte) 0x65, (byte) 0x67, (byte) 0x63, - - (byte) 0x01, // 8 bit values, (byte) table 1 - (byte) 0x11, (byte) 0x12, (byte) 0x12, (byte) 0x18, (byte) 0x15, - (byte) 0x18, (byte) 0x2F, (byte) 0x1A, (byte) 0x1A, (byte) 0x2F, - (byte) 0x63, (byte) 0x42, (byte) 0x38, (byte) 0x42, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - - // Define huffman table (section B.2.4.1) - (byte) 0xFF, (byte) 0xC4, // Marker - (byte) 0x00, (byte) 0x1F, // Length (31 bytes) - (byte) 0x00, // DC, (byte) table 0 - (byte) 0x00, (byte) 0x01, (byte) 0x05, (byte) 0x01, (byte) 0x01, - (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, - (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08, - (byte) 0x09, (byte) 0x0A, (byte) 0x0B, - - // Define huffman table (section B.2.4.1) - (byte) 0xFF, (byte) 0xC4, // Marker - (byte) 0x00, (byte) 0xB5, // Length (181 bytes) - (byte) 0x10, // AC, (byte) table 0 - (byte) 0x00, (byte) 0x02, (byte) 0x01, (byte) 0x03, (byte) 0x03, - (byte) 0x02, (byte) 0x04, (byte) 0x03, (byte) 0x05, (byte) 0x05, - (byte) 0x04, (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x01, - (byte) 0x7D, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x00, - (byte) 0x04, (byte) 0x11, (byte) 0x05, (byte) 0x12, (byte) 0x21, - (byte) 0x31, (byte) 0x41, (byte) 0x06, (byte) 0x13, (byte) 0x51, - (byte) 0x61, (byte) 0x07, (byte) 0x22, (byte) 0x71, (byte) 0x14, - (byte) 0x32, (byte) 0x81, (byte) 0x91, (byte) 0xA1, (byte) 0x08, - (byte) 0x23, (byte) 0x42, (byte) 0xB1, (byte) 0xC1, (byte) 0x15, - (byte) 0x52, (byte) 0xD1, (byte) 0xF0, (byte) 0x24, (byte) 0x33, - (byte) 0x62, (byte) 0x72, (byte) 0x82, (byte) 0x09, (byte) 0x0A, - (byte) 0x16, (byte) 0x17, (byte) 0x18, (byte) 0x19, (byte) 0x1A, - (byte) 0x25, (byte) 0x26, (byte) 0x27, (byte) 0x28, (byte) 0x29, - (byte) 0x2A, (byte) 0x34, (byte) 0x35, (byte) 0x36, (byte) 0x37, - (byte) 0x38, (byte) 0x39, (byte) 0x3A, (byte) 0x43, (byte) 0x44, - (byte) 0x45, (byte) 0x46, (byte) 0x47, (byte) 0x48, (byte) 0x49, - (byte) 0x4A, (byte) 0x53, (byte) 0x54, (byte) 0x55, (byte) 0x56, - (byte) 0x57, (byte) 0x58, (byte) 0x59, (byte) 0x5A, (byte) 0x63, - (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, - (byte) 0x69, (byte) 0x6A, (byte) 0x73, (byte) 0x74, (byte) 0x75, - (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, - (byte) 0x83, (byte) 0x84, (byte) 0x85, (byte) 0x86, (byte) 0x87, - (byte) 0x88, (byte) 0x89, (byte) 0x8A, (byte) 0x92, (byte) 0x93, - (byte) 0x94, (byte) 0x95, (byte) 0x96, (byte) 0x97, (byte) 0x98, - (byte) 0x99, (byte) 0x9A, (byte) 0xA2, (byte) 0xA3, (byte) 0xA4, - (byte) 0xA5, (byte) 0xA6, (byte) 0xA7, (byte) 0xA8, (byte) 0xA9, - (byte) 0xAA, (byte) 0xB2, (byte) 0xB3, (byte) 0xB4, (byte) 0xB5, - (byte) 0xB6, (byte) 0xB7, (byte) 0xB8, (byte) 0xB9, (byte) 0xBA, - (byte) 0xC2, (byte) 0xC3, (byte) 0xC4, (byte) 0xC5, (byte) 0xC6, - (byte) 0xC7, (byte) 0xC8, (byte) 0xC9, (byte) 0xCA, (byte) 0xD2, - (byte) 0xD3, (byte) 0xD4, (byte) 0xD5, (byte) 0xD6, (byte) 0xD7, - (byte) 0xD8, (byte) 0xD9, (byte) 0xDA, (byte) 0xE1, (byte) 0xE2, - (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, - (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xF1, (byte) 0xF2, - (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, - (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, - - // Define huffman table (section B.2.4.1) - (byte) 0xFF, (byte) 0xC4, // Marker - (byte) 0x00, (byte) 0x1F, // Length (31 bytes) - (byte) 0x01, // DC, (byte) table 1 - (byte) 0x00, (byte) 0x03, (byte) 0x01, (byte) 0x01, (byte) 0x01, - (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01, - (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, - (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08, - (byte) 0x09, (byte) 0x0A, (byte) 0x0B, - - // Define huffman table (section B.2.4.1) - (byte) 0xFF, (byte) 0xC4, // Marker - (byte) 0x00, (byte) 0xB5, // Length (181 bytes) - (byte) 0x11, // AC, (byte) table 1 - (byte) 0x00, (byte) 0x02, (byte) 0x01, (byte) 0x02, (byte) 0x04, - (byte) 0x04, (byte) 0x03, (byte) 0x04, (byte) 0x07, (byte) 0x05, - (byte) 0x04, (byte) 0x04, (byte) 0x00, (byte) 0x01, (byte) 0x02, - (byte) 0x77, (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, - (byte) 0x11, (byte) 0x04, (byte) 0x05, (byte) 0x21, (byte) 0x31, - (byte) 0x06, (byte) 0x12, (byte) 0x41, (byte) 0x51, (byte) 0x07, - (byte) 0x61, (byte) 0x71, (byte) 0x13, (byte) 0x22, (byte) 0x32, - (byte) 0x81, (byte) 0x08, (byte) 0x14, (byte) 0x42, (byte) 0x91, - (byte) 0xA1, (byte) 0xB1, (byte) 0xC1, (byte) 0x09, (byte) 0x23, - (byte) 0x33, (byte) 0x52, (byte) 0xF0, (byte) 0x15, (byte) 0x62, - (byte) 0x72, (byte) 0xD1, (byte) 0x0A, (byte) 0x16, (byte) 0x24, - (byte) 0x34, (byte) 0xE1, (byte) 0x25, (byte) 0xF1, (byte) 0x17, - (byte) 0x18, (byte) 0x19, (byte) 0x1A, (byte) 0x26, (byte) 0x27, - (byte) 0x28, (byte) 0x29, (byte) 0x2A, (byte) 0x35, (byte) 0x36, - (byte) 0x37, (byte) 0x38, (byte) 0x39, (byte) 0x3A, (byte) 0x43, - (byte) 0x44, (byte) 0x45, (byte) 0x46, (byte) 0x47, (byte) 0x48, - (byte) 0x49, (byte) 0x4A, (byte) 0x53, (byte) 0x54, (byte) 0x55, - (byte) 0x56, (byte) 0x57, (byte) 0x58, (byte) 0x59, (byte) 0x5A, - (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, - (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x73, (byte) 0x74, - (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, - (byte) 0x7A, (byte) 0x82, (byte) 0x83, (byte) 0x84, (byte) 0x85, - (byte) 0x86, (byte) 0x87, (byte) 0x88, (byte) 0x89, (byte) 0x8A, - (byte) 0x92, (byte) 0x93, (byte) 0x94, (byte) 0x95, (byte) 0x96, - (byte) 0x97, (byte) 0x98, (byte) 0x99, (byte) 0x9A, (byte) 0xA2, - (byte) 0xA3, (byte) 0xA4, (byte) 0xA5, (byte) 0xA6, (byte) 0xA7, - (byte) 0xA8, (byte) 0xA9, (byte) 0xAA, (byte) 0xB2, (byte) 0xB3, - (byte) 0xB4, (byte) 0xB5, (byte) 0xB6, (byte) 0xB7, (byte) 0xB8, - (byte) 0xB9, (byte) 0xBA, (byte) 0xC2, (byte) 0xC3, (byte) 0xC4, - (byte) 0xC5, (byte) 0xC6, (byte) 0xC7, (byte) 0xC8, (byte) 0xC9, - (byte) 0xCA, (byte) 0xD2, (byte) 0xD3, (byte) 0xD4, (byte) 0xD5, - (byte) 0xD6, (byte) 0xD7, (byte) 0xD8, (byte) 0xD9, (byte) 0xDA, - (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, - (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xF2, - (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, - (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, - - // Start of Scan (section B.2.3) - (byte) 0xFF, (byte) 0xDA, // Marker - (byte) 0x00, (byte) 0x0C, // Length of header - (byte) 0x03, // Number of image components - // Scan 1: use DC/AC huff tables 0/0 - (byte) 0x01, (byte) 0x00, - // Scan 2: use DC/AC huff tables 1/1 - (byte) 0x02, (byte) 0x11, - // Scan 3: use DC/AC huff tables 1/1 - (byte) 0x03, (byte) 0x11, - (byte) 0x00, (byte) 0x3F, (byte) 0x00 // Not used - }; - - // This array represents the default JFIF header for quality = 100 and - // size = 640x480, without Huffman tables. The values are adjusted when a - // file is generated. - private static byte[] jfifNoHuff100Header = { - // SOI - (byte) 0xFF, (byte) 0xD8, - - // JFIF header - (byte) 0xFF, (byte) 0xE0, // Marker - (byte) 0x00, (byte) 0x10, // Length = 16 bytes - (byte) 0x4A, (byte) 0x46, (byte) 0x49, (byte) 0x46, // "JFIF" - (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00, - (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, - - // Start of frame (section B.2.2) - (byte) 0xFF, (byte) 0xC0, // Baseline DCT - (byte) 0x00, (byte) 0x11, // Length = 17 bytes - (byte) 0x08, // Sample precision - (byte) 0x01, (byte) 0xE0, // Height - (byte) 0x02, (byte) 0x80, // Width - (byte) 0x03, // Number of components = 3 - // Scan 1: 2:1 horiz, (byte) 1:1 vertical, (byte) use QT 0 - (byte) 0x01, (byte) 0x21, (byte) 0x00, - // Scan 2: 1:1 horiz, (byte) 1:1 vertical, (byte) use QT 1 - (byte) 0x02, (byte) 0x11, (byte) 0x01, - // Scan 3: 1:1 horiz, (byte) 1:1 vertical, (byte) use QT 1 - (byte) 0x03, (byte) 0x11, (byte) 0x01, - - // Define Quant table (section B.2.4.1) - (byte) 0xFF, (byte) 0xDB, // Marker - (byte) 0x00, (byte) 0x84, // Length (both tables) - (byte) 0x00, // 8 bit values, (byte) table 0 - (byte) 0x10, (byte) 0x0B, (byte) 0x0C, (byte) 0x0E, (byte) 0x0C, - (byte) 0x0A, (byte) 0x10, (byte) 0x0E, (byte) 0x0D, (byte) 0x0E, - (byte) 0x12, (byte) 0x11, (byte) 0x10, (byte) 0x13, (byte) 0x18, - (byte) 0x28, (byte) 0x1A, (byte) 0x18, (byte) 0x16, (byte) 0x16, - (byte) 0x18, (byte) 0x31, (byte) 0x23, (byte) 0x25, (byte) 0x1D, - (byte) 0x28, (byte) 0x3A, (byte) 0x33, (byte) 0x3D, (byte) 0x3C, - (byte) 0x39, (byte) 0x33, (byte) 0x38, (byte) 0x37, (byte) 0x40, - (byte) 0x48, (byte) 0x5C, (byte) 0x4E, (byte) 0x40, (byte) 0x44, - (byte) 0x57, (byte) 0x45, (byte) 0x37, (byte) 0x38, (byte) 0x50, - (byte) 0x6D, (byte) 0x51, (byte) 0x57, (byte) 0x5F, (byte) 0x62, - (byte) 0x67, (byte) 0x68, (byte) 0x67, (byte) 0x3E, (byte) 0x4D, - (byte) 0x71, (byte) 0x79, (byte) 0x70, (byte) 0x64, (byte) 0x78, - (byte) 0x5C, (byte) 0x65, (byte) 0x67, (byte) 0x63, - - (byte) 0x01, // 8 bit values, (byte) table 1 - (byte) 0x11, (byte) 0x12, (byte) 0x12, (byte) 0x18, (byte) 0x15, - (byte) 0x18, (byte) 0x2F, (byte) 0x1A, (byte) 0x1A, (byte) 0x2F, - (byte) 0x63, (byte) 0x42, (byte) 0x38, (byte) 0x42, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - (byte) 0x63, (byte) 0x63, (byte) 0x63, (byte) 0x63, - - // Start of Scan (section B.2.3) - (byte) 0xFF, (byte) 0xDA, // Marker - (byte) 0x00, (byte) 0x0C, // Length of header - (byte) 0x03, // Number of image components - // Scan 1: use DC/AC huff tables 0/0 - (byte) 0x01, (byte) 0x00, - // Scan 2: use DC/AC huff tables 1/1 - (byte) 0x02, (byte) 0x11, - // Scan 3: use DC/AC huff tables 1/1 - (byte) 0x03, (byte) 0x11, - (byte) 0x00, (byte) 0x3F, (byte) 0x00 // Not used - }; - - private void writeJfifHuffHeader() throws IOException - { - byte[] newHeader = new byte[jfifHuff100Header.length]; - - System.arraycopy( - jfifHuff100Header, 0, newHeader, 0, jfifHuff100Header.length ); - - // Set image width in JFIF header. - newHeader[27] = (byte) ( ( width >>> 8 ) & 0xff ); - newHeader[28] = (byte) ( width & 0xff ); - - // Set image height in JFIF header. - newHeader[25] = (byte) ( ( height >>> 8 ) & 0xff ); - newHeader[26] = (byte) ( height & 0xff ); - - // Adjust the quality factor. - // - // The default quality factor is 100, therefore if - // our quality factor does not equal 100 we must - // scale the quantization matrices in the JFIF header. - // Note that values are clipped to a max of 255. - if ( qfactor != 100 ) - { - for ( int i = 44; i < 108; ++i ) - { - int t = ( newHeader[i] * qfactor ) / 100; - newHeader[i] = (byte) Math.max( t, 0xff ); - } - for ( int i = 109; i < 173; ++i ) - { - int t = ( newHeader[i] * qfactor ) / 100; - newHeader[i] = (byte) Math.max( t, 0xff ); - } - } - - // Write out buffer. - out.write( newHeader ); - } - - private void writeJfifNoHuffHeader() throws IOException - { - byte[] newHeader = new byte[jfifNoHuff100Header.length]; - - System.arraycopy( - jfifNoHuff100Header, 0, newHeader, 0, jfifNoHuff100Header.length ); - - // Set image width in JFIF header. - newHeader[27] = (byte) ( ( width >>> 8 ) & 0xff ); - newHeader[28] = (byte) ( width & 0xff ); - - // Set image height in JFIF header. - newHeader[25] = (byte) ( ( height >>> 8 ) & 0xff ); - newHeader[26] = (byte) ( height & 0xff ); - - // Adjust the quality factor. - // - // The default quality factor is 100, therefore if - // our quality factor does not equal 100 we must - // scale the quantization matrices in the JFIF header. - // Note that values are clipped to a max of 255. - if ( qfactor != 100 ) - { - for ( int i = 44; i < 108; ++i ) - { - int t = ( newHeader[i] * qfactor ) / 100; - newHeader[i] = (byte) Math.max( t, 0xff ); - } - for ( int i = 109; i < 173; ++i ) - { - int t = ( newHeader[i] * qfactor ) / 100; - newHeader[i] = (byte) Math.max( t, 0xff ); - } - } - - // Write out buffer. - out.write( newHeader ); - } - - } diff --git a/src/Acme/JPM/Encoders/PpmEncoder.java b/src/Acme/JPM/Encoders/PpmEncoder.java deleted file mode 100644 index bb15382e..00000000 --- a/src/Acme/JPM/Encoders/PpmEncoder.java +++ /dev/null @@ -1,103 +0,0 @@ -// PpmEncoder - write out an image as a PPM -// -// Copyright (C)1996,1998 by Jef Poskanzer . 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 Acme.JPM.Encoders; - -import java.util.*; -import java.io.*; -import java.awt.Image; -import java.awt.image.*; - -/// Write out an image as a PPM. -//

-// Writes an image onto a specified OutputStream in the PPM file format. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see ToPpm - -public class PpmEncoder extends ImageEncoder - { - - /// Constructor. - // @param img The image to encode. - // @param out The stream to write the PPM to. - public PpmEncoder( Image img, OutputStream out ) throws IOException - { - super( img, out ); - } - - /// Constructor. - // @param prod The ImageProducer to encode. - // @param out The stream to write the PPM to. - public PpmEncoder( ImageProducer prod, OutputStream out ) throws IOException - { - super( prod, out ); - } - - - void encodeStart( int width, int height ) throws IOException - { - writeString( out, "P6\n" ); - writeString( out, width + " " + height + "\n" ); - writeString( out, "255\n" ); - } - - static void writeString( OutputStream out, String str ) throws IOException - { - byte[] buf = str.getBytes(); - out.write( buf ); - } - - void encodePixels( - int x, int y, int w, int h, int[] rgbPixels, int off, int scansize ) - throws IOException - { - byte[] ppmPixels = new byte[w * 3]; - for ( int row = 0; row < h; ++row ) - { - int rowOff = off + row * scansize; - for ( int col = 0; col < w; ++col ) - { - int i = rowOff + col; - int j = col * 3; - ppmPixels[j ] = (byte) ( ( rgbPixels[i] & 0xff0000 ) >> 16 ); - ppmPixels[j + 1] = (byte) ( ( rgbPixels[i] & 0x00ff00 ) >> 8 ); - ppmPixels[j + 2] = (byte) ( rgbPixels[i] & 0x0000ff ); - } - out.write( ppmPixels ); - } - } - - void encodeDone() throws IOException - { - // Nothing. - } - - } diff --git a/src/Acme/JPM/Filters/CompositeFilter.java b/src/Acme/JPM/Filters/CompositeFilter.java deleted file mode 100644 index 0ed59c1f..00000000 --- a/src/Acme/JPM/Filters/CompositeFilter.java +++ /dev/null @@ -1,106 +0,0 @@ -// CompositeFilter - compose two filters into one -// -// Copyright (C) 1997 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; -import java.util.*; - -/// Compose two filters into one. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class CompositeFilter extends ImageFilterPlus - { - - private ImageFilterPlus filterOne, filterTwo; - private ImageFilter instanceOne, instanceTwo; - - /// Constructor. Builds a filter chain with a FilteredImageSource as - // the glue. - public CompositeFilter( ImageProducer producer, ImageFilterPlus filterOne, ImageFilterPlus filterTwo ) - { - super( producer ); - this.filterOne = filterOne; - this.filterTwo = filterTwo; - - filterOne.setSource( producer ); - ImageProducer producerOne = - new FilteredImageSource( producer, filterOne ); - filterTwo.setSource( producerOne ); - } - - public ImageFilter getFilterInstance( ImageConsumer consumer ) - { - CompositeFilter instance = (CompositeFilter) clone(); - instance.instanceTwo = filterTwo.getFilterInstance( consumer ); - instance.instanceOne = filterOne.getFilterInstance( instanceTwo ); - return (ImageFilter) instance; - } - - - // The rest of the methods just delegate to instanceOne. - - public void setColorModel( ColorModel model ) - { - instanceOne.setColorModel( model ); - } - - public void setDimensions( int width, int height ) - { - instanceOne.setDimensions( width, height ); - } - - public void setHints( int hintflags ) - { - instanceOne.setHints( hintflags ); - } - - public void setProperties( Hashtable props ) - { - instanceOne.setProperties( props ); - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, byte[] pixels, int off, int scansize ) - { - instanceOne.setPixels( x, y, w, h, model, pixels, off, scansize ); - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize ) - { - instanceOne.setPixels( x, y, w, h, model, pixels, off, scansize ); - } - - public void imageComplete( int status ) - { - //super.imageComplete( status ); - instanceOne.imageComplete( status ); - } - - } diff --git a/src/Acme/JPM/Filters/EdgeDetect.java b/src/Acme/JPM/Filters/EdgeDetect.java deleted file mode 100644 index f5758b07..00000000 --- a/src/Acme/JPM/Filters/EdgeDetect.java +++ /dev/null @@ -1,169 +0,0 @@ -// EdgeDetect - edge-detection filter -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.io.*; -import java.awt.image.*; -import Acme.JPM.Decoders.*; -import Acme.JPM.Encoders.*; - -/// Edge-detection filter. -// -// -//

-// Outlines the edges of an image. -// The edge detection technique used is to take the Pythagorean sum of -// two Sobel gradient operators at 90 degrees to each other, separately -// for each color component. -// For more details see "Digital Image Processing" by Gonzalez and Wintz, -// chapter 7. -//

-// This filter is slow. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class EdgeDetect extends RGBAllFilter - { - - // Constructor. - public EdgeDetect( ImageProducer producer ) - { - super( producer ); - } - - - private static final double SCALE = 1.8D; - - public void filterRGBAll( int width, int height, int[][] rgbPixels ) - { - int[][] newPixels = new int[height][width]; - long sum1, sum2; - double sum; - int r, g, b; - - // First and last rows are black. - for ( int col = 0; col < width; ++col ) - { - newPixels[0][col] = 0xff000000; - newPixels[height - 1][col] = 0xff000000; - } - for ( int row = 1; row < height - 1; ++row ) - { - // First and last columns are black too. - newPixels[row][0] = 0xff000000; - newPixels[row][width - 1] = 0xff000000; - // The real pixels. - for ( int col = 1; col < width - 1; ++col ) - { - sum1 = - rgbModel.getRed( rgbPixels[row - 1][col + 1] ) - - rgbModel.getRed( rgbPixels[row - 1][col - 1] ) + - 2 * ( - rgbModel.getRed( rgbPixels[row][col + 1] ) - - rgbModel.getRed( rgbPixels[row][col - 1] ) ) + - rgbModel.getRed( rgbPixels[row + 1][col + 1] ) - - rgbModel.getRed( rgbPixels[row + 1][col - 1] ); - sum2 = ( - rgbModel.getRed( rgbPixels[row + 1][col - 1] ) + - 2 * rgbModel.getRed( rgbPixels[row + 1][col] ) + - rgbModel.getRed( rgbPixels[row + 1][col + 1] ) - ) - ( - rgbModel.getRed( rgbPixels[row - 1][col - 1] ) + - 2 * rgbModel.getRed( rgbPixels[row - 1][col] ) + - rgbModel.getRed( rgbPixels[row - 1][col + 1] ) - ); - sum = Math.sqrt( (double) ( sum1*sum1 + sum2*sum2 ) ) / SCALE; - r = Math.min( (int) sum, 255 ); - - sum1 = - rgbModel.getGreen( rgbPixels[row - 1][col + 1] ) - - rgbModel.getGreen( rgbPixels[row - 1][col - 1] ) + - 2 * ( - rgbModel.getGreen( rgbPixels[row][col + 1] ) - - rgbModel.getGreen( rgbPixels[row][col - 1] ) ) + - rgbModel.getGreen( rgbPixels[row + 1][col + 1] ) - - rgbModel.getGreen( rgbPixels[row + 1][col - 1] ); - sum2 = ( - rgbModel.getGreen( rgbPixels[row + 1][col - 1] ) + - 2 * rgbModel.getGreen( rgbPixels[row + 1][col] ) + - rgbModel.getGreen( rgbPixels[row + 1][col + 1] ) - ) - ( - rgbModel.getGreen( rgbPixels[row - 1][col - 1] ) + - 2 * rgbModel.getGreen( rgbPixels[row - 1][col] ) + - rgbModel.getGreen( rgbPixels[row - 1][col + 1] ) - ); - sum = Math.sqrt( (double) ( sum1*sum1 + sum2*sum2 ) ) / SCALE; - g = Math.min( (int) sum, 255 ); - - sum1 = - rgbModel.getBlue( rgbPixels[row - 1][col + 1] ) - - rgbModel.getBlue( rgbPixels[row - 1][col - 1] ) + - 2 * ( - rgbModel.getBlue( rgbPixels[row][col + 1] ) - - rgbModel.getBlue( rgbPixels[row][col - 1] ) ) + - rgbModel.getBlue( rgbPixels[row + 1][col + 1] ) - - rgbModel.getBlue( rgbPixels[row + 1][col - 1] ); - sum2 = ( - rgbModel.getBlue( rgbPixels[row + 1][col - 1] ) + - 2 * rgbModel.getBlue( rgbPixels[row + 1][col] ) + - rgbModel.getBlue( rgbPixels[row + 1][col + 1] ) - ) - ( - rgbModel.getBlue( rgbPixels[row - 1][col - 1] ) + - 2 * rgbModel.getBlue( rgbPixels[row - 1][col] ) + - rgbModel.getBlue( rgbPixels[row - 1][col + 1] ) - ); - sum = Math.sqrt( (double) ( sum1*sum1 + sum2*sum2 ) ) / SCALE; - b = Math.min( (int) sum, 255 ); - - newPixels[row][col] = - 0xff000000 | ( r << 16 ) | ( g << 8 ) | b; - } - } - setPixels( width, height, newPixels ); - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - if ( args.length != 0 ) - usage(); - ImageFilterPlus filter = new EdgeDetect( null ); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: EdgeDetect" ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/Filters/Enlarge.java b/src/Acme/JPM/Filters/Enlarge.java deleted file mode 100644 index e090b2bd..00000000 --- a/src/Acme/JPM/Filters/Enlarge.java +++ /dev/null @@ -1,140 +0,0 @@ -// Enlarge - an ImageFilter that enlarges by pixel replication -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// An ImageFilter that enlarges by pixel replication. -//

-// Enlarges an image an integral factor by replicating pixels. -// The output uses the same color model as the input. -// This filter is very fast. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see Shrink -// @see ScaleCopy - -public class Enlarge extends ImageFilterPlus - { - - private int multiplier; - private int newWidth, newHeight; - - /// Constructor. - public Enlarge( ImageProducer producer, int multiplier ) - { - super( producer ); - this.multiplier = multiplier; - } - - - public void setDimensions( int width, int height ) - { - newWidth = width * multiplier; - newHeight = height * multiplier; - consumer.setDimensions( newWidth, newHeight ); - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, byte[] pixels, int off, int scansize ) - { - int newX = Math.min( x * multiplier, newWidth - 1 ); - int newY = Math.min( y * multiplier, newHeight - 1 ); - int newW = w * multiplier; - if ( newX + newW > newWidth ) - newW = newWidth - newX; - int newH = h * multiplier; - if ( newY + newH > newHeight ) - newH = newHeight - newY; - byte[] newPixels = new byte[newW * newH]; - for ( int row = 0; row < h; ++row ) - { - for ( int col = 0; col < w; ++col ) - { - byte pixel = pixels[row * scansize + off + col]; - for ( int i = 0; i < multiplier; ++i ) - for ( int j = 0; j < multiplier; ++j ) - { - int newRow = row * multiplier + i; - int newCol = col * multiplier + j; - newPixels[newRow * newW + newCol] = pixel; - } - } - } - consumer.setPixels( newX, newY, newW, newH, model, newPixels, 0, newW ); - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize ) - { - int newX = Math.min( x * multiplier, newWidth - 1 ); - int newY = Math.min( y * multiplier, newHeight - 1 ); - int newW = w * multiplier; - if ( newX + newW > newWidth ) - newW = newWidth - newX; - int newH = h * multiplier; - if ( newY + newH > newHeight ) - newH = newHeight - newY; - int[] newPixels = new int[newW * newH]; - for ( int row = 0; row < h; ++row ) - { - for ( int col = 0; col < w; ++col ) - { - int pixel = pixels[row * scansize + off + col]; - for ( int i = 0; i < multiplier; ++i ) - for ( int j = 0; j < multiplier; ++j ) - { - int newRow = row * multiplier + i; - int newCol = col * multiplier + j; - newPixels[newRow * newW + newCol] = pixel; - } - } - } - consumer.setPixels( newX, newY, newW, newH, model, newPixels, 0, newW ); - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - if ( args.length != 1 ) - usage(); - ImageFilterPlus filter = - new Enlarge( null, Integer.parseInt( args[0] ) ); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: Enlarge " ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/Filters/Flip.java b/src/Acme/JPM/Filters/Flip.java deleted file mode 100644 index 25c25b6c..00000000 --- a/src/Acme/JPM/Filters/Flip.java +++ /dev/null @@ -1,295 +0,0 @@ -// Flip - an ImageFilter that flips or rotates the image -// -// Copyright (C) 1997 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// An ImageFilter that flips or rotates the image. -//

-// Flips the image left-right, top-bottom, rotates clockwise or -// counter-clockwise, or otherwise munges the image as specified. -// This filter is fast. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class Flip extends ImageFilterPlus - { - - /// The null transformation. - public static final int FLIP_NULL = 0; - - /// Flip left to right. - public static final int FLIP_LR = 1; - - /// Flip top to bottom. - public static final int FLIP_TB = 2; - - /// Transpose X and Y - reflection along a diagonal. - public static final int FLIP_XY = 3; - - /// Rotate clockwise 90 degrees. - public static final int FLIP_CW = 4; - - /// Rotate counter-clockwise 90 degrees. - public static final int FLIP_CCW = 5; - - /// Rotate 180 degrees. - public static final int FLIP_R180 = 6; - - private int flipType; - private int width, height; - private int newWidth, newHeight; - - /// Constructor. - public Flip( ImageProducer producer, int flipType ) - { - super( producer, true ); - this.flipType = flipType; - } - - - public void setDimensions( int width, int height ) - { - this.width = width; - this.height = height; - switch ( flipType ) - { - case FLIP_NULL: - case FLIP_LR: - case FLIP_TB: - case FLIP_R180: - newWidth = width; - newHeight = height; - break; - case FLIP_XY: - case FLIP_CW: - case FLIP_CCW: - newWidth = height; - newHeight = width; - break; - } - consumer.setDimensions( newWidth, newHeight ); - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, byte[] pixels, int off, int scansize ) - { - int newX = x; - int newY = y; - int newW = w; - int newH = h; - switch ( flipType ) - { - case FLIP_NULL: - break; - case FLIP_LR: - newX = width - ( x + w ); - break; - case FLIP_TB: - newY = height - ( y + h ); - break; - case FLIP_XY: - newW = h; - newH = w; - newX = y; - newY = x; - break; - case FLIP_CW: - newW = h; - newH = w; - newX = height - ( y + h ); - newY = x; - break; - case FLIP_CCW: - newW = h; - newH = w; - newX = y; - newY = width - ( x + w ); - break; - case FLIP_R180: - newX = width - ( x + w ); - newY = height - ( y + h ); - break; - } - byte[] newPixels = new byte[newW * newH]; - for ( int row = 0; row < h; ++row ) - { - for ( int col = 0; col < w; ++col ) - { - int index = row * scansize + off + col; - int newRow = row; - int newCol = col; - switch ( flipType ) - { - case FLIP_NULL: - break; - case FLIP_LR: - newCol = w - col - 1; - break; - case FLIP_TB: - newRow = h - row - 1; - break; - case FLIP_XY: - newRow = col; - newCol = row; - break; - case FLIP_CW: - newRow = col; - newCol = h - row - 1;; - break; - case FLIP_CCW: - newRow = w - col - 1; - newCol = row; - break; - case FLIP_R180: - newRow = h - row - 1; - newCol = w - col - 1; - break; - } - int newIndex = newRow * newW + newCol; - newPixels[newIndex] = pixels[index]; - } - } - consumer.setPixels( newX, newY, newW, newH, model, newPixels, 0, newW ); - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize ) - { - int newX = x; - int newY = y; - int newW = w; - int newH = h; - switch ( flipType ) - { - case FLIP_NULL: - break; - case FLIP_LR: - newX = width - ( x + w ); - break; - case FLIP_TB: - newY = height - ( y + h ); - break; - case FLIP_XY: - newW = h; - newH = w; - newX = y; - newY = x; - break; - case FLIP_CW: - newW = h; - newH = w; - newX = height - ( y + h ); - newY = x; - break; - case FLIP_CCW: - newW = h; - newH = w; - newX = y; - newY = width - ( x + w ); - break; - case FLIP_R180: - newX = width - ( x + w ); - newY = height - ( y + h ); - break; - } - int[] newPixels = new int[newW * newH]; - for ( int row = 0; row < h; ++row ) - { - for ( int col = 0; col < w; ++col ) - { - int index = row * scansize + off + col; - int newRow = row; - int newCol = col; - switch ( flipType ) - { - case FLIP_NULL: - break; - case FLIP_LR: - newCol = w - col - 1; - break; - case FLIP_TB: - newRow = h - row - 1; - break; - case FLIP_XY: - newRow = col; - newCol = row; - break; - case FLIP_CW: - newRow = col; - newCol = h - row - 1;; - break; - case FLIP_CCW: - newRow = w - col - 1; - newCol = row; - break; - case FLIP_R180: - newRow = h - row - 1; - newCol = w - col - 1; - break; - } - int newIndex = newRow * newW + newCol; - newPixels[newIndex] = pixels[index]; - } - } - consumer.setPixels( newX, newY, newW, newH, model, newPixels, 0, newW ); - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - if ( args.length != 1 ) - usage(); - int flipType = FLIP_NULL; - if ( args[0].equalsIgnoreCase( "-lr" ) ) - flipType = FLIP_LR; - else if ( args[0].equalsIgnoreCase( "-tb" ) ) - flipType = FLIP_TB; - else if ( args[0].equalsIgnoreCase( "-xy" ) ) - flipType = FLIP_XY; - else if ( args[0].equalsIgnoreCase( "-cw" ) ) - flipType = FLIP_CW; - else if ( args[0].equalsIgnoreCase( "-ccw" ) ) - flipType = FLIP_CCW; - else if ( args[0].equalsIgnoreCase( "-r180" ) ) - flipType = FLIP_R180; - else - usage(); - ImageFilterPlus filter = new Flip( null, flipType ); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: Flip -lr|-tb|-xy|-cw|-ccw|-r180" ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/Filters/Gamma.java b/src/Acme/JPM/Filters/Gamma.java deleted file mode 100644 index 765c7fd7..00000000 --- a/src/Acme/JPM/Filters/Gamma.java +++ /dev/null @@ -1,148 +0,0 @@ -// Gamma - gamma-correction filter -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// Gamma-correction filter. -//

-// Gamma correction fixes a form of color distortion common to many monitors. -// Values less than 1.0 darken the image, and greater than 1.0 lighten it. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class Gamma extends RGBBlockFilter - { - - private double rValue, gValue, bValue; - - /// Constructor, single exponent. - public Gamma( ImageProducer producer, double value ) - { - this( producer, value, value, value ); - } - - /// Constructor, different exponents for R G and B. - public Gamma( ImageProducer producer, double rValue, double gValue, double bValue ) - { - super( producer ); - this.rValue = rValue; - this.gValue = gValue; - this.bValue = bValue; - } - - - private int[] rTable, gTable, bTable; - - public int[][] filterRGBBlock( int x, int y, int width, int height, int[][] rgbPixels ) - { - initialize(); - for ( int row = 0; row < height; ++row ) - for ( int col = 0; col < width; ++col ) - { - int rgb = rgbPixels[row][col]; - int a = ( rgb >> 24 ) & 0xff; - int r = ( rgb >> 16 ) & 0xff; - int g = ( rgb >> 8 ) & 0xff; - int b = rgb & 0xff; - r = rTable[r]; - g = gTable[g]; - b = bTable[b]; - rgbPixels[row][col] = - ( a << 24 ) | ( r << 16 ) | ( g << 8 ) | b; - } - return rgbPixels; - } - - - private boolean initialized = false; - - private void initialize() - { - if ( initialized ) - return; - initialized = true; - - rTable = buildTable( rValue ); - - if ( gValue == rValue ) - gTable = rTable; - else - gTable = buildTable( gValue ); - - if ( bValue == rValue ) - bTable = rTable; - else if ( bValue == gValue ) - bTable = gTable; - else - bTable = buildTable( bValue ); - } - - private int[] buildTable( double gamma ) - { - int[] table = new int[256]; - double oneOverGamma = 1.0D / gamma; - for ( int i = 0; i < 256; ++i ) - { - int v = (int) ( - ( 255.0D * Math.pow( i / 255.0D, oneOverGamma ) ) + 0.5D ); - if ( v > 255 ) - v = 255; - table[i] = v; - } - return table; - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - ImageFilterPlus filter = null; - if ( args.length == 1 ) - filter = new Gamma( null, Double.valueOf( args[0] ).doubleValue() ); - else if ( args.length == 3 ) - filter = new Gamma( null, - Double.valueOf( args[0] ).doubleValue(), - Double.valueOf( args[1] ).doubleValue(), - Double.valueOf( args[2] ).doubleValue() ); - else - usage(); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: Gamma " ); - System.err.println( "or: Gamma " ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/Filters/ImageFilterPlus.java b/src/Acme/JPM/Filters/ImageFilterPlus.java deleted file mode 100644 index 7c36b8d9..00000000 --- a/src/Acme/JPM/Filters/ImageFilterPlus.java +++ /dev/null @@ -1,160 +0,0 @@ -// ImageFilterPlus - an ImageFilter with some extra features and bug fixes -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; -import java.io.*; -import Acme.JPM.Decoders.*; -import Acme.JPM.Encoders.*; - -/// An ImageFilter with some extra features and bug fixes. -//

-// You can use an image filter to turn one Image into another via -// a FilteredImageSource, e.g.: -//

-// Image newImage = comp.createImage( new FilteredImageSource(
-//     oldImage.getSource(), new SomeFilter( oldImage.getSource() ) ) );
-// 
-// Or use the convenient utility JPMUtils.filterImage(): -//
-// Image newImage = JPMUtils.filterImage(
-//     comp, SomeFilter( oldImage.getSource() ) );
-// 
-//

-// You can also use image filters from the command line, reading PPM -// from stdin and writing PPM to stdout, if you add code like the following -// to each filter: -//

-// System.exit( 
-//     ImageFilterPlus.filterStream(
-//         System.in, System.out,
-//         new SomeFilter( null ) ) );
-// 
-//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class ImageFilterPlus extends ImageFilter - { - - private ImageProducer producer; - private boolean pixelOrderChanges; - - /// Constructor. - // @param producer The ImageProducer is required, so that we can - // remove ourself from its consumers list when we're done. - // However, if you don't have the producer available when you want - // to create the filter, you can pass in null and set it later - // via setSource(). - public ImageFilterPlus( ImageProducer producer ) - { - this( producer, false ); - } - - /// Constructor, with pixel order change. - // @param producer The ImageProducer is required, so that we can - // remove ourself from its consumers list when we're done. - // However, if you don't have the producer available when you want - // to create the filter, you can pass in null and set it later - // via setSource(). - // @param pixelOrderChanges If the filter may output pixels in a different - // order from the one they were delivered in, this flag must be set. - public ImageFilterPlus( ImageProducer producer, boolean pixelOrderChanges ) - { - setSource( producer ); - this.pixelOrderChanges = pixelOrderChanges; - } - - - /// The default color model - useful for comparisons. - public static final ColorModel rgbModel = ColorModel.getRGBdefault(); - - - /// Return the ImageProducer for this filter. - public ImageProducer getSource() - { - return producer; - } - - /// Set the ImageProducer for this filter, if it wasn't set by the - // constructor. - public void setSource( ImageProducer producer ) - { - this.producer = producer; - } - - - /// Set the hint flags. If the pixel order may change, we have to - // turn off the TOPDOWNLEFTRIGHT flag; otherwise the flags are passed - // through unmodified. - public void setHints( int hintflags ) - { - if ( pixelOrderChanges ) - hintflags &= ~TOPDOWNLEFTRIGHT; - consumer.setHints( hintflags ); - } - - - /// This routine fixes a bug in java.awt.image.ImageFilter. All - // ImageConsumers are required remove themselves from the producer's - // list when they're done reading. If they don't do this then some - // producers will generate an error. The standard ImageFilter class - // fails to do this, but this one does it. - public void imageComplete( int status ) - { - if ( status != ImageConsumer.SINGLEFRAMEDONE ) - producer.removeConsumer( this ); - super.imageComplete( status ); - } - - - /// Filter a PPM InputStream to a PPM OutputStream. - //

- // Create the filter with a null producer, and this routine will - // fill it in for you. - // @return a status code suitable for use with System.exit(). - public static int filterStream( InputStream in, OutputStream out, ImageFilterPlus filter ) - { - ImageDecoder producer = new PpmDecoder( in ); - filter.setSource( producer ); - try - { - ImageEncoder consumer = new PpmEncoder( - new FilteredImageSource( producer, filter ), out ); - consumer.encode(); - } - catch ( IOException e ) - { - System.err.println( e.toString() ); - return 1; - } - return 0; - } - - } diff --git a/src/Acme/JPM/Filters/Invert.java b/src/Acme/JPM/Filters/Invert.java deleted file mode 100644 index c4d65b32..00000000 --- a/src/Acme/JPM/Filters/Invert.java +++ /dev/null @@ -1,83 +0,0 @@ -// Invert - color-inversion filter -// -// Copyright (C) 1997 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// Color-inversion filter. -//

-// Switches black for white, and all the other colors too. -// This filter is very fast. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class Invert extends RGBBlockFilter - { - - /// Constructor. - public Invert( ImageProducer producer ) - { - super( producer ); - } - - - public int[][] filterRGBBlock( int x, int y, int width, int height, int[][] rgbPixels ) - { - for ( int row = 0; row < height; ++row ) - for ( int col = 0; col < width; ++col ) - { - int rgb = rgbPixels[row][col]; - int alpha = rgb & 0xff000000; - int rest = ( ~ rgb ) & 0x00ffffff; - rgbPixels[row][col] = alpha | rest; - } - return rgbPixels; - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - ImageFilterPlus filter = null; - if ( args.length == 0 ) - filter = new Invert( null ); - else - usage(); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: Invert" ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/Filters/Margin.java b/src/Acme/JPM/Filters/Margin.java deleted file mode 100644 index 5375bb54..00000000 --- a/src/Acme/JPM/Filters/Margin.java +++ /dev/null @@ -1,133 +0,0 @@ -// Margin - an ImageFilter that adds a margin to an image -// -// Copyright (C) 1997 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.*; -import java.awt.image.*; - -/// An ImageFilter that adds a margin to an image. -//

-// Adds a margin of a specified color and width around an image. -// The output uses the same color model as the input. -// This filter is very fast. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class Margin extends ImageFilterPlus - { - - private Color color; - private int size; - private int width, height; - private int newWidth; - - /// Constructor. - public Margin( ImageProducer producer, Color color, int size ) - { - super( producer, true ); - this.color = color; - this.size = size; - } - - - public void setDimensions( int width, int height ) - { - this.width = width; - this.height = height; - newWidth = width + size * 2; - consumer.setDimensions( newWidth, height + size * 2 ); - } - - private boolean started = false; - - private void start() - { - started = true; - int rgb = color.getRGB(); - - int[] fullRow = new int[newWidth]; - for ( int col = 0; col < newWidth; ++col ) - fullRow[col] = rgb; - for ( int row = 0; row < size; ++row ) - { - consumer.setPixels( - 0, row, newWidth, 1, rgbModel, fullRow, 0, newWidth ); - consumer.setPixels( - 0, size + height + row, newWidth, 1, rgbModel, fullRow, 0, - newWidth ); - } - - int[] sideRow = new int[size]; - for ( int col = 0; col < size; ++col ) - sideRow[col] = rgb; - for ( int row = 0; row < height; ++row ) - { - consumer.setPixels( - 0, size + row, size, 1, rgbModel, sideRow, 0, size ); - consumer.setPixels( - size + width, size + row, size, 1, rgbModel, sideRow, 0, size ); - } - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, byte[] pixels, int off, int scansize ) - { - if ( ! started ) - start(); - consumer.setPixels( - x + size, y + size, w, h, model, pixels, off, scansize ); - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize ) - { - if ( ! started ) - start(); - consumer.setPixels( - x + size, y + size, w, h, model, pixels, off, scansize ); - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - if ( args.length != 1 ) - usage(); - ImageFilterPlus filter = - new Margin( null, Color.black, Integer.parseInt( args[0] ) ); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: Margin " ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/Filters/Oil.java b/src/Acme/JPM/Filters/Oil.java deleted file mode 100644 index cd39df9e..00000000 --- a/src/Acme/JPM/Filters/Oil.java +++ /dev/null @@ -1,141 +0,0 @@ -// Oil - oil-transfer filter -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// Oil-transfer filter. -// -// -//

-// The oil transfer is described in "Beyond Photography" by Holzmann, -// chapter 4, photo 7. -// It's a sort of localized smearing. -// The parameter controls the size of the smeared area, with a default of 3. -//

-// This filter is very slow. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class Oil extends RGBAllFilter - { - - private int n; - - /// Constructor. - public Oil( ImageProducer producer, int n ) - { - super( producer ); - this.n = n; - } - - /// Constructor, default value. - public Oil( ImageProducer producer ) - { - this( producer, 3 ); - } - - - public void filterRGBAll( int width, int height, int[][] rgbPixels ) - { - int[][] newPixels = new int[height][width]; - int[] rHist = new int[256]; - int[] gHist = new int[256]; - int[] bHist = new int[256]; - - for ( int row = 0; row < height; ++row ) - { - for ( int col = 0; col < width; ++col ) - { - for ( int i = 0; i < 256; ++i ) - rHist[i] = gHist[i] = bHist[i] =0; - for ( int drow = row - n; drow <= row + n; ++drow ) - if ( drow >= 0 && drow < height ) - for ( int dcol = col - n; dcol <= col + n; ++dcol ) - if ( dcol >= 0 && dcol < width ) - { - int rgb = rgbPixels[drow][dcol]; - rHist[( rgb >> 16 ) & 0xff]++; - gHist[( rgb >> 8 ) & 0xff]++; - bHist[rgb & 0xff]++; - } - int r = 0, g = 0, b = 0; - for ( int i = 1; i < 256; ++i ) - { - if ( rHist[i] > rHist[r] ) - r = i; - if ( gHist[i] > gHist[g] ) - g = i; - if ( bHist[i] > bHist[b] ) - b = i; - } - newPixels[row][col] = - 0xff000000 | ( r << 16 ) | ( g << 8 ) | b; - } - } - setPixels( width, height, newPixels ); - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - int n = -1; - int argc = args.length; - int argn; - for ( argn = 0; argn < argc && args[argn].charAt( 0 ) == '-'; ++argn ) - { - if ( args[argn].equals( "-n" ) && argn + 1 < argc ) - { - ++argn; - n = Integer.parseInt( args[argn] ); - } - else - usage(); - } - if ( argn != argc ) - usage(); - - ImageFilterPlus filter; - if ( n == -1 ) - filter = new Oil( null ); - else - filter = new Oil( null, n ); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: Oil [-n N]" ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/Filters/RGBAllFilter.java b/src/Acme/JPM/Filters/RGBAllFilter.java deleted file mode 100644 index b9da544f..00000000 --- a/src/Acme/JPM/Filters/RGBAllFilter.java +++ /dev/null @@ -1,170 +0,0 @@ -// RGBAllFilter - an ImageFilter that grabs the whole image -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// An ImageFilter that grabs the whole image. -//

-// Many image filters need to work on the whole image at once. -// This class collects up the image and hands it to a single -// routine for processing. -//

-// Also, because Java's image classes allow each setPixels() call to -// use a different color model, we have to convert all pixels into -// the default RGB model. -//

-// Here's a sample RGBAllFilter that smooths an image by averaging -// nine adjacent pixels. -//

-// class SmoothFilter extends RGBAllFilter
-//     {
-//     public void filterRGBAll( int width, int height, int[][] rgbPixels )
-//         {
-//         int[][] newPixels = new int[height][width];
-//         for ( int row = 0; row < height; ++row )
-//             for ( int col = 0; col < width; ++col )
-//                 {
-//                 int a = 0, r = 0, g = 0, b = 0, c = 0;
-//                 for ( int subrow = row - 1; subrow <= row + 1; ++subrow )
-//                     if ( subrow >= 0 && subrow < height )
-//                         for ( int subcol = col - 1; subcol <= col + 1; ++subcol )
-//                             if ( subcol >= 0 && subcol < width )
-//                                 {
-//                                 int pixel = rgbPixels[subrow][subcol];
-//                                 a += rgbModel.getAlpha( pixel );
-//                                 r += rgbModel.getRed( pixel );
-//                                 g += rgbModel.getGreen( pixel );
-//                                 b += rgbModel.getBlue( pixel );
-//                                 ++c;
-//                                 }
-//                 a /= c;
-//                 r /= c;
-//                 g /= c;
-//                 b /= c;
-//                 newPixels[row][col] =
-//                     ( a << 24 ) | ( r << 16 ) | ( g << 8 ) | b;
-//                 }
-//         setPixels( width, height, newPixels );
-//         }
-//     }
-// 
-//

-// Fetch the software.
-// Fetch the entire Acme package. - -public abstract class RGBAllFilter extends ImageFilterPlus - { - - private int width = -1, height = -1; - private int[][] rgbPixels = null; - - public RGBAllFilter( ImageProducer producer ) - { - super( producer ); - } - - - /// This is the routine that subclasses must implement. - // It gets the entire image as an int[height][width] in the default - // RGB color model. It should call setPixels() with a filtered array, - // same color model. - public abstract void filterRGBAll( int width, int height, int[][] rgbPixels ); - - - /// The version of setPixels() that gets called by the subclass. - public void setPixels( int newWidth, int newHeight, int[][] newPixels ) - { - // Send it on to the consumer. - consumer.setDimensions( newWidth, newHeight ); - for ( int row = 0; row < newHeight; ++row ) - consumer.setPixels( - 0, row, newWidth, 1, rgbModel, newPixels[row], 0, newWidth ); - - } - - - public void setColorModel( ColorModel model ) - { - consumer.setColorModel( rgbModel ); - } - - public void setDimensions( int width, int height ) - { - if ( width == this.width && height == this.height ) - return; - this.width = width; - this.height = height; - rgbPixels = new int[height][width]; - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, byte[] pixels, int off, int scansize ) - { - for ( int row = 0; row < h; ++row ) - { - int rowOffsetIn = row * scansize + off; - for ( int col = 0; col < w; ++col ) - rgbPixels[y + row][x + col] = - model.getRGB( pixels[rowOffsetIn + col] & 0xff ); - } - } - - - public void setPixels( int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize ) - { - for ( int row = 0; row < h; ++row ) - { - int rowOffsetIn = row * scansize + off; - if ( model == rgbModel ) - System.arraycopy( - pixels, rowOffsetIn, rgbPixels[y + row], x, w ); - else - for ( int col = 0; col < w; ++col ) - rgbPixels[y + row][x + col] = - model.getRGB( pixels[rowOffsetIn + col] ); - } - } - - public void imageComplete( int status ) - { - if ( status == ImageConsumer.IMAGEERROR || - status == ImageConsumer.IMAGEABORTED ) - { - super.imageComplete( status ); - return; - } - - // Do the actual work. - filterRGBAll( width, height, rgbPixels ); - - // And we're done. - super.imageComplete( status ); - } - - } diff --git a/src/Acme/JPM/Filters/RGBBlockFilter.java b/src/Acme/JPM/Filters/RGBBlockFilter.java deleted file mode 100644 index 5fc60e07..00000000 --- a/src/Acme/JPM/Filters/RGBBlockFilter.java +++ /dev/null @@ -1,135 +0,0 @@ -// RGBBlockFilter - more efficient RGB ImageFilter -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// More efficient RGB ImageFilter. -//

-// Similar in concept to java.awt.image.RGBImageFilter, but designed -// to run more efficiently when filtering large images. -//

-// As with RGBImageFilter, you only have to implement a single routine -// to use the filter. However, RGBImageFilter's routine filters a single -// pixel at a time. This means a lot of routine-calling overhead. -// RGBBlockFilter filters a block at a time. -//

-// Here's a sample RGBBlockFilter that makes an image translucent -// by setting all the alpha values to 0x80: -//

-// class TranslucentFilter extends RGBBlockFilter
-//     {
-//     public int[] filterRGBBlock(
-//         int x, int y, int width, int height, int[][] rgbPixels )
-//         {
-//         for ( int row = 0; row < height; ++row )
-//             for ( int col = 0; col < width; ++col )
-//                 rgbPixels[row][col] =
-//                     ( rgbPixels[row][col] & 0x00ffffff ) | 0x80000000;
-//         return rgbPixels;
-//         }
-//     }
-// 
-//

-// Fetch the software.
-// Fetch the entire Acme package. - -public abstract class RGBBlockFilter extends ImageFilterPlus - { - - public RGBBlockFilter( ImageProducer producer ) - { - super( producer ); - } - - - /// This is the routine that subclasses must implement. - // It gets a block of the image as an int[height][width] in the default - // RGB color model. It should return a filtered array, same size - // and same model. - public abstract int[][] filterRGBBlock( - int x, int y, int width, int height, int[][] rgbPixels ); - - - public void setColorModel( ColorModel model ) - { - consumer.setColorModel( rgbModel ); - } - - /// Byte version of setPixels reformats the pixels to RGB and the - // array to 2 dimensions. - public void setPixels( - int x, int y, int width, int height, ColorModel model, - byte[] pixels, int offset, int scansize ) - { - int[][] rgbPixels = new int[height][width]; - for ( int row = 0; row < height; ++row ) - { - int rowOffsetIn = offset + row * scansize; - for ( int col = 0; col < width; ++col ) - rgbPixels[row][col] = - model.getRGB( pixels[rowOffsetIn + col] & 0xff ); - } - setPixels( x, y, width, height, rgbPixels ); - } - - /// Int version of setPixels reformats the array to 2 dimensions. - public void setPixels( - int x, int y, int width, int height, ColorModel model, - int[] pixels, int offset, int scansize ) - { - int[][] rgbPixels = new int[height][width]; - for ( int row = 0; row < height; ++row ) - { - int rowOffsetIn = offset + row * scansize; - int rowOffsetOut = row * width; - // Convert color models if necessary. - if ( model == rgbModel ) - System.arraycopy( - pixels, rowOffsetIn, rgbPixels[row], 0, width ); - else - for ( int col = 0; col < width; ++col ) - rgbPixels[row][col] = - model.getRGB( pixels[rowOffsetIn + col] ); - } - setPixels( x, y, width, height, rgbPixels ); - } - - /// Call the filter routine, and send the results to the consumer. - private void setPixels( int x, int y, int width, int height, int[][] rgbPixels ) - { - int[][] newPixels = filterRGBBlock( x, y, width, height, rgbPixels ); - - // And send it on to the consumer. - for ( int row = 0; row < height; ++row ) - consumer.setPixels( - x, y + row, width, 1, rgbModel, newPixels[row], 0, width ); - } - - } diff --git a/src/Acme/JPM/Filters/Rotate.java b/src/Acme/JPM/Filters/Rotate.java deleted file mode 100644 index 93d7fcc0..00000000 --- a/src/Acme/JPM/Filters/Rotate.java +++ /dev/null @@ -1,81 +0,0 @@ -// Rotate - rotate an image by some angle -// -// Copyright (C) 1997 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// Rotate an image by some angle. -//

-// Rotates an image by the specified angle. -// The angle is in degrees measured counter-clockwise. -// It can be negative, but it should be between -90 and 90 -// or the resulting image will be unreasonably large. -// Staying between -45 and 45 is best. -//

-// The rotation algorithm is Alan Paeth's three-shear method, described -// in "A Fast Algorithm for General Raster Rotation", Graphics Interface -// '86, pp. 77-81. -//

-// This filter is slow. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class Rotate extends CompositeFilter - { - - private double angle; - - /// Constructor. - public Rotate( ImageProducer producer, double angle ) - { - super( producer, new Shear( null, angle ), new Flip( null, Flip.FLIP_XY ) ); - this.angle = angle * Math.PI / 180.0; - double xshearfac = Math.tan( angle / 2.0 ); - double yshearfac = Math.sin( angle ); - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - if ( args.length != 1 ) - usage(); - ImageFilterPlus filter = new Rotate( null, Integer.parseInt( args[0] ) ); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: Rotate " ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/Filters/ScaleCopy.java b/src/Acme/JPM/Filters/ScaleCopy.java deleted file mode 100644 index 1c568e17..00000000 --- a/src/Acme/JPM/Filters/ScaleCopy.java +++ /dev/null @@ -1,159 +0,0 @@ -// ScaleCopy - an ImageFilter that scales by pixel copying -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// An ImageFilter that scales by pixel copying. -//

-// Scales an image by copying pixels. -// If the image is being enlarged, pixels get replicated; -// if the image is being shrunk, pixels get dropped. -// The output uses the same color model as the input. -// For enlarging, this filter is slightly slower than Enlarge due -// to the floating-point arithmetic; -// for shrinking, it's much faster than Shrink, but -// the results aren't as nice. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see Enlarge -// @see Shrink - -public class ScaleCopy extends ImageFilterPlus - { - - private double xScale, yScale; - private int newWidth, newHeight; - - /// Constructor, same X and Y scale factor. - public ScaleCopy( ImageProducer producer, double scale ) - { - this( producer, scale, scale ); - } - - /// Constructor, different X and Y scale factors. - public ScaleCopy( ImageProducer producer, double xScale, double yScale ) - { - super( producer ); - this.xScale = xScale; - this.yScale = yScale; - } - - - public void setDimensions( int width, int height ) - { - newWidth = (int) ( width * xScale ); - newHeight = (int) ( height * yScale ); - consumer.setDimensions( newWidth, newHeight ); - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, byte[] pixels, int off, int scansize ) - { - int newX = Math.min( (int) ( x * xScale ), newWidth - 1 ); - int newY = Math.min( (int) ( y * yScale ), newHeight - 1 ); - int newW = Math.max( (int) ( w * xScale ), 1 ); - if ( newX + newW > newWidth ) - newW = newWidth - newX; - int newH = Math.max( (int) ( h * yScale ), 1 ); - if ( newY + newH > newHeight ) - newH = newHeight - newY; - byte[] newPixels = new byte[newW * newH]; - for ( int newRow = 0; newRow < newH; ++newRow ) - { - int row = (int) ( newRow / yScale ); - if ( row >= h ) - continue; - for ( int newCol = 0; newCol < newW; ++newCol ) - { - int col = (int) ( newCol / xScale ); - if ( col >= w ) - continue; - newPixels[newRow * newW + newCol] = - pixels[row * scansize + off + col]; - } - } - consumer.setPixels( newX, newY, newW, newH, model, newPixels, 0, newW ); - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize ) - { - int newX = Math.min( (int) ( x * xScale ), newWidth - 1 ); - int newY = Math.min( (int) ( y * yScale ), newHeight - 1 ); - int newW = Math.max( (int) ( w * xScale ), 1 ); - if ( newX + newW > newWidth ) - newW = newWidth - newX; - int newH = Math.max( (int) ( h * yScale ), 1 ); - if ( newY + newH > newHeight ) - newH = newHeight - newY; - int[] newPixels = new int[newW * newH]; - for ( int newRow = 0; newRow < newH; ++newRow ) - { - int row = (int) ( newRow / yScale ); - if ( row >= h ) - continue; - for ( int newCol = 0; newCol < newW; ++newCol ) - { - int col = (int) ( newCol / xScale ); - if ( col >= w ) - continue; - newPixels[newRow * newW + newCol] = - pixels[row * scansize + off + col]; - } - } - consumer.setPixels( newX, newY, newW, newH, model, newPixels, 0, newW ); - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - ImageFilterPlus filter = null; - if ( args.length == 1 ) - filter = new ScaleCopy( null, - Double.valueOf( args[0] ).doubleValue() ); - else if ( args.length == 2 ) - filter = new ScaleCopy( null, - Double.valueOf( args[0] ).doubleValue(), - Double.valueOf( args[1] ).doubleValue() ); - else - usage(); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: ScaleCopy scale" ); - System.err.println( "or: ScaleCopy xScale yScale" ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/Filters/Shear.java b/src/Acme/JPM/Filters/Shear.java deleted file mode 100644 index 31bd2054..00000000 --- a/src/Acme/JPM/Filters/Shear.java +++ /dev/null @@ -1,144 +0,0 @@ -// Shear - shear an image by some angle -// -// Copyright (C) 1997 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// Shear an image by some angle. -//

-// Shears an image by the specified angle. -// The angle is in degrees (floating point), and measures this: -//


-// +-------+  +-------+
-// |       |  |\       \
-// |  OLD  |  | \  NEW  \
-// |       |  |an\       \
-// +-------+  |gle+-------+
-// 
-// If the angle is negative, it shears the other way: -//

-// +-------+  |-an+-------+
-// |       |  |gl/       /
-// |  OLD  |  |e/  NEW  /
-// |       |  |/       /
-// +-------+  +-------+
-// 
-// The angle should not get too close to 90 or -90, or the resulting -// image will be unreasonably wide. Staying between -45 and 45 is best. -//

-// The shearing is implemented by looping over the source pixels and -// distributing fractions to each of the destination pixels. -// This has an "anti-aliasing" effect - it avoids jagged edges and similar -// artifacts. -//

-// This filter is fast. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class Shear extends RGBAllFilter - { - - private double angle; - - /// Constructor. - public Shear( ImageProducer producer, double angle ) - { - super( producer ); - this.angle = angle * Math.PI / 180.0; - } - - - public void filterRGBAll( int width, int height, int[][] rgbPixels ) - { - double shearfac = Math.tan( angle ); - if ( shearfac < 0.0 ) - shearfac = -shearfac; - int newWidth = (int) ( height * shearfac + width + 0.999999 ); - int[][] newPixels = new int[height][newWidth]; - for ( int row = 0; row < height; ++row ) - { - double new0; - if ( angle > 0.0 ) - new0 = row * shearfac; - else - new0 = ( height - row ) * shearfac; - int intnew0 = (int) new0; - double fracnew0 = new0 - intnew0; - double omfracnew0 = 1.0 - fracnew0; - - for ( int col = 0; col < newWidth; ++col ) - newPixels[row][col] = 0x00000000; - - int preva = 0; - int prevr = ( rgbPixels[row][0] >> 16 ) & 0xff; - int prevg = ( rgbPixels[row][0] >> 8 ) & 0xff; - int prevb = rgbPixels[row][0] & 0xff; - for ( int col = 0; col < width; ++col ) - { - int rgb = rgbPixels[row][col]; - int a = ( rgb >> 24 ) & 0xff; - int r = ( rgb >> 16 ) & 0xff; - int g = ( rgb >> 8 ) & 0xff; - int b = rgb & 0xff; - newPixels[row][intnew0 + col] = - ( (int) ( fracnew0 * preva + omfracnew0 * a ) << 24 ) | - ( (int) ( fracnew0 * prevr + omfracnew0 * r ) << 16 ) | - ( (int) ( fracnew0 * prevg + omfracnew0 * g ) << 8 ) | - ( (int) ( fracnew0 * prevb + omfracnew0 * b ) ); - preva = a; - prevr = r; - prevg = g; - prevb = b; - } - newPixels[row][intnew0 + width] = - ( (int) ( fracnew0 * preva ) << 24 ) | - ( prevr << 16 ) | ( prevg << 8 ) | prevb; - } - setPixels( newWidth, height, newPixels ); - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - if ( args.length != 1 ) - usage(); - ImageFilterPlus filter = new Shear( null, Integer.parseInt( args[0] ) ); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: Shear " ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/Filters/Shrink.java b/src/Acme/JPM/Filters/Shrink.java deleted file mode 100644 index 4599cb1b..00000000 --- a/src/Acme/JPM/Filters/Shrink.java +++ /dev/null @@ -1,116 +0,0 @@ -// Shrink - an ImageFilter that shrinks by pixel averaging -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// An ImageFilter that shrinks by pixel averaging. -//

-// Shrinks an image an integral factor by averaging pixels. -// Because the resulting pixels might not fit into the input's -// color model, the output is always in the default RGB color model. -// This filter is somewhat slow. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see Enlarge -// @see ScaleCopy - -public class Shrink extends RGBAllFilter - { - - private int divisor; - - /// Constructor. - public Shrink( ImageProducer producer, int divisor ) - { - super( producer ); - this.divisor = divisor; - } - - - public void filterRGBAll( int width, int height, int[][] rgbPixels ) - { - int divisor2 = divisor * divisor; - int newWidth = Math.max( width / divisor, 1 ); - int newHeight = Math.max( height / divisor, 1 ); - int[][] newPixels = new int[newHeight][newWidth]; - for ( int newRow = 0; newRow < newHeight; ++newRow ) - { - for ( int newCol = 0; newCol < newWidth; ++newCol ) - { - int a = 0, r = 0, g = 0, b = 0; - for ( int i = 0; i < divisor; ++i ) - { - int row = newRow * divisor + i; - if ( row >= height ) - continue; - for ( int j = 0; j < divisor; ++j ) - { - int col = newCol * divisor + j; - if ( col >= width ) - continue; - int rgb = rgbPixels[row][col]; - a += ( rgb >> 24 ) & 0xff; - r += ( rgb >> 16 ) & 0xff; - g += ( rgb >> 8 ) & 0xff; - b += rgb & 0xff; - } - } - a /= divisor2; - r /= divisor2; - g /= divisor2; - b /= divisor2; - newPixels[newRow][newCol] = - ( a << 24 ) | ( r << 16 ) | ( g << 8 ) | b; - } - } - setPixels( newWidth, newHeight, newPixels ); - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - if ( args.length != 1 ) - usage(); - ImageFilterPlus filter = new Enlarge( - null, Integer.parseInt( args[0] ) ); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: Shrink " ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/Filters/Smooth.java b/src/Acme/JPM/Filters/Smooth.java deleted file mode 100644 index aadab230..00000000 --- a/src/Acme/JPM/Filters/Smooth.java +++ /dev/null @@ -1,123 +0,0 @@ -// Smooth - smoothing filter -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// Smoothing filter. -//

-// Smooths an image by averaging adjacent pixels. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class Smooth extends RGBAllFilter - { - - private int n; - - /// Constructor. - public Smooth( ImageProducer producer, int n ) - { - super( producer ); - this.n = n; - } - - /// Constructor, default value. - public Smooth( ImageProducer producer ) - { - this( producer, 1 ); - } - - - public void filterRGBAll( int width, int height, int[][] rgbPixels ) - { - int[][] newPixels = new int[height][width]; - for ( int row = 0; row < height; ++row ) - for ( int col = 0; col < width; ++col ) - { - int a = 0, r = 0, g = 0, b = 0, c = 0; - for ( int subrow = row - n; subrow <= row + n; ++subrow ) - if ( subrow >= 0 && subrow < height ) - for ( int subcol = col - n; subcol <= col + n; ++subcol ) - if ( subcol >= 0 && subcol < width ) - { - int rgb = rgbPixels[subrow][subcol]; - a += ( rgb >> 24 ) & 0xff; - r += ( rgb >> 16 ) & 0xff; - g += ( rgb >> 8 ) & 0xff; - b += rgb & 0xff; - ++c; - } - a /= c; - r /= c; - g /= c; - b /= c; - newPixels[row][col] = - ( a << 24 ) | ( r << 16 ) | ( g << 8 ) | b; - } - setPixels( width, height, newPixels ); - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - int n = -1; - int argc = args.length; - int argn; - for ( argn = 0; argn < argc && args[argn].charAt( 0 ) == '-'; ++argn ) - { - if ( args[argn].equals( "-n" ) && argn + 1 < argc ) - { - ++argn; - n = Integer.parseInt( args[argn] ); - } - else - usage(); - } - if ( argn != argc ) - usage(); - - ImageFilterPlus filter; - if ( n == -1 ) - filter = new Smooth( null ); - else - filter = new Smooth( null, n ); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: Smooth [-n N]" ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/Filters/Tile.java b/src/Acme/JPM/Filters/Tile.java deleted file mode 100644 index 1d374d15..00000000 --- a/src/Acme/JPM/Filters/Tile.java +++ /dev/null @@ -1,126 +0,0 @@ -// Tile - an ImageFilter that replicates an image in a tiled pattern -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM.Filters; - -import java.awt.image.*; - -/// An ImageFilter that replicates an image in a tiled pattern. -//

-// Tiles the image onto an output image of a specified size. -// The output uses the same color model as the input. -// This filter is very fast. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class Tile extends ImageFilterPlus - { - - private int width, height; - private int newWidth, newHeight; - private int nWide, nHigh; - - /// Constructor. - public Tile( ImageProducer producer, int newWidth, int newHeight ) - { - super( producer, true ); - this.newWidth = newWidth; - this.newHeight = newHeight; - } - - - public void setDimensions( int width, int height ) - { - this.width = width; - this.height = height; - consumer.setDimensions( newWidth, newHeight ); - nWide = ( newWidth + width - 1 ) / width; - nHigh = ( newHeight + height - 1 ) / height; - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, byte[] pixels, int off, int scansize ) - { - for ( int r = 0; r < nHigh; ++r ) - { - int ty = r * height + y; - int th = h; - if ( ty + th > newHeight ) - th = newHeight - ty; - for ( int c = 0; c < nWide; ++c ) - { - int tx = c * width + x; - int tw = w; - if ( tx + tw > newWidth ) - tw = newWidth - tx; - consumer.setPixels( - tx, ty, tw, th, model, pixels, off, scansize ); - } - } - } - - public void setPixels( int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize ) - { - for ( int r = 0; r < nHigh; ++r ) - { - int ty = r * height + y; - int th = h; - if ( ty + th > newHeight ) - th = newHeight - ty; - for ( int c = 0; c < nWide; ++c ) - { - int tx = c * width + x; - int tw = w; - if ( tx + tw > newWidth ) - tw = newWidth - tx; - consumer.setPixels( - tx, ty, tw, th, model, pixels, off, scansize ); - } - } - } - - - // Main routine for command-line interface. - public static void main( String[] args ) - { - if ( args.length != 2 ) - usage(); - ImageFilterPlus filter = - new Tile( null, - Integer.parseInt( args[0] ), Integer.parseInt( args[1] ) ); - System.exit( - ImageFilterPlus.filterStream( System.in, System.out, filter ) ); - } - - private static void usage() - { - System.err.println( "usage: Tile " ); - System.exit( 1 ); - } - - } diff --git a/src/Acme/JPM/JPMUtils.java b/src/Acme/JPM/JPMUtils.java deleted file mode 100644 index 003c987a..00000000 --- a/src/Acme/JPM/JPMUtils.java +++ /dev/null @@ -1,50 +0,0 @@ -// JPMUtils - static utility routines for the JPM packages -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.JPM; - -import java.awt.*; -import java.awt.image.*; -import Acme.JPM.Filters.*; - -/// Static utility routines for the JPM packages. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class JPMUtils - { - - /// Filter one image into another. - public static Image filterImage( Component comp, ImageFilterPlus filter ) - { - return comp.createImage( - new FilteredImageSource( filter.getSource(), filter ) ); - } - - } diff --git a/src/Acme/LruHashtable.java b/src/Acme/LruHashtable.java deleted file mode 100644 index 9611a237..00000000 --- a/src/Acme/LruHashtable.java +++ /dev/null @@ -1,303 +0,0 @@ -// LruHashtable - a Hashtable that expires least-recently-used objects -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme; - -import java.util.*; - -/// A Hashtable that expires least-recently-used objects. -//

-// Use just like java.util.Hashtable, except that the initial-capacity -// parameter is required. Instead of growing bigger than that size, -// it will throw out objects that haven't been looked at in a while. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see java.util.Hashtable - -public class LruHashtable extends Hashtable - { - - // Number of buckets. - private static final int nBuckets = 2; - - // Load factor. - private float loadFactor; - - // When count exceeds this threshold, expires the old table. - private int threshold; - - // Capacity of each bucket. - private int eachCapacity; - - // The tables. - private Hashtable oldTable; - private Hashtable newTable; - - /// Constructs a new, empty hashtable with the specified initial - // capacity and the specified load factor. - // Unlike a plain Hashtable, an LruHashtable will never grow or - // shrink from this initial capacity. - // @param initialCapacity the initial number of buckets - // @param loadFactor a number between 0.0 and 1.0, it defines - // the threshold for expiring old entries - // @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 LruHashtable( int initialCapacity, float loadFactor ) - { - // We have to call a superclass constructor, but we're not actually - // going to use it at all. The only reason we want to extend Hashtable - // is for type conformance. So, make a parent hash table of minimum - // size and then ignore it. - super( 1 ); - - if ( initialCapacity <= 0 || loadFactor <= 0.0 ) - throw new IllegalArgumentException(); - this.loadFactor = loadFactor; - threshold = (int) ( initialCapacity * loadFactor ) - 1; - eachCapacity = initialCapacity / nBuckets + 1; - oldTable = new Hashtable( eachCapacity, loadFactor ); - newTable = new Hashtable( eachCapacity, loadFactor ); - } - - /// Constructs a new, empty hashtable with the specified initial - // capacity. - // Unlike a plain Hashtable, an LruHashtable will never grow or - // shrink from this initial capacity. - // @param initialCapacity the initial number of buckets - public LruHashtable( int initialCapacity ) - { - this( initialCapacity, 0.75F ); - } - - /// Returns the number of elements contained in the hashtable. - public int size() - { - return newTable.size() + oldTable.size(); - } - - /// Returns true if the hashtable contains no elements. - public boolean isEmpty() - { - return size() == 0; - } - - /// Returns an enumeration of the hashtable's keys. - // @see LruHashtable#elements - // @see Enumeration - public synchronized Enumeration keys() - { - return new LruHashtableEnumerator( oldTable, newTable, true ); - } - - /// Returns an enumeration of the elements. Use the Enumeration methods - // on the returned object to fetch the elements sequentially. - // @see LruHashtable#keys - // @see Enumeration - public synchronized Enumeration elements() - { - return new LruHashtableEnumerator( oldTable, newTable, 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 LruHashtable#containsKey - public synchronized boolean contains( Object value ) - { - if ( newTable.contains( value ) ) - return true; - if ( oldTable.contains( value ) ) - { - // We would like to move the object from the old table to the - // new table. However, we need keys to re-add the objects, and - // there's no good way to find all the keys for the given object. - // We'd have to enumerate through all the keys and check each - // one. Yuck. For now we just punt. Anyway, contains() is - // probably not a commonly-used operation. - 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 LruHashtable#contains - public synchronized boolean containsKey( Object key ) - { - if ( newTable.containsKey( key ) ) - return true; - if ( oldTable.containsKey( key ) ) - { - // Move object from old table to new table. - Object value = oldTable.get( key ); - newTable.put( key, value ); - oldTable.remove( 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 LruHashtable#put - public synchronized Object get( Object key ) - { - Object value; - value = newTable.get( key ); - if ( value != null ) - return value; - value = oldTable.get( key ); - if ( value != null ) - { - // Move object from old table to new table. - newTable.put( key, value ); - oldTable.remove( key ); - return value; - } - return null; - } - - /// 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 LruHashtable#get - // @return the old value of the key, or null if it did not have one. - public synchronized Object put( Object key, Object value ) - { - Object oldValue = newTable.put( key, value ); - if ( oldValue != null ) - return oldValue; - oldValue = oldTable.get( key ); - if ( oldValue != null ) - oldTable.remove( key ); - else - { - if ( size() >= threshold ) - { - // Rotate the tables. - oldTable = newTable; - newTable = new Hashtable( eachCapacity, loadFactor ); - } - } - return oldValue; - } - - /// 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( Object key ) - { - Object oldValue = newTable.remove( key ); - if ( oldValue == null ) - oldValue = oldTable.remove( key ); - return oldValue; - } - - /// Clears the hash table so that it has no more elements in it. - public synchronized void clear() - { - newTable.clear(); - oldTable.clear(); - } - - /// 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() - { - LruHashtable n = (LruHashtable) super.clone(); - n.newTable = (Hashtable) n.newTable.clone(); - n.oldTable = (Hashtable) n.oldTable.clone(); - return n; - } - - // toString() can be inherited. - - } - - -class LruHashtableEnumerator implements Enumeration - { - Enumeration oldEnum; - Enumeration newEnum; - boolean old; - - LruHashtableEnumerator( Hashtable oldTable, Hashtable newTable, boolean keys ) - { - if ( keys ) - { - oldEnum = oldTable.keys(); - newEnum = newTable.keys(); - } - else - { - oldEnum = oldTable.elements(); - newEnum = newTable.elements(); - } - old = true; - } - - public boolean hasMoreElements() - { - boolean r; - if ( old ) - { - r = oldEnum.hasMoreElements(); - if ( ! r ) - { - old = false; - r = newEnum.hasMoreElements(); - } - } - else - r = newEnum.hasMoreElements(); - return r; - } - - public Object nextElement() - { - if ( old ) - return oldEnum.nextElement(); - return newEnum.nextElement(); - } - - } diff --git a/src/Acme/Serve/CgiServlet.java b/src/Acme/Serve/CgiServlet.java deleted file mode 100644 index 64006ef1..00000000 --- a/src/Acme/Serve/CgiServlet.java +++ /dev/null @@ -1,313 +0,0 @@ -// CgiServlet - runs CGI programs -// -// Copyright (C)1996,1998 by Jef Poskanzer . 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 Acme.Serve; - -import java.io.*; -import java.util.*; -import javax.servlet.*; -import javax.servlet.http.*; - -/// Runs CGI programs. -//

-// Note: although many implementations of CGI set the working directory of -// the subprocess to be the directory containing the executable file, the -// CGI spec actually says nothing about the working directory. Since -// Java has no method for setting the working directory, this implementation -// does not set it. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see Acme.Serve.Serve - -public class CgiServlet extends HttpServlet - { - - /// Returns a string containing information about the author, version, and - // copyright of the servlet. - public String getServletInfo() - { - return "runs CGI programs"; - } - - /// Services a single request from the client. - // @param req the servlet request - // @param req the servlet response - // @exception ServletException when an exception has occurred - public void service( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException - { - if ( ! ( req.getMethod().equalsIgnoreCase( "get" ) || - req.getMethod().equalsIgnoreCase( "post" ) ) ) - { - res.sendError( HttpServletResponse.SC_NOT_IMPLEMENTED ); - return; - } - - String path = req.getServletPath(); - if ( path == null || path.charAt( 0 ) != '/' ) - { - res.sendError( HttpServletResponse.SC_BAD_REQUEST ); - return; - } - if ( path.indexOf( "/../" ) != -1 || path.endsWith( "/.." ) ) - { - res.sendError( HttpServletResponse.SC_FORBIDDEN ); - return; - } - - // Make a version without the leading /. - String pathname = path.substring( 1 ); - if ( pathname.length() == 0 ) - pathname = "./"; - - dispatchPathname( req, res, path, pathname ); - } - - - private void dispatchPathname( HttpServletRequest req, HttpServletResponse res, String path, String pathname ) throws IOException - { - String filename = pathname.replace( '/', File.separatorChar ); - if ( filename.charAt( filename.length() - 1 ) == File.separatorChar ) - filename = filename.substring( 0, filename.length() - 1 ); - filename = getServletContext().getRealPath( filename ); - File file = new File( filename ); - if ( file.exists() ) - serveFile( req, res, path, filename, file ); - else - res.sendError( HttpServletResponse.SC_NOT_FOUND ); - } - - - private void serveFile( HttpServletRequest req, HttpServletResponse res, String path, String filename, File file ) throws IOException - { - String queryString = req.getQueryString(); - int contentLength = req.getContentLength(); - int c; - - log( "running " + path ); - - // Make argument list. - Vector argVec = new Vector(); - argVec.addElement( filename ); - if ( queryString != null && queryString.indexOf( "=" ) == -1 ) - { - Enumeration enum = new StringTokenizer( queryString, "+" ); - while ( enum.hasMoreElements() ) - argVec.addElement( (String) enum.nextElement() ); - } - String argList[] = makeList( argVec ); - - // Make environment list. - Vector envVec = new Vector(); - envVec.addElement( makeEnv( - "PATH", "/usr/local/bin:/usr/ucb:/bin:/usr/bin" ) ); - envVec.addElement( makeEnv( "GATEWAY_INTERFACE", "CGI/1.1" ) ); - envVec.addElement( makeEnv( - "SERVER_SOFTWARE", getServletContext().getServerInfo() ) ); - envVec.addElement( makeEnv( "SERVER_NAME", req.getServerName() ) ); - envVec.addElement( makeEnv( - "SERVER_PORT", Integer.toString( req.getServerPort() ) ) ); - envVec.addElement( makeEnv( "REMOTE_ADDR", req.getRemoteAddr() ) ); - envVec.addElement( makeEnv( "REMOTE_HOST", req.getRemoteHost() ) ); - envVec.addElement( makeEnv( "REQUEST_METHOD", req.getMethod() ) ); - if ( contentLength != -1 ) - envVec.addElement( makeEnv( - "CONTENT_LENGTH", Integer.toString( contentLength ) ) ); - if ( req.getContentType() != null ) - envVec.addElement( makeEnv( - "CONTENT_TYPE", req.getContentType() ) ); - envVec.addElement( makeEnv( "SCRIPT_NAME", req.getServletPath() ) ); - if ( req.getPathInfo() != null ) - envVec.addElement( makeEnv( "PATH_INFO", req.getPathInfo() ) ); - if ( req.getPathTranslated() != null ) - envVec.addElement( makeEnv( - "PATH_TRANSLATED", req.getPathTranslated() ) ); - if ( queryString != null ) - envVec.addElement( makeEnv( "QUERY_STRING", queryString ) ); - envVec.addElement( makeEnv( "SERVER_PROTOCOL", req.getProtocol() ) ); - if ( req.getRemoteUser() != null ) - envVec.addElement( makeEnv( "REMOTE_USER", req.getRemoteUser() ) ); - if ( req.getAuthType() != null ) - envVec.addElement( makeEnv( "AUTH_TYPE", req.getAuthType() ) ); - Enumeration enum = req.getHeaderNames(); - while ( enum.hasMoreElements() ) - { - String name = (String) enum.nextElement(); - String value = req.getHeader( name ); - if ( value == null ) - value = ""; - envVec.addElement( makeEnv( - "HTTP_" + name.toUpperCase().replace( '-', '_' ), value ) ); - } - String envList[] = makeList( envVec ); - - // Start the command. - Process proc = Runtime.getRuntime().exec( argList, envList ); - - try - { - // If it's a POST, copy the request data to the process. - if ( req.getMethod().equalsIgnoreCase( "post" ) ) - { - InputStream reqIn = req.getInputStream(); - OutputStream procOut = proc.getOutputStream(); - for ( int i = 0; i < contentLength; ++i ) - { - c = reqIn.read(); - if ( c == -1 ) - break; - procOut.write( c ); - } - procOut.close(); - } - - // Now read the response from the process. - BufferedReader procIn = new BufferedReader( new InputStreamReader( - proc.getInputStream() ) ); - OutputStream resOut = res.getOutputStream(); - // Some of the headers have to be intercepted and handled. - boolean firstLine = true; - while ( true ) - { - String line = procIn.readLine(); - if ( line == null ) - break; - line = line.trim(); - if ( line.equals( "" ) ) - break; - int colon = line.indexOf( ":" ); - if ( colon == -1 ) - { - // No colon. If it's the first line, parse it for status. - if ( firstLine ) - { - StringTokenizer tok = new StringTokenizer( line, " " ); - try - { - switch( tok.countTokens() ) - { - case 2: - tok.nextToken(); - res.setStatus( - Integer.parseInt( tok.nextToken() ) ); - break; - case 3: - tok.nextToken(); - res.setStatus( - Integer.parseInt( tok.nextToken() ), - tok.nextToken() ); - break; - } - } - catch ( NumberFormatException ignore ) {} - } - else - { - // No colon and it's not the first line? Ignore. - } - } - else - { - // There's a colon. Check for certain special headers. - String name = line.substring( 0, colon ); - String value = line.substring( colon + 1 ).trim(); - if ( name.equalsIgnoreCase( "Status" ) ) - { - StringTokenizer tok = new StringTokenizer( value, " " ); - try - { - switch( tok.countTokens() ) - { - case 1: - res.setStatus( - Integer.parseInt( tok.nextToken() ) ); - break; - case 2: - res.setStatus( - Integer.parseInt( tok.nextToken() ), - tok.nextToken() ); - break; - } - } - catch ( NumberFormatException ignore ) {} - } - else if ( name.equalsIgnoreCase( "Content-type" ) ) - { - res.setContentType( value ); - } - else if ( name.equalsIgnoreCase( "Content-length" ) ) - { - try - { - res.setContentLength( Integer.parseInt( value ) ); - } - catch ( NumberFormatException ignore ) {} - } - else if ( name.equalsIgnoreCase( "Location" ) ) - { - res.setStatus( - HttpServletResponse.SC_MOVED_TEMPORARILY ); - res.setHeader( name, value ); - } - else - { - // Not a special header. Just set it. - res.setHeader( name, value ); - } - } - } - // Copy the rest of the data uninterpreted. - Acme.Utils.copyStream( procIn, resOut ); - procIn.close(); - resOut.close(); - } - catch ( IOException e ) - { - //res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - // There's some weird bug in Java, when reading from a Process - // you get a spurious IOException. We have to ignore it. - } - } - - - private static String makeEnv( String name, String value ) - { - return name + "=" + value; - } - - - private static String[] makeList( Vector vec ) - { - String list[] = new String[vec.size()]; - for ( int i = 0; i < vec.size(); ++i ) - list[i] = (String) vec.elementAt( i ); - return list; - } - - } diff --git a/src/Acme/Serve/FileServlet.java b/src/Acme/Serve/FileServlet.java deleted file mode 100644 index 3a8c59a3..00000000 --- a/src/Acme/Serve/FileServlet.java +++ /dev/null @@ -1,316 +0,0 @@ -// FileServlet - servlet similar to a standard httpd -// -// Copyright (C)1996,1998 by Jef Poskanzer . 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 Acme.Serve; - -import java.io.*; -import java.util.*; -import java.text.*; -import javax.servlet.*; -import javax.servlet.http.*; - -/// Servlet similar to a standard httpd. -//

-// Implements the "GET" and "HEAD" methods for files and directories. -// Handles index.html. -// Redirects directory URLs that lack a trailing /. -// Handles If-Modified-Since and Range. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see Acme.Serve.Serve - -public class FileServlet extends HttpServlet - { - - // We keep a single throttle table for all instances of the servlet. - // Normally there is only one instance; the exception is subclasses. - static Acme.WildcardDictionary throttleTab = null; - - /// Constructor. - public FileServlet() - { - } - - /// Constructor with throttling. - // @param throttles filename containing throttle settings - // @see ThrottledOutputStream - public FileServlet( String throttles ) throws IOException - { - this(); - readThrottles( throttles ); - } - - private void readThrottles( String throttles ) throws IOException - { - Acme.WildcardDictionary newThrottleTab = - ThrottledOutputStream.parseThrottleFile( throttles ); - if ( throttleTab == null ) - throttleTab = newThrottleTab; - else - { - // Merge the new one into the old one. - Enumeration keys = newThrottleTab.keys(); - Enumeration elements = newThrottleTab.elements(); - while ( keys.hasMoreElements() ) - { - Object key = keys.nextElement(); - Object element = elements.nextElement(); - throttleTab.put( key, element ); - } - } - } - - /// Returns a string containing information about the author, version, and - // copyright of the servlet. - public String getServletInfo() - { - return "servlet similar to a standard httpd"; - } - - - /// Services a single request from the client. - // @param req the servlet request - // @param req the servlet response - // @exception ServletException when an exception has occurred - public void service( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException - { - boolean headOnly; - if ( req.getMethod().equalsIgnoreCase( "get" ) ) - headOnly = false; - else if ( ! req.getMethod().equalsIgnoreCase( "head" ) ) - headOnly = true; - else - { - res.sendError( HttpServletResponse.SC_NOT_IMPLEMENTED ); - return; - } - - String path = req.getServletPath(); - if ( path == null || path.charAt( 0 ) != '/' ) - { - res.sendError( HttpServletResponse.SC_BAD_REQUEST ); - return; - } - if ( path.indexOf( "/../" ) != -1 || path.endsWith( "/.." ) ) - { - res.sendError( HttpServletResponse.SC_FORBIDDEN ); - return; - } - - // Make a version without the leading /. - String pathname = path.substring( 1 ); - if ( pathname.length() == 0 ) - pathname = "./"; - - dispatchPathname( req, res, headOnly, path, pathname ); - } - - - private void dispatchPathname( HttpServletRequest req, HttpServletResponse res, boolean headOnly, String path, String pathname ) throws IOException - { - String filename = pathname.replace( '/', File.separatorChar ); - if ( filename.charAt( filename.length() - 1 ) == File.separatorChar ) - filename = filename.substring( 0, filename.length() - 1 ); - filename = getServletContext().getRealPath( filename ); - File file = new File( filename ); - if ( file.exists() ) - { - if ( ! file.isDirectory() ) - serveFile( req, res, headOnly, path, filename, file ); - else - { - if ( pathname.charAt( pathname.length() - 1 ) != '/' ) - redirectDirectory( req, res, path, file ); - else - { - String indexFilename = - filename + File.separatorChar + "index.html"; - File indexFile = new File( indexFilename ); - if ( indexFile.exists() ) - serveFile( - req, res, headOnly, path, indexFilename, - indexFile ); - else - serveDirectory( - req, res, headOnly, path, filename, file ); - } - } - } - else - { - if ( pathname.endsWith( "/index.html" ) ) - dispatchPathname( - req, res, headOnly, path, - pathname.substring( 0, pathname.length() - 10 ) ); - else if ( pathname.equals( "index.html" ) ) - dispatchPathname( req, res, headOnly, path, "./" ); - else - res.sendError( HttpServletResponse.SC_NOT_FOUND ); - } - } - - - protected void serveFile( HttpServletRequest req, HttpServletResponse res, boolean headOnly, String path, String filename, File file ) throws IOException - { - // log( "getting " + path ); - if ( ! file.canRead() ) - { - res.sendError( HttpServletResponse.SC_FORBIDDEN ); - return; - } - - // Handle If-Modified-Since. - res.setStatus( HttpServletResponse.SC_OK ); - long lastMod = file.lastModified(); - String ifModSinceStr = req.getHeader( "If-Modified-Since" ); - long ifModSince = -1; - if ( ifModSinceStr != null ) - { - int semi = ifModSinceStr.indexOf( ';' ); - if ( semi != -1 ) - ifModSinceStr = ifModSinceStr.substring( 0, semi ); - try - { - ifModSince = - DateFormat.getDateInstance().parse( ifModSinceStr ).getTime(); - } - catch ( Exception ignore ) {} - } - if ( ifModSince != -1 && ifModSince >= lastMod ) - { - res.setStatus( HttpServletResponse.SC_NOT_MODIFIED ); - headOnly = true; - } - - String rangeStr = req.getHeader( "Range" ); - if ( rangeStr != null ) - { - //!!! - } - - res.setContentType( getServletContext().getMimeType( filename ) ); - res.setContentLength( (int) file.length() ); - res.setDateHeader( "Last-modified", lastMod ); - OutputStream out = res.getOutputStream(); - if ( ! headOnly ) - { - // Check throttle. - if ( throttleTab != null ) - { - ThrottleItem throttleItem = - (ThrottleItem) throttleTab.get( path ); - if ( throttleItem != null ) - { - // !!! Need to account for multiple simultaneous fetches. - out = new ThrottledOutputStream( - out, throttleItem.getMaxBps() ); - } - } - - InputStream in = new FileInputStream( file ); - copyStream( in, out ); - in.close(); - } - out.close(); - } - - /// Copy a file from in to out. - // Sub-classes can override this in order to do filtering of some sort. - public void copyStream( InputStream in, OutputStream out ) throws IOException - { - Acme.Utils.copyStream( in, out ); - } - - - private void serveDirectory( HttpServletRequest req, HttpServletResponse res, boolean headOnly, String path, String filename, File file ) throws IOException - { - log( "indexing " + path ); - if ( ! file.canRead() ) - { - res.sendError( HttpServletResponse.SC_FORBIDDEN ); - return; - } - res.setStatus( HttpServletResponse.SC_OK ); - res.setContentType( "text/html" ); - OutputStream out = res.getOutputStream(); - if ( ! headOnly ) - { - PrintStream p = new PrintStream( new BufferedOutputStream( out ) ); - p.println( "" ); - p.println( "Index of " + path + "" ); - p.println( "" ); - p.println( "

Index of " + path + "

" ); - p.println( "
" );
-	    p.println( "mode     bytes  last-changed  name" );
-	    p.println( "
" ); - String[] names = file.list(); - Acme.Utils.sortStrings( names ); - for ( int i = 0; i < names.length; ++i ) - { - String aFilename = filename + File.separatorChar + names[i]; - File aFile = new File( aFilename ); - String aFileType; - if ( aFile.isDirectory() ) - aFileType = "d"; - else if ( aFile.isFile() ) - aFileType = "-"; - else - aFileType = "?"; - String aFileRead = ( aFile.canRead() ? "r" : "-" ); - String aFileWrite = ( aFile.canWrite() ? "w" : "-" ); - String aFileExe = "-"; - String aFileSize = Acme.Fmt.fmt( aFile.length(), 8 ); - String aFileDate = - Acme.Utils.lsDateStr( new Date( aFile.lastModified() ) ); - String aFileDirsuf = ( aFile.isDirectory() ? "/" : "" ); - String aFileSuf = ( aFile.isDirectory() ? "/" : "" ); - p.println( - aFileType + aFileRead + aFileWrite + aFileExe + - " " + aFileSize + " " + aFileDate + " " + - "" + - names[i] + aFileSuf + "" ); - } - p.println( "
" ); - p.println( "
" ); - ServeUtils.writeAddress( p ); - p.println( "" ); - p.flush(); - } - out.close(); - } - - - protected void redirectDirectory( HttpServletRequest req, HttpServletResponse res, String path, File file ) throws IOException - { - log( "redirecting " + path ); - res.sendRedirect( path + "/" ); - } - - } diff --git a/src/Acme/Serve/SampleServlet.java b/src/Acme/Serve/SampleServlet.java deleted file mode 100644 index e575851a..00000000 --- a/src/Acme/Serve/SampleServlet.java +++ /dev/null @@ -1,70 +0,0 @@ -// SampleServlet - trivial servlet -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.Serve; - -import java.io.*; -import javax.servlet.*; -import javax.servlet.http.*; - -/// Trivial servlet. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class SampleServlet extends HttpServlet - { - - /// Returns a string containing information about the author, version, and - // copyright of the servlet. - public String getServletInfo() - { - return "trivial servlet"; - } - - /// Services a single request from the client. - // @param req the servlet request - // @param req the servlet response - // @exception ServletException when an exception has occurred - public void service( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException - { - log( "called" ); - res.setStatus( HttpServletResponse.SC_OK ); - res.setContentType( "text/html" ); - ServletOutputStream p = res.getOutputStream(); - p.println( "" ); - p.println( "Sample Servlet Output" ); - p.println( "" ); - p.println( "

Sample Servlet Output

" ); - p.println( "

Output from a sample servlet." ); - p.println( "" ); - p.flush(); - p.close(); - } - - } diff --git a/src/Acme/Serve/Serve.java b/src/Acme/Serve/Serve.java deleted file mode 100644 index a7c8390b..00000000 --- a/src/Acme/Serve/Serve.java +++ /dev/null @@ -1,1763 +0,0 @@ -// Serve - minimal Java HTTP server class -// -// Copyright (C)1996,1998 by Jef Poskanzer . 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 Acme.Serve; - -import java.io.*; -import java.util.*; -import java.net.*; -import java.text.*; -// import Acme.Serve.servlet.*; -// import Acme.Serve.servlet.http.*; -import javax.servlet.*; -import javax.servlet.http.*; - -/// Minimal Java HTTP server class. -//

-// This class implements a very small embeddable HTTP server. -// It runs Servlets compatible with the API used by JavaSoft's -// JavaServer server. -// It comes with default Servlets which provide the usual -// httpd services, returning files and directory listings. -//

-// This is not in any sense a competitor for JavaServer. -// JavaServer is a full-fledged HTTP server and more. -// Acme.Serve is tiny, about 1500 lines, and provides only the -// functionality necessary to deliver an Applet's .class files -// and then start up a Servlet talking to the Applet. -// They are both written in Java, they are both web servers, and -// they both implement the Servlet API; other than that they couldn't -// be more different. -//

-// This is actually the second HTTP server I've written. -// The other one is called -// thttpd, -// it's written in C, and is also pretty small although much more -// featureful than this. -//

-// Other Java HTTP servers: -//

-//

-// A June 1997 BYTE magazine article mentioning this server.
-// A December 1997 BYTE magazine article giving it an Editor's Choice Award of Distinction.
-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see Acme.Serve.servlet.http.HttpServlet -// @see FileServlet -// @see CgiServlet - -public class Serve implements ServletContext, Runnable - { - - private static final String progName = "Serve"; - - /// Main routine, if you want to run this directly as an application. - public static void main( String[] args ) - { - // Parse args. - int port = 9090; - String throttles = null; - int argc = args.length; - int argn; - for ( argn = 0; argn < argc && args[argn].charAt( 0 ) == '-'; ++argn ) - { - if ( args[argn].equals( "-p" ) && argn + 1 < argc ) - { - ++argn; - port = Integer.parseInt( args[argn] ); - } - else if ( args[argn].equals( "-t" ) && argn + 1 < argc ) - { - ++argn; - throttles = args[argn]; - } - else - usage(); - } - if ( argn != argc ) - usage(); - - // Create the server. - Serve serve = new Serve( port ); - - // Any custom Servlets should be added here. - serve.addServlet( "/SampleServlet", new Acme.Serve.SampleServlet() ); - Servlet ts = new Acme.Serve.TestServlet(); - serve.addServlet( "/TestServlet", ts ); - serve.addServlet( "/TestServlet/*", ts ); - - // And add the standard Servlets. - if ( throttles == null ) - serve.addDefaultServlets( true ); - else - try - { - serve.addDefaultServlets( true, throttles ); - } - catch ( IOException e ) - { - System.err.println( "Problem reading throttles file: " + e ); - System.exit( 1 ); - } - - // And run. - serve.serve(); - - System.exit( 0 ); - } - - private static void usage() - { - System.err.println( "usage: " + progName + " [-p port]" ); - System.exit( 1 ); - } - - - private int port; - private PrintStream logStream; - Acme.WildcardDictionary registry; - // the servlet to use if no other matches the request - Servlet defaultServlet; - Properties props; - - /// Constructor. - public Serve( int port, PrintStream logStream, Properties props ) - { - this.port = port; - this.logStream = logStream; - this.props = props; - registry = new Acme.WildcardDictionary(); - } - - /// Constructor. - public Serve( int port, PrintStream logStream ) - { - this( port, logStream, new Properties()); - } - - /// Constructor, default log stream. - public Serve( int port, Properties props ) - { - this( port, System.err, props ); - } - - - /// Constructor, default log stream. - public Serve( int port ) - { - this( port, System.err, new Properties() ); - } - - /// Constructor, default port and log stream. - // We don't use 80 as the default port because we don't want to - // encourage people to run a Java web server as root because Java - // currently has no way of giving up root privs! Instead, the - // current default port is 9090. - public Serve() - { - this( 9090, System.err, new Properties()); - } - - - /// Register a Servlet by class name. Registration consists of a URL - // pattern, which can contain wildcards, and the class name of the Servlet - // to launch when a matching URL comes in. Patterns are checked for - // matches in the order they were added, and only the first match is run. - public void addServlet( String urlPat, String className ) - { - // See if we have already instantiated this one. - Servlet servlet = (Servlet) servlets.get( className ); - if ( servlet != null ) - { - addServlet( urlPat, servlet ); - return; - } - - // Check if we're allowed to make one of these. - SecurityManager security = System.getSecurityManager(); - if ( security != null ) - { - int i = className.lastIndexOf( '.' ); - if ( i != -1 ) - { - security.checkPackageAccess( - className.substring( 0, i ) ); - security.checkPackageDefinition( - className.substring( 0, i ) ); - } - } - - // Make a new one. - try - { - servlet = (Servlet) Class.forName( className ).newInstance(); - addServlet( urlPat, servlet ); - return; - } - catch ( ClassNotFoundException e ) - { - log( "Class not found: " + className ); - } - catch ( ClassCastException e ) - { - log( "Class cast problem: " + e.getMessage() ); - } - catch ( InstantiationException e ) - { - log( "Instantiation problem: " + e.getMessage() ); - } - catch ( IllegalAccessException e ) - { - log( "Illegal class access: " + e.getMessage() ); - } - catch ( Exception e ) - { - log( "Unexpected problem creating servlet: " + e ); - } - } - - /// Register a Servlet. Registration consists of a URL pattern, - // which can contain wildcards, and the Servlet to - // launch when a matching URL comes in. Patterns are checked for - // matches in the order they were added, and only the first match is run. - public void addServlet( String urlPat, Servlet servlet ) - { - try - { - servlet.init( new ServeConfig( (ServletContext) this ) ); - registry.put( urlPat, servlet ); - servlets.put( servlet.getClass().getName(), servlet ); - } - catch ( ServletException e ) - { - log( "Problem initializing servlet: " + e ); - } - } - - public void removeServlet( String urlPat ) - { - registry.remove (urlPat); - } - - public void setDefaultServlet (Servlet servlet) { - defaultServlet = servlet; - } - - /// Register a standard set of Servlets. These will return - // files or directory listings, and run CGI programs, much like a - // standard HTTP server. - //

- // Because of the pattern checking order, this should be called - // after you've added any custom Servlets. - //

- // The current set of default servlet mappings: - //

    - //
  • If enabled, *.cgi goes to CgiServlet, and gets run as a CGI program. - //
  • * goes to FileServlet, and gets served up as a file or directory. - //
- // @param cgi whether to run CGI programs - public void addDefaultServlets( boolean cgi ) - { - if ( cgi ) - addServlet( "*.cgi", new Acme.Serve.CgiServlet() ); - addServlet( "*", new Acme.Serve.FileServlet() ); - } - - /// Register a standard set of Servlets, with throttles. - // @param cgi whether to run CGI programs - // @param throttles filename to read FileServlet throttle settings from - public void addDefaultServlets( boolean cgi, String throttles ) throws IOException - { - if ( cgi ) - addServlet( "*.cgi", new Acme.Serve.CgiServlet() ); - addServlet( "*", new Acme.Serve.FileServlet( throttles ) ); - } - - public void run() - { - serve(); - } - - - /// Run the server. Returns only on errors. - public void serve() - { - ServerSocket serverSocket; - try - { - serverSocket = new ServerSocket( port, 1000 ); - } - catch ( IOException e ) - { - log( "Server socket: " + e ); - return; - } - - try - { - while ( true ) - { - Socket socket = serverSocket.accept(); - new ServeConnection( socket, this ); - } - } - catch ( IOException e ) - { - log( "Accept: " + e ); - } - finally - { - try - { - serverSocket.close(); - destroyAllServlets(); - } - catch ( IOException e ) {} - } - } - - - // Methods from ServletContext. - - protected Hashtable servlets = new Hashtable(); - - /// Gets a servlet by name. - // @param name the servlet name - // @return null if the servlet does not exist - public Servlet getServlet( String name ) - { - return (Servlet) servlets.get( name ); - } - - /// Enumerates the servlets in this context (server). Only servlets that - // are accesible will be returned. This enumeration always includes the - // servlet itself. - public Enumeration getServlets() - { - return servlets.elements(); - } - - /// Enumerates the names of the servlets in this context (server). Only - // servlets that are accesible will be returned. This enumeration always - // includes the servlet itself. - public Enumeration getServletNames() - { - return servlets.keys(); - } - - /// Destroys all currently-loaded servlets. - public void destroyAllServlets() - { - Enumeration en = servlets.elements(); - while ( en.hasMoreElements() ) - { - Servlet servlet = (Servlet) en.nextElement(); - servlet.destroy(); - } - servlets.clear(); - } - - /// Write information to the servlet log. - // @param message the message to log - public void log( String message ) - { - Date date = new Date( System.currentTimeMillis() ); - logStream.println( "[" + date.toString() + "] " + message ); - } - - /// Write a stack trace to the servlet log. - // @param exception where to get the stack trace - // @param message the message to log - public void log( Exception exception, String message ) - { - // !!! - log( message ); - } - - /// Applies alias rules to the specified virtual path and returns the - // corresponding real path. It returns null if the translation - // cannot be performed. - // @param path the path to be translated - public String getRealPath( String path ) - { - // No mapping. - return path; - } - - /// Returns the MIME type of the specified file. - // @param file file name whose MIME type is required - public String getMimeType( String file ) - { - int lastDot = file.lastIndexOf( '.' ); - int lastSep = file.lastIndexOf( File.separatorChar ); - if ( lastDot == -1 || - ( lastSep != -1 && lastDot < lastSep ) ) - return "text/plain"; - String extension = file.substring( lastDot + 1 ); - if ( extension.equals( "html" ) || extension.equals( "htm" ) ) - return "text/html"; - if ( extension.equals( "gif" ) ) - return "image/gif"; - if ( extension.equals( "jpg" ) || extension.equals( "jpeg" ) ) - return "image/jpeg"; - if ( extension.equals( "au" ) ) - return "audio/basic"; - if ( extension.equals( "ra" ) || extension.equals( "ram" ) ) - return "audio/x-pn-realaudio"; - if ( extension.equals( "wav" ) ) - return "audio/wav"; - if ( extension.equals( "mpg" ) || extension.equals( "mpeg" ) ) - return "video/mpeg"; - if ( extension.equals( "qt" ) || extension.equals( "mov" ) ) - return "video/quicktime"; - if ( extension.equals( "class" ) ) - return "application/octet-stream"; - if ( extension.equals( "ps" ) ) - return "application/postscript"; - if ( extension.equals( "wrl" ) ) - return "x-world/x-vrml"; - if ( extension.equals( "pac" ) ) - return "application/x-ns-proxy-autoconfig"; - return "text/plain"; - } - - /// Returns the name and version of the web server under which the servlet - // is running. - // Same as the CGI variable SERVER_SOFTWARE. - public String getServerInfo() - { - return ServeUtils.serverName + " " + helma.main.Server.version + " (" + ServeUtils.serverUrl + ")"; - } - - /// Returns the value of the named attribute of the network service, or - // null if the attribute does not exist. This method allows access to - // additional information about the service, not already provided by - // the other methods in this interface. - public Object getAttribute( String name ) - { - // This server does not support attributes. - return null; - } - - } - - -class ServeConfig implements ServletConfig - { - - private ServletContext context; - - public ServeConfig( ServletContext context ) - { - this.context = context; - } - - // Methods from ServletConfig. - - /// Returns the context for the servlet. - public ServletContext getServletContext() - { - return context; - } - - /// Gets an initialization parameter of the servlet. - // @param name the parameter name - public String getInitParameter( String name ) - { - // This server doesn't support servlet init params. - return null; - } - - /// Gets the names of the initialization parameters of the servlet. - // @param name the parameter name - public Enumeration getInitParameterNames() - { - // This server doesn't support servlet init params. - return new Vector().elements(); - } - - } - - -class ServeConnection implements Runnable, HttpServletRequest, HttpServletResponse - { - - private Socket socket; - private Serve serve; - - private ServletInputStream in; - private ServletOutputStream out; - - private Vector cookies = new Vector(); // !!! - - - /// Constructor. - public ServeConnection( Socket socket, Serve serve ) - { - // Save arguments. - this.socket = socket; - this.serve = serve; - - // Start a separate thread to read and handle the request. - Thread thread = new Thread( this ); - thread.start(); - } - - - // Methods from Runnable. - - private String reqMethod = null; - private String reqUriPath = null; - private String reqProtocol = null; - private boolean oneOne; // HTTP/1.1 or better - private boolean reqMime; - String reqQuery = null; - private Vector reqHeaderNames = new Vector(); - private Vector reqHeaderValues = new Vector(); - - public void run() - { - try - { - // Get the streams. - in = new ServeInputStream( socket.getInputStream() ); - out = new ServeOutputStream( socket.getOutputStream(), this ); - } - catch ( IOException e ) - { - problem( "Getting streams: " + e.getMessage(), SC_BAD_REQUEST ); - } - - parseRequest(); - - // FIXME: - // There's a strange bug with Netscape/Unix where NS laments - // that the peer closed the connection when POST requests are - // redirected. Waiting for one second seems to fix the problem. - /* try - { - Thread.currentThread().sleep (1000l); - } - catch (InterruptedException ignore) {} */ - - try - { - socket.close(); - } - catch ( IOException e ) { /* ignore */ } - } - - private void parseRequest() - { - byte[] lineBytes = new byte[4096]; - int len; - String line; - - try - { - // Read the first line of the request. - len = in.readLine( lineBytes, 0, lineBytes.length ); - if ( len == -1 || len == 0 ) - { - problem( "Empty request", SC_BAD_REQUEST ); - return; - } - line = new String( lineBytes, 0, len ); - String[] tokens = Acme.Utils.splitStr( line ); - switch ( tokens.length ) - { - case 2: - // Two tokens means the protocol is HTTP/0.9. - reqProtocol = "HTTP/0.9"; - oneOne = false; - reqMime = false; - break; - case 3: - reqProtocol = tokens[2]; - oneOne = ! reqProtocol.toUpperCase().equals( "HTTP/1.0" ); - reqMime = true; - // Read the rest of the lines. - while ( true ) - { - len = in.readLine( lineBytes, 0, lineBytes.length ); - if ( len == -1 || len == 0 ) - break; - line = new String( lineBytes, 0, len ); - int colonBlank = line.indexOf( ": " ); - if ( colonBlank != -1 ) - { - String name = line.substring( 0, colonBlank ); - String value = line.substring( colonBlank + 2 ); - reqHeaderNames.addElement( name.toLowerCase() ); - reqHeaderValues.addElement( value ); - } - } - break; - default: - problem( "Malformed request line", SC_BAD_REQUEST ); - return; - } - reqMethod = tokens[0]; - reqUriPath = tokens[1]; - - // Check Host: header in HTTP/1.1 requests. - if ( oneOne ) - { - String host = getHeader( "host" ); - if ( host == null ) - { - problem( - "Host header missing on HTTP/1.1 request", - SC_BAD_REQUEST ); - return; - } - // !!! - } - - // Split off query string, if any. - int qmark = reqUriPath.indexOf( '?' ); - if ( qmark != -1 ) - { - reqQuery = reqUriPath.substring( qmark + 1 ); - reqUriPath = reqUriPath.substring( 0, qmark ); - } - - // Decode %-sequences. - reqUriPath = decode( reqUriPath ); - if (reqQuery != null) - reqQuery = decode (reqQuery); - Servlet servlet = (Servlet) serve.registry.get( reqUriPath ); - // maybe the application name without slash? try with slash appended - if (servlet == null) - servlet = (Servlet) serve.registry.get (reqUriPath+"//"); - if (servlet == null) - servlet = serve.defaultServlet; - if ( servlet != null ) - runServlet( (HttpServlet) servlet ); - else if ( "/".equals( reqUriPath )) - sendRedirect (serve.props.getProperty ("rootapp", "base")); - else if ( !reqUriPath.endsWith ("/")) - sendRedirect (reqUriPath+"/"); - else // Not found - sendError (404, "Not Found", - "

If you are looking for a specific app, try /appname.

"+ - "

If the URL was generated by the Hop's href() method "+ - "check if the baseURI property is set correctly in the app's app.properties file.

"); - } - catch ( IOException e ) - { - problem( "Reading request: " + e.getMessage(), SC_BAD_REQUEST ); - } - } - - private void runServlet( HttpServlet servlet ) - { - // Set default response fields. - setStatus( SC_OK ); - setDateHeader( "Date", System.currentTimeMillis() ); - setHeader( - "Server", ServeUtils.serverName + "/" + helma.main.Server.version ); - setHeader( "Connection", "close" ); - try - { - servlet.service( this, this ); - } - catch ( IOException e ) - { - problem( - "IO problem running servlet: " + e.toString(), SC_BAD_REQUEST ); - } - catch ( ServletException e ) - { - problem( - "problem running servlet: " + e.toString(), SC_BAD_REQUEST ); - } - catch ( Exception e ) - { - problem( - "unexpected problem running servlet: " + e.toString(), - SC_INTERNAL_SERVER_ERROR ); - } - } - - private void problem( String logMessage, int resCode ) - { - serve.log( logMessage ); - try - { - sendError( resCode ); - } - catch ( IOException e ) { /* ignore */ } - } - - private String decode( String str ) - { - StringBuffer result = new StringBuffer(); - int l = str.length(); - for ( int i = 0; i < l; ++i ) - { - char c = str.charAt( i ); - if ( c == '%' && i + 2 < l ) - { - char c1 = str.charAt( i + 1 ); - char c2 = str.charAt( i + 2 ); - if ( isHexit( c1 ) && isHexit( c2 ) ) - { - result.append( (char) ( hexit( c1 ) * 16 + hexit( c2 ) ) ); - i += 2; - } - else - result.append( c ); - } - else if ( c == '+' ) - result.append( ' ' ); - else - result.append( c ); - } - return result.toString(); - } - - private boolean isHexit( char c ) - { - String legalChars = "0123456789abcdefABCDEF"; - return ( legalChars.indexOf( c ) != -1 ); - } - - private int hexit( char c ) - { - if ( c >= '0' && c <= '9' ) - return c - '0'; - if ( c >= 'a' && c <= 'f' ) - return c - 'a' + 10; - if ( c >= 'A' && c <= 'F' ) - return c - 'A' + 10; - return 0; // shouldn't happen, we're guarded by isHexit() - } - - - // Methods from ServletRequest. - - /// Returns the size of the request entity data, or -1 if not known. - // Same as the CGI variable CONTENT_LENGTH. - public int getContentLength() - { - return getIntHeader( "content-length" ); - } - - /// Returns the MIME type of the request entity data, or null if - // not known. - // Same as the CGI variable CONTENT_TYPE. - public String getContentType() - { - return getHeader( "content-type" ); - } - - /// Returns the protocol and version of the request as a string of - // the form /.. - // Same as the CGI variable SERVER_PROTOCOL. - public String getProtocol() - { - return reqProtocol; - } - - /// Returns the scheme of the URL used in this request, for example - // "http", "https", or "ftp". Different schemes have different rules - // for constructing URLs, as noted in RFC 1738. The URL used to create - // a request may be reconstructed using this scheme, the server name - // and port, and additional information such as URIs. - public String getScheme() - { - return "http"; - } - - /// Returns the host name of the server as used in the part of - // the request URI. - // Same as the CGI variable SERVER_NAME. - public String getServerName() - { - try - { - return InetAddress.getLocalHost().getHostName(); - } - catch ( UnknownHostException e ) - { - return null; - } - } - - /// Returns the port number on which this request was received as used in - // the part of the request URI. - // Same as the CGI variable SERVER_PORT. - public int getServerPort() - { - return socket.getLocalPort(); - } - - /// Returns the IP address of the agent that sent the request. - // Same as the CGI variable REMOTE_ADDR. - public String getRemoteAddr() - { - return socket.getInetAddress().getHostAddress(); - } - - /// Returns the fully qualified host name of the agent that sent the - // request. - // Same as the CGI variable REMOTE_HOST. - public String getRemoteHost() - { - return socket.getInetAddress().getHostName(); - } - - /// Applies alias rules to the specified virtual path and returns the - // corresponding real path, or null if the translation can not be - // performed for any reason. For example, an HTTP servlet would - // resolve the path using the virtual docroot, if virtual hosting is - // enabled, and with the default docroot otherwise. Calling this - // method with the string "/" as an argument returns the document root. - public String getRealPath( String path ) - { - return serve.getRealPath( path ); - } - - /// Returns an input stream for reading request data. - // @exception IllegalStateException if getReader has already been called - // @exception IOException on other I/O-related errors - public ServletInputStream getInputStream() throws IOException - { - return in; - } - - /// Returns a buffered reader for reading request data. - // @exception UnsupportedEncodingException if the character set encoding isn't supported - // @exception IllegalStateException if getInputStream has already been called - // @exception IOException on other I/O-related errors - public BufferedReader getReader() - { - // !!! - return null; - } - - Hashtable parameters; - - protected void parseParams() { - - // Have we already done it? - if (parameters != null) { - return; - } - - // Parse any query string parameters from the request - Hashtable queryParameters = null; - try { - queryParameters = HttpUtils.parseQueryString(getQueryString()); - } catch (IllegalArgumentException e) { - queryParameters = null; - } - - // Parse any posted parameters in the input stream - Hashtable postParameters = null; - if ("POST".equals(getMethod()) && - "application/x-www-form-urlencoded".equals(getContentType())) { - try { - ServletInputStream is = getInputStream(); - postParameters = - HttpUtils.parsePostData(getContentLength(), in); - } catch (IllegalArgumentException e) { - postParameters = null; - } catch (IOException e) { - postParameters = null; - } - } - - // Handle the simple cases that require no merging - if ((queryParameters == null) && (postParameters == null)) { - parameters = new Hashtable(); - return; - } else if (queryParameters == null) { - parameters = postParameters; - return; - } else if (postParameters == null) { - parameters = queryParameters; - return; - } - - // Merge the parameters retrieved from both sources - Enumeration postKeys = postParameters.keys(); - while (postKeys.hasMoreElements()) { - String postKey = (String) postKeys.nextElement(); - Object postValue = postParameters.get(postKey); - Object queryValue = queryParameters.get(postKey); - if (queryValue == null) { - queryParameters.put(postKey, postValue); - continue; - } - Vector queryValues = new Vector(); - if (queryValue instanceof String) { - queryValues.addElement(queryValue); - } else if (queryValue instanceof String[]) { - String queryArray[] = (String[]) queryValue; - for (int i = 0; i < queryArray.length; i++) { - queryValues.addElement(queryArray[i]); - } - } - if (postValue instanceof String) { - queryValues.addElement(postValue); - } else if (postValue instanceof String[]) { - String postArray[] = (String[]) postValue; - for (int i = 0; i < postArray.length; i++) { - queryValues.addElement(postArray[i]); - } - } - String queryArray[] = new String[queryValues.size()]; - for (int i = 0; i < queryArray.length; i++) { - queryArray[i] = (String) queryValues.elementAt(i); - } - queryParameters.put(postKey, queryArray); - } - parameters = queryParameters; - - } - - - /// Returns the parameter names for this request. - public Enumeration getParameterNames() { - parseParams(); - return parameters.keys(); - } - - /// Returns the value of the specified query string parameter, or null - // if not found. - // @param name the parameter name - public String getParameter(String name) { - - parseParams(); - - Object val = parameters.get(name); - - if (val == null) { - return null; - } else if (val instanceof String[]) { - // It's an array, return the first element - return ((String[])val)[0]; - } else { - // It's a string so return it - return (String) val; - } - } - - /// Returns the values of the specified parameter for the request as an - // array of strings, or null if the named parameter does not exist. - public String[] getParameterValues(String name) { - - parseParams(); - - Object val = parameters.get(name); - - if (val == null) { - return null; - } else if (val instanceof String) { - // It's a string, convert to an array and return - String va[] = {(String) val}; - return va; - } else { - // It's an array so return it - return (String[]) val; - } - } - - /// Returns the value of the named attribute of the request, or null if - // the attribute does not exist. This method allows access to request - // information not already provided by the other methods in this interface. - public Object getAttribute( String name ) - { - // This server does not implement attributes. - return null; - } - - - // Methods from HttpServletRequest. - - /// Gets the array of cookies found in this request. - public Cookie[] getCookies() - { - return parseCookieHeader(getHeader("Cookie")); - } - - /** - * Parse a cookie header into an array of cookies as per - * RFC2109 - HTTP Cookies - * - * @param cookieHdr The Cookie header value. - */ - public Cookie[] parseCookieHeader(String cookieHdr) { - Vector cookieJar = new Vector(); - - if(cookieHdr == null || cookieHdr.length() == 0) - return new Cookie[0]; - - StringTokenizer stok = new StringTokenizer(cookieHdr, "; "); - while (stok.hasMoreTokens()) { - try { - String tok = stok.nextToken(); - int equals_pos = tok.indexOf('='); - if (equals_pos > 0) { - String name = decode(tok.substring(0, equals_pos)); - String value = decode(tok.substring(equals_pos + 1)); - cookieJar.addElement(new Cookie(name, value)); - } - else if ( tok.length() > 0 && equals_pos == -1 ) { - String name = decode(tok); - cookieJar.addElement(new Cookie(name, "")); - } - } catch (IllegalArgumentException badcookie) { - } catch (NoSuchElementException badcookie) { - } - } - - Cookie[] cookies = new Cookie[cookieJar.size()]; - cookieJar.copyInto(cookies); - return cookies; - } - - - /// Returns the method with which the request was made. This can be "GET", - // "HEAD", "POST", or an extension method. - // Same as the CGI variable REQUEST_METHOD. - public String getMethod() - { - return reqMethod; - } - - /// Returns the full request URI. - public String getRequestURI() - { - String portPart = ""; - int port = getServerPort(); - if ( port != 80 ) - portPart = ":" + port; - String queryPart = ""; - String queryString = getQueryString(); - if ( queryString != null && queryString.length() > 0 ) - queryPart = "?" + queryString; - return "http://" + getServerName() + portPart + reqUriPath + queryPart; - } - - /// Returns the part of the request URI that referred to the servlet being - // invoked. - // Analogous to the CGI variable SCRIPT_NAME. - public String getServletPath() - { - // In this server, the entire path is regexp-matched against the - // servlet pattern, so there's no good way to distinguish which - // part refers to the servlet. - return reqUriPath; - } - - /// Returns optional extra path information following the servlet path, but - // immediately preceding the query string. Returns null if not specified. - // Same as the CGI variable PATH_INFO. - public String getPathInfo() - { - // In this server, the entire path is regexp-matched against the - // servlet pattern, so there's no good way to distinguish which - // part refers to the servlet. - return null; - } - - /// Returns extra path information translated to a real path. Returns - // null if no extra path information was specified. - // Same as the CGI variable PATH_TRANSLATED. - public String getPathTranslated() - { - // In this server, the entire path is regexp-matched against the - // servlet pattern, so there's no good way to distinguish which - // part refers to the servlet. - return null; - } - - /// Returns the query string part of the servlet URI, or null if not known. - // Same as the CGI variable QUERY_STRING. - public String getQueryString() - { - return reqQuery; - } - - /// Returns the name of the user making this request, or null if not known. - // Same as the CGI variable REMOTE_USER. - public String getRemoteUser() - { - // This server does not support authentication, so even if a username - // is supplied in the headers we don't want to look at it. - return null; - } - - /// Returns the authentication scheme of the request, or null if none. - // Same as the CGI variable AUTH_TYPE. - public String getAuthType() - { - // This server does not support authentication. - return null; - } - - /// Returns the value of a header field, or null if not known. - // Same as the information passed in the CGI variabled HTTP_*. - // @param name the header field name - public String getHeader( String name ) - { - int i = reqHeaderNames.indexOf( name.toLowerCase() ); - if ( i == -1 ) - return null; - return (String) reqHeaderValues.elementAt( i ); - } - - /// Returns the value of an integer header field. - // @param name the header field name - // @param def the integer value to return if header not found or invalid - public int getIntHeader( String name ) - { - String val = getHeader( name ); - try - { - return Integer.parseInt( val ); - } - catch ( Exception e ) - { - return -1; - } - } - - /// Returns the value of a long header field. - // @param name the header field name - public long getLongHeader( String name ) - { - String val = getHeader( name ); - try - { - return Long.parseLong( val ); - } - catch ( Exception e ) - { - return -1l; - } - } - - /// Returns the value of a date header field. - // @param name the header field name - public long getDateHeader( String name ) - { - String val = getHeader( name ); - try - { - return DateFormat.getDateInstance().parse( val ).getTime(); - } - catch ( Exception e ) - { - return -1l; - } - } - - /// Returns an Enumeration of the header names. - public Enumeration getHeaderNames() - { - return reqHeaderNames.elements(); - } - - // Session stuff. Not implemented, but the API is here for compatibility. - - /// Gets the current valid session associated with this request, if - // create is false or, if necessary, creates a new session for the - // request, if create is true. - //

- // Note: to ensure the session is properly maintained, the servlet - // developer must call this method (at least once) before any output - // is written to the response. - //

- // Additionally, application-writers need to be aware that newly - // created sessions (that is, sessions for which HttpSession.isNew - // returns true) do not have any application-specific state. - public HttpSession getSession( boolean create ) - { - return null; - } - - /// Gets the session id specified with this request. This may differ - // from the actual session id. For example, if the request specified - // an id for an invalid session, then this will get a new session with - // a new id. - public String getRequestedSessionId() - { - String sid = ServeUtils.getCookie (this, "HopSession"); - if (sid == null) { - sid = Long.toString (Math.round (Math.random ()*Long.MAX_VALUE), 16); - ServeUtils.setCookie (this, "HopSession", sid); - } - return sid; - } - - /// Checks whether this request is associated with a session that is - // valid in the current session context. If it is not valid, the - // requested session will never be returned from the getSession - // method. - public boolean isRequestedSessionIdValid() - { - return false; - } - - /// Checks whether the session id specified by this request came in as - // a cookie. (The requested session may not be one returned by the - // getSession method.) - public boolean isRequestedSessionIdFromCookie() - { - return false; - } - - /// Checks whether the session id specified by this request came in as - // part of the URL. (The requested session may not be the one returned - // by the getSession method.) - public boolean isRequestedSessionIdFromUrl() - { - return false; - } - - - // Methods from ServletResponse. - - /// Sets the content length for this response. - // @param length the content length - public void setContentLength( int length ) - { - setIntHeader( "Content-length", length ); - } - - /// Sets the content type for this response. - // @param type the content type - public void setContentType( String type ) - { - setHeader( "Content-type", type ); - } - - /// Returns an output stream for writing response data. - public ServletOutputStream getOutputStream() - { - return out; - } - - /// Returns a print writer for writing response data. The MIME type of - // the response will be modified, if necessary, to reflect the character - // encoding used, through the charset=... property. This means that the - // content type must be set before calling this method. - // @exception UnsupportedEncodingException if no such encoding can be provided - // @exception IllegalStateException if getOutputStream has been called - // @exception IOException on other I/O errors - public PrintWriter getWriter() throws IOException - { - // !!! - return new PrintWriter (new OutputStreamWriter (out, "ISO8859_1")); - } - - /// Returns the character set encoding used for this MIME body. The - // character encoding is either the one specified in the assigned - // content type, or one which the client understands. If no content - // type has yet been assigned, it is implicitly set to text/plain. - public String getCharacterEncoding() - { - // !!! - return null; - } - - - // Methods from HttpServletResponse. - - /// Adds the specified cookie to the response. It can be called - // multiple times to set more than one cookie. - public void addCookie( Cookie cookie ) - { - cookies.addElement( cookie ); - } - - /// Checks whether the response message header has a field with the - // specified name. - public boolean containsHeader( String name ) - { - return resHeaderNames.contains( name ); - } - - private int resCode = -1; - private String resMessage = null; - private Vector resHeaderNames = new Vector(); - private Vector resHeaderValues = new Vector(); - - /// Sets the status code and message for this response. - // @param resCode the status code - // @param resMessage the status message - public void setStatus( int resCode, String resMessage ) - { - this.resCode = resCode; - this.resMessage = resMessage; - } - - /// Sets the status code and a default message for this response. - // @param resCode the status code - public void setStatus( int resCode ) - { - switch ( resCode ) - { - case SC_CONTINUE: setStatus( resCode, "Continue" ); break; - case SC_SWITCHING_PROTOCOLS: - setStatus( resCode, "Switching protocols" ); break; - case SC_OK: setStatus( resCode, "Ok" ); break; - case SC_CREATED: setStatus( resCode, "Created" ); break; - case SC_ACCEPTED: setStatus( resCode, "Accepted" ); break; - case SC_NON_AUTHORITATIVE_INFORMATION: - setStatus( resCode, "Non-authoritative" ); break; - case SC_NO_CONTENT: setStatus( resCode, "No content" ); break; - case SC_RESET_CONTENT: setStatus( resCode, "Reset content" ); break; - case SC_PARTIAL_CONTENT: - setStatus( resCode, "Partial content" ); break; - case SC_MULTIPLE_CHOICES: - setStatus( resCode, "Multiple choices" ); break; - case SC_MOVED_PERMANENTLY: - setStatus( resCode, "Moved permanentently" ); break; - case SC_MOVED_TEMPORARILY: - setStatus( resCode, "Moved temporarily" ); break; - case SC_SEE_OTHER: setStatus( resCode, "See other" ); break; - case SC_NOT_MODIFIED: setStatus( resCode, "Not modified" ); break; - case SC_USE_PROXY: setStatus( resCode, "Use proxy" ); break; - case SC_BAD_REQUEST: setStatus( resCode, "Bad request" ); break; - case SC_UNAUTHORIZED: setStatus( resCode, "Unauthorized" ); break; - case SC_PAYMENT_REQUIRED: - setStatus( resCode, "Payment required" ); break; - case SC_FORBIDDEN: setStatus( resCode, "Forbidden" ); break; - case SC_NOT_FOUND: setStatus( resCode, "Not found" ); break; - case SC_METHOD_NOT_ALLOWED: - setStatus( resCode, "Method not allowed" ); break; - case SC_NOT_ACCEPTABLE: - setStatus( resCode, "Not acceptable" ); break; - case SC_PROXY_AUTHENTICATION_REQUIRED: - setStatus( resCode, "Proxy auth required" ); break; - case SC_REQUEST_TIMEOUT: - setStatus( resCode, "Request timeout" ); break; - case SC_CONFLICT: setStatus( resCode, "Conflict" ); break; - case SC_GONE: setStatus( resCode, "Gone" ); break; - case SC_LENGTH_REQUIRED: - setStatus( resCode, "Length required" ); break; - case SC_PRECONDITION_FAILED: - setStatus( resCode, "Precondition failed" ); break; - case SC_REQUEST_ENTITY_TOO_LARGE: - setStatus( resCode, "Request entity too large" ); break; - case SC_REQUEST_URI_TOO_LONG: - setStatus( resCode, "Request URI too large" ); break; - case SC_UNSUPPORTED_MEDIA_TYPE: - setStatus( resCode, "Unsupported media type" ); break; - case SC_INTERNAL_SERVER_ERROR: - setStatus( resCode, "Internal server error" ); break; - case SC_NOT_IMPLEMENTED: - setStatus( resCode, "Not implemented" ); break; - case SC_BAD_GATEWAY: setStatus( resCode, "Bad gateway" ); break; - case SC_SERVICE_UNAVAILABLE: - setStatus( resCode, "Service unavailable" ); break; - case SC_GATEWAY_TIMEOUT: - setStatus( resCode, "Gateway timeout" ); break; - case SC_HTTP_VERSION_NOT_SUPPORTED: - setStatus( resCode, "HTTP version not supported" ); break; - default: setStatus( resCode, "" ); break; - } - } - - /// Sets the value of a header field. - // @param name the header field name - // @param value the header field value - public void setHeader( String name, String value ) - { - resHeaderNames.addElement( name ); - resHeaderValues.addElement( value ); - } - - /// Sets the value of an integer header field. - // @param name the header field name - // @param value the header field integer value - public void setIntHeader( String name, int value ) - { - setHeader( name, Integer.toString( value ) ); - } - - /// Sets the value of a long header field. - // @param name the header field name - // @param value the header field long value - public void setLongHeader( String name, long value ) - { - setHeader( name, Long.toString( value ) ); - } - - /// Sets the value of a date header field. - // @param name the header field name - // @param value the header field date value - public void setDateHeader( String name, long value ) - { - setHeader( name, to1123String( new Date( value ) ) ); - } - - private static final String[] weekdays = - { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; - - /// Converts a Date into an RFC-1123 string. - private static String to1123String( Date date ) - { - // We have to go through some machinations here to get the - // correct day of the week in GMT. getDay() gives the day in - // local time. getDate() gives the day of the month in local - // time. toGMTString() gives a formatted string in GMT. So, we - // extract the day of the month from the GMT string, and if it - // doesn't match the local one we change the local day of the - // week accordingly. - // - // The Date class sucks. - int localDay = date.getDay(); - int localDate = date.getDate(); - String gmtStr = date.toGMTString(); - int blank = gmtStr.indexOf( ' ' ); - int gmtDate = Integer.parseInt( gmtStr.substring( 0, blank ) ); - int gmtDay; - if ( gmtDate > localDate || ( gmtDate < localDate && gmtDate == 1 ) ) - gmtDay = ( localDay + 1 ) % 7; - else if ( localDate > gmtDate || ( localDate < gmtDate && localDate == 1 ) ) - gmtDay = ( localDay + 6 ) % 7; - else - gmtDay = localDay; - return weekdays[gmtDay] + ( gmtDate < 10 ? ", 0" : ", " ) + gmtStr; - } - - private boolean headersWritten = false; - - /// Writes the status line and message headers for this response to the - // output stream. - // @exception IOException if an I/O error has occurred - void writeHeaders() throws IOException - { - if ( headersWritten ) - return; - headersWritten = true; - if ( reqMime ) - { - out.println( reqProtocol + " " + resCode + " " + resMessage ); - for ( int i = 0; i < resHeaderNames.size(); ++i ) - { - String name = (String) resHeaderNames.elementAt( i ); - String value = (String) resHeaderValues.elementAt( i ); - if ( value != null ) // just in case - out.println( name + ": " + value ); - } - writeCookies(); - out.println( "" ); - out.flush(); - } - } - - void writeCookies() throws IOException - { - // Send the cookies - Enumeration enum = cookies.elements(); - while (enum.hasMoreElements()) - { - Cookie cookie = (Cookie) enum.nextElement(); - String cookieHdr = "Set-Cookie: " + encodeCookie(cookie); - out.println(cookieHdr); - } - } - - /// Encode Cookie. Borrowed from Apache JServ. - private static SimpleDateFormat cookieDate = - new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss zz", Locale.US ); - public static String encodeCookie(Cookie cookie) { - StringBuffer buf = new StringBuffer( cookie.getName() ); - buf.append('='); - buf.append(cookie.getValue()); - - long age = cookie.getMaxAge(); - if (age > 0) { - buf.append("; expires="); - buf.append(cookieDate.format( - new Date(System.currentTimeMillis() + (long)age * 1000 ))); - } else if (age == 0) { - buf.append("; expires="); - // Set expiration to the epoch to delete the cookie - buf.append(cookieDate.format(new Date(0))); - } - - if (cookie.getDomain() != null) { - buf.append("; domain="); - buf.append(cookie.getDomain()); - } - - if (cookie.getPath() != null) { - buf.append("; path="); - buf.append(cookie.getPath()); - } - - if (cookie.getSecure()) { - buf.append("; secure"); - } - - return buf.toString(); - } - - /// Writes an error response using the specified status code and message. - // @param resCode the status code - // @param resMessage the status message - // @exception IOException if an I/O error has occurred - public void sendError( int resCode, String resMessage, String resBody ) throws IOException - { - setStatus( resCode, resMessage ); - realSendError(resBody); - } - - /// Writes an error response using the specified status code and message. - // @param resCode the status code - // @param resMessage the status message - // @exception IOException if an I/O error has occurred - public void sendError( int resCode, String resMessage ) throws IOException - { - setStatus( resCode, resMessage ); - realSendError(null); - } - - /// Writes an error response using the specified status code and a default - // message. - // @param resCode the status code - // @exception IOException if an I/O error has occurred - public void sendError( int resCode ) throws IOException - { - setStatus( resCode ); - realSendError(null); - } - - private void realSendError( String resBody ) throws IOException - { - setContentType( "text/html" ); - out.println( "" ); - out.println( "" + resCode + " " + resMessage + "" ); - out.println( "" ); - out.println( "

" + resCode + " " + resMessage + "

" ); - if (resBody != null) - out.println (resBody); - out.println( "
" ); - ServeUtils.writeAddress( out ); - out.println( "" ); - out.flush(); - } - - /// Sends a redirect message to the client using the specified redirect - // location URL. - // @param location the redirect location URL - // @exception IOException if an I/O error has occurred - public void sendRedirect( String location ) throws IOException - { - setHeader( "Location", location ); - sendError (SC_MOVED_TEMPORARILY); - } - - // URL session-encoding stuff. Not implemented, but the API is here - // for compatibility. - - /// Encodes the specified URL by including the session ID in it, or, if - // encoding is not needed, returns the URL unchanged. The - // implementation of this method should include the logic to determine - // whether the session ID needs to be encoded in the URL. For example, - // if the browser supports cookies, or session tracking is turned off, - // URL encoding is unnecessary. - //

- // All URLs emitted by a Servlet should be run through this method. - // Otherwise, URL rewriting cannot be used with browsers which do not - // support cookies. - public String encodeUrl( String url ) - { - return url; - } - - /// Encodes the specified URL for use in the sendRedirect method or, if - // encoding is not needed, returns the URL unchanged. The - // implementation of this method should include the logic to determine - // whether the session ID needs to be encoded in the URL. Because the - // rules for making this determination differ from those used to - // decide whether to encode a normal link, this method is seperate - // from the encodeUrl method. - //

- // All URLs sent to the HttpServletResponse.sendRedirect method should be - // run through this method. Otherwise, URL rewriting cannot be used with - // browsers which do not support cookies. - public String encodeRedirectUrl( String url ) - { - return url; - } - - } - - -class ServeInputStream extends ServletInputStream - { - - private InputStream in; - - public ServeInputStream( InputStream in ) - { - this.in = in; - } - - public int readLine( byte[] b, int off, int len ) throws IOException - { - int off2 = off; - while ( off2 - off < len ) - { - int r = read(); - if ( r == -1 ) - { - if (off2 == off ) - return -1; - break; - } - if ( r == 13 ) - continue; - if ( r == 10 ) - break; - b[off2] = (byte) r; - ++off2; - } - return off2 - off; - } - - public int read() throws IOException - { - return in.read(); - } - - public int read( byte[] b, int off, int len ) throws IOException - { - return in.read( b, off, len ); - } - - public int available() throws IOException - { - return in.available(); - } - - public void close() throws IOException - { - in.close(); - } - - } - - -class ServeOutputStream extends ServletOutputStream - { - - private OutputStream out; - private ServeConnection conn; - - public ServeOutputStream( OutputStream out, ServeConnection conn ) - { - this.out = out; - this.conn = conn; - } - - public void write( int b ) throws IOException - { - conn.writeHeaders(); - out.write( b ); - } - - public void write( byte[] b, int off, int len ) throws IOException - { - conn.writeHeaders(); - out.write( b, off, len ); - } - - public void flush() throws IOException - { - conn.writeHeaders(); - out.flush(); - } - - public void close() throws IOException - { - conn.writeHeaders(); - out.close(); - } - - public void print( String s ) throws IOException - { - conn.writeHeaders(); - out.write( s.getBytes() ); - } - - public void print( int i ) throws IOException - { - conn.writeHeaders(); - out.write( Integer.toString(i).getBytes() ); - } - - public void print( long l ) throws IOException - { - conn.writeHeaders(); - out.write( Long.toString(l).getBytes() ); - } - - public void println( String s ) throws IOException - { - conn.writeHeaders(); - out.write( s.getBytes() ); - out.write ("\r\n".getBytes()); - } - - public void println( int i ) throws IOException - { - conn.writeHeaders(); - out.write( Integer.toString(i).getBytes() ); - out.write ("\r\n".getBytes()); - } - - public void println( long l ) throws IOException - { - conn.writeHeaders(); - out.write( Long.toString(l).getBytes() ); - out.write ("\r\n".getBytes()); - } - - public void println() throws IOException - { - conn.writeHeaders(); - out.write ("\r\n".getBytes()); - } - - } diff --git a/src/Acme/Serve/ServeUtils.java b/src/Acme/Serve/ServeUtils.java deleted file mode 100644 index d1c73264..00000000 --- a/src/Acme/Serve/ServeUtils.java +++ /dev/null @@ -1,95 +0,0 @@ -// ServeUtils - static utilities for minimal Java HTTP server -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.Serve; - -import java.io.*; -import java.util.*; -import javax.servlet.*; -import javax.servlet.http.*; - -/// Static utilities for minimal Java HTTP server. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class ServeUtils - { - - // Server identification. - public static final String serverName = "Helma"; - // we're using the server version from helma.main.Server class. - // public static final String serverVersion = "1.2 p1"; - public static final String serverUrl = "http://helma.org/"; - - /// Write a standard-format HTML address for this server. - public static void writeAddress( OutputStream o ) throws IOException - { - PrintStream p = new PrintStream( o ); - p.println( - "

" + - serverName + " " + helma.main.Server.version + "
" ); - } - - - /// Get a cookie of a given name. - public static String getCookie( HttpServletRequest req, String name ) - { - String h = req.getHeader( "Cookie" ); - if ( h == null ) - return null; - StringTokenizer st = new StringTokenizer( h, "; " ); - while ( st.hasMoreTokens() ) - { - String tk = st.nextToken(); - int eq = tk.indexOf( '=' ); - String n, v; - if ( eq == -1 ) - { - n = tk; - v = ""; - } - else - { - n = tk.substring( 0, eq ); - v = tk.substring( eq + 1 ); - } - if ( name.equals( n ) ) - return v; - } - return null; - } - - /// Set a cookie. - public static void setCookie( HttpServletResponse res, String name, String value ) - { - res.setHeader( "Set-Cookie", name + "=" + value ); - } - - } - diff --git a/src/Acme/Serve/TestServlet.java b/src/Acme/Serve/TestServlet.java deleted file mode 100644 index c002a76e..00000000 --- a/src/Acme/Serve/TestServlet.java +++ /dev/null @@ -1,132 +0,0 @@ -// TestServlet - simple servlet that tests the Servlet API -// -// Copyright (C) 1996,1998 by Jef Poskanzer . 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 Acme.Serve; - -import java.io.*; -import java.util.*; -import javax.servlet.*; -import javax.servlet.http.*; - -/// Simple servlet that tests the Servlet API. -// Sample output: -//
-// getContentLength(): -1
-// getContentType(): null
-// getProtocol(): HTTP/1.0
-// getScheme(): http
-// getServerName(): www.acme.com
-// getServerPort(): 1234
-// getRemoteAddr(): 192.100.66.1
-// getRemoteHost(): acme.com
-// getMethod(): GET
-// getRequestURI(): http://www.acme.com:1234/TestServlet?foo=bar
-// getServletPath(): /TestServlet
-// getPathInfo(): null
-// getPathTranslated(): null
-// getQueryString(): foo=bar
-// getRemoteUser(): null
-// getAuthType(): null
-// 
-// Parameters:
-//     foo = bar
-// 
-// Header:
-//     accept: text/html, image/gif, image/jpeg, *; q=.2
-//     user-agent: Java1.0.2
-// 
-// Fetch the software.
-// Fetch the entire Acme package. - -public class TestServlet extends HttpServlet - { - - /// Returns a string containing information about the author, version, and - // copyright of the servlet. - public String getServletInfo() - { - return "simple servlet that tests the Servlet API"; - } - - /// Services a single request from the client. - // @param req the servlet request - // @param req the servlet response - // @exception ServletException when an exception has occurred - public void service( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException - { - Enumeration en; - log( "called" ); - res.setStatus( HttpServletResponse.SC_OK ); - res.setContentType( "text/html" ); - ServletOutputStream p = res.getOutputStream(); - p.println( "" ); - p.println( "Test Servlet Output" ); - p.println( "" ); - p.println( "

Test Servlet Output

" ); - p.println( "
" ); - p.println( "
" );
-	p.println( "getContentLength(): " + req.getContentLength() );
-	p.println( "getContentType(): " + req.getContentType() );
-	p.println( "getProtocol(): " + req.getProtocol() );
-	p.println( "getScheme(): " + req.getScheme() );
-	p.println( "getServerName(): " + req.getServerName() );
-	p.println( "getServerPort(): " + req.getServerPort() );
-	p.println( "getRemoteAddr(): " + req.getRemoteAddr() );
-	p.println( "getRemoteHost(): " + req.getRemoteHost() );
-	p.println( "getMethod(): " + req.getMethod() );
-	p.println( "getRequestURI(): " + req.getRequestURI() );
-	p.println( "getServletPath(): " + req.getServletPath() );
-	p.println( "getPathInfo(): " + req.getPathInfo() );
-	p.println( "getPathTranslated(): " + req.getPathTranslated() );
-	p.println( "getQueryString(): " + req.getQueryString() );
-	p.println( "getRemoteUser(): " + req.getRemoteUser() );
-	p.println( "getAuthType(): " + req.getAuthType() );
-	p.println( "" );
-	p.println( "Parameters:" );
-	en = req.getParameterNames();
-	while ( en.hasMoreElements() )
-	    {
-	    String name = (String) en.nextElement();
-	    p.println( "    " + name + " = " + req.getParameter( name ) );
-	    }
-	p.println( "" );
-	p.println( "Headers:" );
-	en = req.getHeaderNames();
-	while ( en.hasMoreElements() )
-	    {
-	    String name = (String) en.nextElement();
-	    p.println( "    " + name + ": " + req.getHeader( name ) );
-	    }
-	p.println( "
" ); - p.println( "
" ); - p.println( "" ); - p.flush(); - p.close(); - } - - } diff --git a/src/Acme/Serve/ThrottleItem.java b/src/Acme/Serve/ThrottleItem.java deleted file mode 100644 index 69ca4651..00000000 --- a/src/Acme/Serve/ThrottleItem.java +++ /dev/null @@ -1,55 +0,0 @@ -// ThrottleItem - data item for ThrottledOutputStream -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme.Serve; - -import java.io.*; -import java.util.*; - -/// Data item for ThrottledOutputStream. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class ThrottleItem - { - - private long maxBps; - - /// Constructor. - public ThrottleItem( long maxBps ) - { - this.maxBps = maxBps; - } - - public long getMaxBps() - { - return maxBps; - } - - } diff --git a/src/Acme/Serve/ThrottledOutputStream.java b/src/Acme/Serve/ThrottledOutputStream.java deleted file mode 100644 index b8896647..00000000 --- a/src/Acme/Serve/ThrottledOutputStream.java +++ /dev/null @@ -1,156 +0,0 @@ -// ThrottledOutputStream - output stream with throttling -// -// Copyright (C)1996,1998 by Jef Poskanzer . 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 Acme.Serve; - -import java.io.*; -import java.util.*; - -/// Output stream with throttling. -//

-// Restricts output to a specified rate. Also includes a static utility -// routine for parsing a file of throttle settings. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class ThrottledOutputStream extends FilterOutputStream - { - - /// Parses a standard throttle file. - //

- // A throttle file lets you set maximum byte rates on filename patterns. - // The format of the throttle file is very simple. A # starts a - // comment, and the rest of the line is ignored. Blank lines are ignored. - // The rest of the lines should consist of a pattern, whitespace, and a - // number. The pattern is a simple shell-style filename pattern, using - // ? and *, or multiple such patterns separated by |. - //

- // The numbers in the file are byte rates, specified in units of bytes - // per second. For comparison, a v.32b/v.42b modem gives about - // 1500/2000 B/s depending on compression, a double-B-channel ISDN line - // about 12800 B/s, and a T1 line is about 150000 B/s. - //

- // Example: - //

-    // # throttle file for www.acme.com
-    // *               100000  # limit total web usage to 2/3 of our T1
-    // *.jpg|*.gif     50000   # limit images to 1/3 of our T1
-    // *.mpg           20000   # and movies to even less
-    // jef/*           20000   # jef's pages are too popular
-    // 
- //

- // The routine returns a WildcardDictionary. Do a lookup in this - // dictionary using a filename, and you'll get back a ThrottleItem - // containing the corresponding byte rate. - public static Acme.WildcardDictionary parseThrottleFile( String filename ) throws IOException - { - Acme.WildcardDictionary wcd = new Acme.WildcardDictionary(); - BufferedReader br = new BufferedReader( new FileReader( filename ) ); - while ( true ) - { - String line = br.readLine(); - if ( line == null ) - break; - int i = line.indexOf( '#' ); - if ( i != -1 ) - line = line.substring( 0, i ); - line = line.trim(); - if ( line.length() == 0 ) - continue; - String[] words = Acme.Utils.splitStr( line ); - if ( words.length != 2 ) - throw new IOException( "malformed throttle line: " + line ); - try - { - wcd.put( - words[0], new ThrottleItem( Long.parseLong( words[1] ) ) ); - } - catch ( NumberFormatException e ) - { - throw new IOException( - "malformed number in throttle line: " + line ); - } - } - br.close(); - return wcd; - } - - - private long maxBps; - private long bytes; - private long start; - - /// Constructor. - public ThrottledOutputStream( OutputStream out, long maxBps ) - { - super( out ); - this.maxBps = maxBps; - bytes = 0; - start = System.currentTimeMillis(); - } - - private byte[] oneByte = new byte[1]; - - /// Writes a byte. This method will block until the byte is actually - // written. - // @param b the byte to be written - // @exception IOException if an I/O error has occurred - public void write( int b ) throws IOException - { - oneByte[0] = (byte) b; - write( oneByte, 0, 1 ); - } - - /// Writes a subarray of bytes. - // @param b the data to be written - // @param off the start offset in the data - // @param len the number of bytes that are written - // @exception IOException if an I/O error has occurred - public void write( byte b[], int off, int len ) throws IOException - { - // Check the throttle. - bytes += len; - long elapsed = System.currentTimeMillis() - start; - long bps = bytes * 1000L / elapsed; - if ( bps > maxBps ) - { - // Oops, sending too fast. - long wakeElapsed = bytes * 1000L / maxBps; - try - { - Thread.sleep( wakeElapsed - elapsed ); - } - catch ( InterruptedException ignore ) {} - } - - // Write the bytes. - out.write( b, off, len ); - } - - } diff --git a/src/Acme/Utils.java b/src/Acme/Utils.java deleted file mode 100644 index 6adf82ef..00000000 --- a/src/Acme/Utils.java +++ /dev/null @@ -1,1053 +0,0 @@ -// Utils - assorted static utility routines -// -// Copyright (C)1996,1998 by Jef Poskanzer . 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 Acme; - -import java.util.*; -import java.io.*; -import java.net.*; - -/// Assorted static utility routines. -//

-// Whenever I come up with a static routine that might be of general use, -// I put it here. So far the class includes: -//

    -//
  • some string routines that were left out of java.lang.String -//
  • a general array-to-string routine -//
  • a fixed version of java.io.InputStream's byte-array read routine -//
  • a bunch of URL-hacking routines -//
  • some easy-to-use wrappers for Runtime.exec -//
  • a debugging routine to dump the current call stack -//
  • a URLDecoder to match java.net.URLEncoder -//
-// and lots more. -//

-// Fetch the software.
-// Fetch the entire Acme package. - -public class Utils - { - - /// Returns a date string formatted in Unix ls style - if it's within - // six months of now, Mmm dd hh:ss, else Mmm dd yyyy. - public static String lsDateStr( Date date ) - { - Calendar cal = new GregorianCalendar(); - cal.setTime( date ); - long dateTime = date.getTime(); - if ( dateTime == -1L ) - return "------------"; - long nowTime = (new Date()).getTime(); - String[] months = { - "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; - String part1 = - months[cal.get(Calendar.MONTH)] + - Fmt.fmt( cal.get(Calendar.DATE), 3 ); - if ( Math.abs( nowTime - dateTime ) < 183L * 24L * 60L * 60L * 1000L ) - return part1 + Fmt.fmt( cal.get(Calendar.HOUR_OF_DAY), 3 ) + ":" + - Fmt.fmt( cal.get(Calendar.MINUTE), 2, Fmt.ZF ); - else - return part1 + Fmt.fmt( cal.get(Calendar.YEAR), 6 ); - } - - - /// Returns "s" for numbers other than one, and "" for one. - public static String pluralStr( long n ) - { - if ( n == 1 ) - return ""; - else - return "s"; - } - - - // Various interval constants. Some are only approximate. - public static final long INT_SECOND = 1000L; - public static final long INT_MINUTE = INT_SECOND * 60L; - public static final long INT_HOUR = INT_MINUTE * 60L; - public static final long INT_DAY = INT_HOUR * 24L; - public static final long INT_WEEK = INT_DAY * 7L; - public static final long INT_MONTH = INT_DAY * 30L; - public static final long INT_YEAR = INT_DAY * 365L; - public static final long INT_DECADE = INT_DAY * 3652L; - - /// Returns a string approximately describing a given time interval. - // @param interval the interval, in milliseconds - public static String intervalStr( long interval ) - { - long decades, years, months, weeks, days, hours, minutes, seconds, millis; - - decades = interval / INT_DECADE; - interval -= decades * INT_DECADE; - years = interval / INT_YEAR; - interval -= years * INT_YEAR; - months = interval / INT_MONTH; - interval -= months * INT_MONTH; - weeks = interval / INT_WEEK; - interval -= weeks * INT_WEEK; - days = interval / INT_DAY; - interval -= days * INT_DAY; - hours = interval / INT_HOUR; - interval -= hours * INT_HOUR; - minutes = interval / INT_MINUTE; - interval -= minutes * INT_MINUTE; - seconds = interval / INT_SECOND; - interval -= seconds * INT_SECOND; - millis = interval; - - if ( decades > 0 ) - if ( years == 0 ) - return decades + " decade" + pluralStr( decades ); - else - return - decades + " decade" + pluralStr( decades ) + ", " + - years + " years" + pluralStr( years ); - else if ( years > 0 ) - if ( months == 0 ) - return years + " year" + pluralStr( years ); - else - return - years + " year" + pluralStr( years ) + ", " + - months + " month" + pluralStr( months ); - else if ( months > 0 ) - if ( weeks == 0 ) - return months + " month" + pluralStr( months ); - else - return - months + " month" + pluralStr( months ) + ", " + - weeks + " week" + pluralStr( weeks ); - else if ( weeks > 0 ) - if ( days == 0 ) - return weeks + " week" + pluralStr( weeks ); - else - return - weeks + " week" + pluralStr( weeks ) + ", " + - days + " day" + pluralStr( days ); - else if ( days > 0 ) - if ( hours == 0 ) - return days + " day" + pluralStr( days ); - else - return - days + " day" + pluralStr( days ) + ", " + - hours + " hour" + pluralStr( hours ); - else if ( hours > 0 ) - if ( minutes == 0 ) - return hours + " hour" + pluralStr( hours ); - else - return - hours + " hour" + pluralStr( hours ) + ", " + - minutes + " minute" + pluralStr( minutes ); - else if ( minutes > 0 ) - if ( seconds == 0 ) - return minutes + " minute" + pluralStr( minutes ); - else - return - minutes + " minute" + pluralStr( minutes ) + ", " + - seconds + " second" + pluralStr( seconds ); - else if ( seconds > 0 ) - if ( millis == 0 ) - return seconds + " second" + pluralStr( seconds ); - else - return - seconds + " second" + pluralStr( seconds ) + ", " + - millis + " millisecond" + pluralStr( millis ); - else - return millis + " millisecond" + pluralStr( millis ); - } - - - /// Returns the length of the initial segment of str which consists - // entirely of characters from charSet. - public static int strSpan( String str, String charSet ) - { - return strSpan( str, charSet, 0 ); - } - - /// Returns the length of the initial segment of str which consists - // entirely of characters from charSet, starting at the given index. - public static int strSpan( String str, String charSet, int fromIdx ) - { - int i; - for ( i = fromIdx; i < str.length(); ++i ) - if ( charSet.indexOf( str.charAt( i ) ) == -1 ) - break; - return i - fromIdx; - } - - /// Returns the length of the initial segment of str which consists - // entirely of characters NOT from charSet. - public static int strCSpan( String str, String charSet ) - { - return strCSpan( str, charSet, 0 ); - } - - /// Returns the length of the initial segment of str which consists - // entirely of characters NOT from charSet, starting at the given index. - public static int strCSpan( String str, String charSet, int fromIdx ) - { - int i; - for ( i = fromIdx; i < str.length(); ++i ) - if ( charSet.indexOf( str.charAt( i ) ) != -1 ) - break; - return i - fromIdx; - } - - /// Checks whether a string matches a given wildcard pattern. - // Only does ? and *, and multiple patterns separated by |. - public static boolean match( String pattern, String string ) - { - for ( int p = 0; ; ++p ) - { - for ( int s = 0; ; ++p, ++s ) - { - boolean sEnd = ( s >= string.length() ); - boolean pEnd = ( p >= pattern.length() || - pattern.charAt( p ) == '|' ); - if ( sEnd && pEnd ) - return true; - if ( sEnd || pEnd ) - break; - if ( pattern.charAt( p ) == '?' ) - continue; - if ( pattern.charAt( p ) == '*' ) - { - int i; - ++p; - for ( i = string.length(); i >= s; --i ) - if ( match( - pattern.substring( p ), - string.substring( i ) ) ) /* not quite right */ - return true; - break; - } - if ( pattern.charAt( p ) != string.charAt( s ) ) - break; - } - p = pattern.indexOf( '|', p ); - if ( p == -1 ) - return false; - } - } - -// /// Finds the maximum length of a string that matches a given wildcard -// // pattern. Only does ? and *, and multiple patterns separated by |. -// public static int matchSpan( String pattern, String string ) -// { -// // !!! -// return 0; -// } - - /// Returns the length of the initial segment of str1 that equals str2. - public static int sameSpan( String str1, String str2 ) - { - int i; - for ( i = 0; - i < str1.length() && i < str2.length() && - str1.charAt( i ) == str2.charAt( i ); - ++i ) - ; - return i; - } - - /// Returns the number of times the given character appears in the string. - public static int charCount( String str, char c ) - { - int n = 0; - for ( int i = 0; i < str.length(); ++i ) - if ( str.charAt( i ) == c ) - ++n; - return n; - } - - - /// Turns a String into an array of Strings, by using StringTokenizer - // to split it up at whitespace. - public static String[] splitStr( String str ) - { - StringTokenizer st = new StringTokenizer( str ); - int n = st.countTokens(); - String[] strs = new String[n]; - for ( int i = 0; i < n; ++i ) - strs[i] = st.nextToken(); - return strs; - } - - /// Turns a String into an array of Strings, by splitting it at - // the specified character. This does not use StringTokenizer, - // and therefore can handle empty fields. - public static String[] splitStr( String str, char delim ) - { - int n = 1; - int index = -1; - while ( true ) - { - index = str.indexOf( delim, index + 1 ); - if ( index == -1 ) - break; - ++n; - } - String[] strs = new String[n]; - index = -1; - for ( int i = 0; i < n - 1; ++i ) - { - int nextIndex = str.indexOf( delim, index + 1 ); - strs[i] = str.substring( index + 1, nextIndex ); - index = nextIndex; - } - strs[n - 1] = str.substring( index + 1 ); - return strs; - } - - /// Turns an array of Strings into a single String, with the components - // separated by spaces. - public static String flattenStrarr( String[] strs ) - { - StringBuffer sb = new StringBuffer(); - for ( int i = 0; i < strs.length; ++i ) - { - if ( i > 0 ) - sb.append( ' ' ); - sb.append( strs[i] ); - } - return sb.toString(); - } - - /// Sorts an array of Strings. - // Java currently has no general sort function. Sorting Strings is - // common enough that it's worth making a special case. - public static void sortStrings( String[] strings ) - { - // Just does a bubblesort. - for ( int i = 0; i < strings.length - 1; ++i ) - { - for ( int j = i + 1; j < strings.length; ++j ) - { - if ( strings[i].compareTo( strings[j] ) > 0 ) - { - String t = strings[i]; - strings[i] = strings[j]; - strings[j] = t; - } - } - } - } - - /// Locates a String in an array of Strings. - // Returns -1 if the String is not found. - public static int indexOfString( String[] strings, String string ) - { - for ( int i = 0; i < strings.length; ++i ) - if ( string.equals( strings[i] ) ) - return i; - return -1; - } - - /// Locates a String in an array of Strings, ignoring case. - // Returns -1 if the String is not found. - public static int indexOfStringIgnoreCase( String[] strings, String string ) - { - for ( int i = 0; i < strings.length; ++i ) - if ( string.equalsIgnoreCase( strings[i] ) ) - return i; - return -1; - } - - /// Compares two arrays of Strings for equality. - public static boolean equalsStrings( String[] strings1, String[] strings2 ) - { - if ( strings1.length != strings2.length ) - return false; - for ( int i = 0; i < strings1.length; ++i ) - if ( ! strings1[i].equals( strings2[i] ) ) - return false; - return true; - } - - - /// Returns the number a raised to the power of b. Long version - // of Math.pow(). Throws ArithmeticException if b is negative. - public static long pow( long a, long b ) throws ArithmeticException - { - if ( b < 0 ) - throw new ArithmeticException(); - long r = 1; - while ( b != 0 ) - { - if ( odd( b ) ) - r *= a; - b >>>= 1; - a *= a; - } - return r; - } - - - /// Parse an integer, returning a default value on errors. - public static int parseInt( String str, int def ) - { - try - { - return Integer.parseInt( str ); - } - catch ( Exception e ) - { - return def; - } - } - - /// Parse a long, returning a default value on errors. - public static long parseLong( String str, long def ) - { - try - { - return Long.parseLong( str ); - } - catch ( Exception e ) - { - return def; - } - } - - - /// An array-to-String routine. Handles arrays of arbitrary - // type, including nested arrays. Sample output: - //

-    // byte[]:    { (byte)0, (byte)1, (byte)2 }
-    // char[]:    { '0', '1', '2' }
-    // short[]:   { (short)0, (short)1, (short)2 }
-    // int[]:     { 0, 1, 2 }
-    // long[]:    { 0L, 1L, 2L }
-    // float[]:   { 0F, 1F, 2F }
-    // double[]:  { 0D, 1D, 2D }
-    // String[]:  { "0", "1", "2" }
-    // int[][]:   { { 0, 1, 2 }, { 3, 4, 5 } }
-    // 
- public static String arrayToString( Object o ) - { - if ( o == null ) - return "null"; - String cl = o.getClass().getName(); - if ( ! cl.startsWith( "[" ) ) - // It's not an array; just call its toString method. - return o.toString(); - StringBuffer sb = new StringBuffer( "{ " ); - if ( o instanceof byte[] ) - { - byte[] ba = (byte[]) o; - for ( int i = 0; i < ba.length; ++i ) - { - if ( i > 0 ) sb.append( ", " ); - sb.append( "(byte)" ); - sb.append( ba[i] ); - } - } - else if ( o instanceof char[] ) - { - char[] ca = (char[]) o; - for ( int i = 0; i < ca.length; ++i ) - { - if ( i > 0 ) sb.append( ", " ); - sb.append( "'" ); - sb.append( ca[i] ); - sb.append( "'" ); - } - } - else if ( o instanceof short[] ) - { - short[] sa = (short[]) o; - for ( int i = 0; i < sa.length; ++i ) - { - if ( i > 0 ) sb.append( ", " ); - sb.append( "(short)" ); - sb.append( sa[i] ); - } - } - else if ( o instanceof int[] ) - { - int[] ia = (int[]) o; - for ( int i = 0; i < ia.length; ++i ) - { - if ( i > 0 ) sb.append( ", " ); - sb.append( ia[i] ); - } - } - else if ( o instanceof long[] ) - { - long[] la = (long[]) o; - for ( int i = 0; i < la.length; ++i ) - { - if ( i > 0 ) sb.append( ", " ); - sb.append( la[i] ); - sb.append( "L" ); - } - } - else if ( o instanceof float[] ) - { - float[] fa = (float[]) o; - for ( int i = 0; i < fa.length; ++i ) - { - if ( i > 0 ) sb.append( ", " ); - sb.append( fa[i] ); - sb.append( "F" ); - } - } - else if ( o instanceof double[] ) - { - double[] da = (double[]) o; - for ( int i = 0; i < da.length; ++i ) - { - if ( i > 0 ) sb.append( ", " ); - sb.append( da[i] ); - sb.append( "D" ); - } - } - else if ( o instanceof String ) - { - // Special-case Strings so we can surround them with quotes. - String[] sa = (String[]) o; - for ( int i = 0; i < sa.length; ++i ) - { - if ( i > 0 ) sb.append( ", " ); - sb.append( "\"" ); - sb.append( sa[i] ); - sb.append( "\"" ); - } - } - else if ( cl.startsWith( "[L" ) ) - { - // Some random class. - Object[] oa = (Object[]) o; - for ( int i = 0; i < oa.length; ++i ) - { - if ( i > 0 ) sb.append( ", " ); - sb.append( oa[i] ); - } - } - else if ( cl.startsWith( "[[" ) ) - { - // Nested arrays. - Object[] aa = (Object[]) o; - for ( int i = 0; i < aa.length; ++i ) - { - if ( i > 0 ) sb.append( ", " ); - sb.append( arrayToString( aa[i] ) ); - } - } - else - sb.append( "(unknown array type)" ); - sb.append( " }" ); - return sb.toString(); - } - - - /// Check if an object extends a given class or one of its superclasses. - // An instanceof that works on Class objects at runtime, instead - // of type descriptors at compile time. - public static boolean instanceOf( Object o, Class cl ) - { - // Null check. - if ( o == null || cl == null ) - return false; - Class ocl = o.getClass(); - // Check if they are the same class. - if ( ocl.equals( cl ) ) - return true; - // If the class is not itself an interface, then check its interfaces. - if ( ! cl.isInterface() ) - { - Class ifs[] = cl.getInterfaces(); - for ( int i = 0; i < ifs.length; ++i ) - if ( instanceOf( o, ifs[i] ) ) - return true; - } - // And check supeclasses. - Class scl = cl.getSuperclass(); - if ( scl != null ) - if ( instanceOf( o, scl ) ) - return true; - // Guess not. - return false; - } - - - /// Test is a number is even. - public static boolean even( long n ) - { - return ( n & 1 ) == 0; - } - - /// Test is a number is odd. - public static boolean odd( long n ) - { - return ( n & 1 ) != 0; - } - - - /// Count the number of 1-bits in a byte. - public static int countOnes( byte n ) - { - return countOnes( n & 0xffL ); - } - - /// Count the number of 1-bits in an int. - public static int countOnes( int n ) - { - return countOnes( n & 0xffffffffL ); - } - - /// Count the number of 1-bits in a long. - public static int countOnes( long n ) - { - // There are faster ways to do this, all the way up to looking - // up bytes in a 256-element table. But this is not too bad. - int count = 0; - while ( n != 0 ) - { - if ( odd( n ) ) - ++count; - n >>>= 1; - } - return count; - } - - - /// A fixed version of java.io.InputStream.read(byte[], int, int). The - // standard version catches and ignores IOExceptions from below. - // This version sends them on to the caller. - public static int read( InputStream in, byte[] b, int off, int len ) throws IOException - { - if ( len <= 0 ) - return 0; - int c = in.read(); - if ( c == -1 ) - return -1; - if ( b != null ) - b[off] = (byte) c; - int i; - for ( i = 1; i < len ; ++i ) - { - c = in.read(); - if ( c == -1 ) - break; - if ( b != null ) - b[off + i] = (byte) c; - } - return i; - } - - /// A version of read that reads the entire requested block, instead - // of sometimes terminating early. - // @return -1 on EOF, otherwise len - public static int readFully( InputStream in, byte[] b, int off, int len ) throws IOException - { - int l, r; - for ( l = 0; l < len; ) - { - r = read( in, b, l, len - l ); - if ( r == -1 ) - return -1; - l += r; - } - return len; - } - - - /// Make a URL with no ref part and no query string. Also, if it's - // a directory then make sure there's a trailing slash. - public static URL plainUrl( URL context, String urlStr ) throws MalformedURLException - { - URL url = new URL( context, urlStr ); - String fileStr = url.getFile(); - int i = fileStr.indexOf( '?' ); - if ( i != -1 ) - fileStr = fileStr.substring( 0, i ); - url = new URL( - url.getProtocol(), url.getHost(), url.getPort(), fileStr ); - if ( ( ! fileStr.endsWith( "/" ) ) && - urlStrIsDir( url.toExternalForm() ) ) - { - fileStr = fileStr + "/"; - url = new URL( - url.getProtocol(), url.getHost(), url.getPort(), fileStr ); - } - return url; - } - - /// Make a URL with no ref part and no query string. Also, if it's - // a directory then make sure there's a trailing slash. - public static URL plainUrl( String urlStr ) throws MalformedURLException - { - return plainUrl( null, urlStr ); - } - - /// Figure out the base URL for a given URL. What this means is - // if the URL points to a directory, you get that directory; if the - // URL points to a file, you get the directory the file is in. - public static String baseUrlStr( String urlStr ) - { - if ( urlStr.endsWith( "/" ) ) - return urlStr; - if ( urlStrIsDir( urlStr ) ) - return urlStr + "/"; - return urlStr.substring( 0, urlStr.lastIndexOf( '/' ) + 1 ); - } - - /// Makes sure if a URL is a directory, it ends with a slash. - public static String fixDirUrlStr( String urlStr ) - { - if ( urlStr.endsWith( "/" ) ) - return urlStr; - if ( urlStrIsDir( urlStr ) ) - return urlStr + "/"; - return urlStr; - } - - /// Figures out whether a URL points to a directory or not. - // Web servers are lenient and accept directory-URLs without - // the trailing slash. What they actually do is return a - // redirect to the same URL with the trailing slash appended. - // Unfortunately, Java doesn't let us see that such a redirect - // happened. Instead we have to figure out it's a directory - // indirectly and heuristically. - public static boolean urlStrIsDir( String urlStr ) - { - // If it ends with a slash, it's probably a directory. - if ( urlStr.endsWith( "/" ) ) - return true; - - // If the last component has a dot, it's probably not a directory. - int lastSlash = urlStr.lastIndexOf( '/' ); - int lastPeriod = urlStr.lastIndexOf( '.' ); - if ( lastPeriod != -1 && ( lastSlash == -1 || lastPeriod > lastSlash ) ) - return false; - - // Otherwise, append a slash and try to connect. This is - // fairly expensive. - String urlStrWithSlash = urlStr + "/"; - try - { - URL url = new URL( urlStrWithSlash ); - InputStream f = url.openStream(); - f.close(); - // Worked fine - it's probably a directory. - return true; - } - catch ( Exception e ) - { - // Got an error - must not be a directory. - return false; - } - } - - - // Figures out whether a URL is absolute or not. - public static boolean urlStrIsAbsolute( String urlStr ) - { - if ( urlStr.startsWith( "/" ) || urlStr.indexOf( ":/" ) != -1 ) - return true; - // Should handle :8000/ and such too. - return false; - } - - // Returns an equivalent URL string that is guaranteed to be absolute. - public static String absoluteUrlStr( String urlStr, URL contextUrl ) throws MalformedURLException - { - URL url = new URL( contextUrl, urlStr ); - return url.toExternalForm(); - } - - - /// URLDecoder to go along with java.net.URLEncoder. Why there isn't - // already a decoder in the standard library is a mystery to me. - public static String urlDecoder( String encoded ) - { - StringBuffer decoded = new StringBuffer(); - int len = encoded.length(); - for ( int i = 0; i < len; ++i ) - { - if ( encoded.charAt( i ) == '%' && i + 2 < len ) - { - int d1 = Character.digit( encoded.charAt( i + 1 ), 16 ); - int d2 = Character.digit( encoded.charAt( i + 2 ), 16 ); - if ( d1 != -1 && d2 != -1 ) - decoded.append( (char) ( ( d1 << 4 ) + d2 ) ); - i += 2; - } - else if ( encoded.charAt( i ) == '+' ) - decoded.append( ' ' ); - else - decoded.append( encoded.charAt( i ) ); - } - return decoded.toString(); - } - - - /// A base-64 encoder, necessary for doing the client side of Basic - // Authentication. This encodes binary data as printable ASCII - // characters. Three 8-bit binary bytes are turned into four 6-bit - // values, like so: - // - // [11111111] [22222222] [33333333] - // - // [111111] [112222] [222233] [333333] - // - // Then the 6-bit values are represented using the characters "A-Za-z0-9+/". - public static String base64Encode( byte[] src ) - { - StringBuffer encoded = new StringBuffer(); - int i, phase = 0; - char c = 0; - - for ( i = 0; i < src.length; ++i ) - { - switch ( phase ) - { - case 0: - c = b64EncodeTable[( src[i] >> 2 ) & 0x3f]; - encoded.append( c ); - c = b64EncodeTable[( src[i] & 0x3 ) << 4]; - encoded.append( c ); - ++phase; - break; - case 1: - c = b64EncodeTable[ - ( b64DecodeTable[c] | ( src[i] >> 4 ) ) & 0x3f]; - encoded.setCharAt( encoded.length() - 1, c ); - c = b64EncodeTable[( src[i] & 0xf ) << 2]; - encoded.append( c ); - ++phase; - break; - case 2: - c = b64EncodeTable[ - ( b64DecodeTable[c] | ( src[i] >> 6 ) ) & 0x3f]; - encoded.setCharAt( encoded.length() - 1, c ); - c = b64EncodeTable[src[i] & 0x3f]; - encoded.append( c ); - phase = 0; - break; - } - } - /* Pad with ='s. */ - while ( phase++ < 3 ) - encoded.append( '=' ); - return encoded.toString(); - } - - private static char b64EncodeTable[] = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 00-07 - 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 08-15 - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 16-23 - 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', // 24-31 - 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 32-39 - 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', // 40-47 - 'w', 'x', 'y', 'z', '0', '1', '2', '3', // 48-55 - '4', '5', '6', '7', '8', '9', '+', '/' // 56-63 - }; - - private static int b64DecodeTable[] = { - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // 00-0F - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // 10-1F - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, // 20-2F - 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, // 30-3F - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, // 40-4F - 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, // 50-5F - -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, // 60-6F - 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, // 70-7F - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // 80-8F - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // 90-9F - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // A0-AF - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // B0-BF - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // C0-CF - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // D0-DF - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // E0-EF - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 // F0-FF - }; - - /// A base-64 encoder that takes a String, for convenience. - public static String base64Encode( String srcString ) - { - byte[] src = new byte[srcString.length()]; - srcString.getBytes( 0, src.length, src, 0 ); - return base64Encode( src ); - } - - - /// Check if an array contains a given element. - public static boolean arraycontains( Object[] array, Object element ) - { - for ( int i = 0; i < array.length; ++i ) - if ( array[i].equals( element ) ) - return true; - return false; - } - - - /// Run a program on the host system. - //

- // This routine runs the specified command, waits for it to - // finish, and returns the exit status. - // This is like the Unix system() routine. Unlike the Unix version, - // though, stdout and stderr get thrown away unless you redirect them. - public static int system( String cmd ) - { - try - { - return runCommand( cmd ).waitFor(); - } - catch ( IOException e ) - { - return -1; - } - catch ( InterruptedException e ) - { - return -1; - } - } - - /// Run a program on the host system, and capture the output. - //

- // This routine runs the specified command, and returns an InputStream - // for reading the output of the program. - //

- // WARNING: In JDK1.0.2 there is a serious bug in the process - // IO routines, such that reading all the way to the end of a process's - // output will invariably get you an IOException( "read error" ). - // In some cases you will also lose the last bufferload of - // the output. The workaround is to add a " ; sleep 1" to the end of - // your command, and to ignore the "read error" IOException. - public static InputStream popenr( String cmd ) - { - try - { - return runCommand( cmd ).getInputStream(); - } - catch ( IOException e ) - { - return null; - } - } - - /// Run a program on the host system, and send it some input. - //

- // This routine runs the specified command, and returns an OutputStream - // for writing the program's input. - public static OutputStream popenw( String cmd ) - { - try - { - return runCommand( cmd ).getOutputStream(); - } - catch ( IOException e ) - { - return null; - } - } - - /// Run a program on the host system. - //

- // This routine runs the specified command, and returns a Process - // object so you can do what you like with it. - //

- // WARNING: In JDK1.0.2 there is a serious bug in the process - // IO routines, such that reading all the way to the end of a process's - // output will invariably get you an IOException( "read error" ). - // In some cases you will also lose the last bufferload of - // the output. The workaround is to add a " ; sleep 1" to the end of - // your command, and to ignore the "read error" IOException. - public static Process runCommand( String cmd ) throws IOException - { - Runtime runtime = Runtime.getRuntime(); - String[] shCmd = new String[3]; - shCmd[0] = "/bin/sh"; - shCmd[1] = "-c"; - shCmd[2] = cmd; - return runtime.exec( shCmd ); - } - - - /// Copy the input to the output until EOF. - public static void copyStream( InputStream in, OutputStream out ) throws IOException - { - byte[] buf = new byte[4096]; - int len; - while ( ( len = in.read( buf ) ) != -1 ) - out.write( buf, 0, len ); - } - - /// Copy the input to the output until EOF. - public static void copyStream( Reader in, Writer out ) throws IOException - { - char[] buf = new char[4096]; - int len; - while ( ( len = in.read( buf ) ) != -1 ) - out.write( buf, 0, len ); - } - - /// Copy the input to the output until EOF. - public static void copyStream( InputStream in, Writer out ) throws IOException - { - byte[] buf1 = new byte[4096]; - char[] buf2 = new char[4096]; - int len, i; - while ( ( len = in.read( buf1 ) ) != -1 ) - { - for ( i = 0; i < len; ++i ) - buf2[i] = (char) buf1[i]; - out.write( buf2, 0, len ); - } - } - - /// Copy the input to the output until EOF. - public static void copyStream( Reader in, OutputStream out ) throws IOException - { - char[] buf1 = new char[4096]; - byte[] buf2 = new byte[4096]; - int len, i; - while ( ( len = in.read( buf1 ) ) != -1 ) - { - for ( i = 0; i < len; ++i ) - buf2[i] = (byte) buf1[i]; - out.write( buf2, 0, len ); - } - } - - - /// Dump out the current call stack. - public static void dumpStack( PrintStream p ) - { - (new Throwable()).printStackTrace( p ); - } - - /// Dump out the current call stack onto System.err. - public static void dumpStack() - { - (new Throwable()).printStackTrace(); - } - - } diff --git a/src/Acme/WildcardDictionary.java b/src/Acme/WildcardDictionary.java deleted file mode 100644 index ee957be7..00000000 --- a/src/Acme/WildcardDictionary.java +++ /dev/null @@ -1,147 +0,0 @@ -// WildcardDictionary - a dictionary with wildcard lookups -// -// Copyright (C) 1996 by Jef Poskanzer . 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 Acme; - -import java.util.*; - -/// A dictionary with wildcard lookups. -//

-// The keys in this dictionary are wildcard patterns. When you do a get(), -// the string you pass in is matched against all the patterns, and the -// first match is returned. -//

-// The wildcard matcher is fairly simple, it implements * meaning any -// string, ? meaning any single character, and | separating multiple -// patterns. All other characters must match literally. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see Acme.Utils#match - -public class WildcardDictionary extends Dictionary - { - - private Vector keys; - private Vector elements; - - /// Constructor. - public WildcardDictionary() - { - keys = new Vector(); - elements = new Vector(); - } - - /// Returns the number of elements contained within the dictionary. - public int size() - { - return elements.size(); - } - - /// Returns true if the dictionary contains no elements. - public boolean isEmpty() - { - return size() == 0; - } - - /// Returns an enumeration of the dictionary's keys. - public Enumeration keys() - { - return keys.elements(); - } - - /// Returns an enumeration of the elements. Use the Enumeration methods - // on the returned object to fetch the elements sequentially. - public Enumeration elements() - { - return elements.elements(); - } - - /// Gets the object associated with the specified key in the dictionary. - // The key is assumed to be a String, which is matched against - // the wildcard-pattern keys in the dictionary. - // @param key the string to match - // @returns the element for the key, or null if there's no match - // @see Acme.Utils#match - public synchronized Object get( Object key ) - { - String sKey = (String) key; - for ( int i = 0; i < keys.size(); ++i ) - { - String thisKey = (String) keys.elementAt( i ); - if ( Acme.Utils.match( thisKey, sKey ) ) - return elements.elementAt( i ); - } - return null; - } - - /// Puts the specified element into the Dictionary, 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 wildcard-pattern key - // @param value the specified element - // @return the old value of the key, or null if it did not have one. - // @exception NullPointerException If the value of the specified - // element is null. - public synchronized Object put( Object key, Object element ) - { - int i = keys.indexOf( key ); - if ( i != -1 ) - { - Object oldElement = elements.elementAt( i ); - elements.setElementAt( element, i ); - return oldElement; - } - else - { - keys.addElement( key ); - elements.addElement( element ); - return null; - } - } - - /// 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( Object key ) - { - int i = keys.indexOf( key ); - if ( i != -1 ) - { - Object oldElement = elements.elementAt( i ); - keys.removeElementAt( i ); - elements.removeElementAt( i ); - return oldElement; - } - else - return null; - } - - } diff --git a/src/FESI/AST/ASTAllocationExpression.java b/src/FESI/AST/ASTAllocationExpression.java deleted file mode 100644 index 20017f57..00000000 --- a/src/FESI/AST/ASTAllocationExpression.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTAllocationExpression.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTAllocationExpression extends SimpleNode { - public ASTAllocationExpression(int id) { - super(id); - } - - public ASTAllocationExpression(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTAllocationExpression(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTAllocationExpression(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTAndExpressionSequence.java b/src/FESI/AST/ASTAndExpressionSequence.java deleted file mode 100644 index 3232ec54..00000000 --- a/src/FESI/AST/ASTAndExpressionSequence.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTAndExpressionSequence.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTAndExpressionSequence extends SimpleNode { - public ASTAndExpressionSequence(int id) { - super(id); - } - - public ASTAndExpressionSequence(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTAndExpressionSequence(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTAndExpressionSequence(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTAssignmentExpression.java b/src/FESI/AST/ASTAssignmentExpression.java deleted file mode 100644 index f1528f62..00000000 --- a/src/FESI/AST/ASTAssignmentExpression.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTAssignmentExpression.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTAssignmentExpression extends SimpleNode { - public ASTAssignmentExpression(int id) { - super(id); - } - - public ASTAssignmentExpression(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTAssignmentExpression(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTAssignmentExpression(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTBinaryExpressionSequence.java b/src/FESI/AST/ASTBinaryExpressionSequence.java deleted file mode 100644 index fa9c3d7f..00000000 --- a/src/FESI/AST/ASTBinaryExpressionSequence.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTBinaryExpressionSequence.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTBinaryExpressionSequence extends SimpleNode { - public ASTBinaryExpressionSequence(int id) { - super(id); - } - - public ASTBinaryExpressionSequence(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTBinaryExpressionSequence(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTBinaryExpressionSequence(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTBreakStatement.java b/src/FESI/AST/ASTBreakStatement.java deleted file mode 100644 index 69ad9d8f..00000000 --- a/src/FESI/AST/ASTBreakStatement.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTBreakStatement.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTBreakStatement extends SimpleNode { - public ASTBreakStatement(int id) { - super(id); - } - - public ASTBreakStatement(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTBreakStatement(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTBreakStatement(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTCompositeReference.java b/src/FESI/AST/ASTCompositeReference.java deleted file mode 100644 index aa3fc24d..00000000 --- a/src/FESI/AST/ASTCompositeReference.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTCompositeReference.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTCompositeReference extends SimpleNode { - public ASTCompositeReference(int id) { - super(id); - } - - public ASTCompositeReference(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTCompositeReference(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTCompositeReference(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTConditionalExpression.java b/src/FESI/AST/ASTConditionalExpression.java deleted file mode 100644 index dfd727bb..00000000 --- a/src/FESI/AST/ASTConditionalExpression.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTConditionalExpression.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTConditionalExpression extends SimpleNode { - public ASTConditionalExpression(int id) { - super(id); - } - - public ASTConditionalExpression(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTConditionalExpression(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTConditionalExpression(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTContinueStatement.java b/src/FESI/AST/ASTContinueStatement.java deleted file mode 100644 index 6a7570b8..00000000 --- a/src/FESI/AST/ASTContinueStatement.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTContinueStatement.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTContinueStatement extends SimpleNode { - public ASTContinueStatement(int id) { - super(id); - } - - public ASTContinueStatement(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTContinueStatement(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTContinueStatement(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTEmptyExpression.java b/src/FESI/AST/ASTEmptyExpression.java deleted file mode 100644 index a5749a6e..00000000 --- a/src/FESI/AST/ASTEmptyExpression.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTEmptyExpression.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTEmptyExpression extends SimpleNode { - public ASTEmptyExpression(int id) { - super(id); - } - - public ASTEmptyExpression(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTEmptyExpression(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTEmptyExpression(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTExpressionList.java b/src/FESI/AST/ASTExpressionList.java deleted file mode 100644 index 9a12e43c..00000000 --- a/src/FESI/AST/ASTExpressionList.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTExpressionList.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTExpressionList extends SimpleNode { - public ASTExpressionList(int id) { - super(id); - } - - public ASTExpressionList(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTExpressionList(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTExpressionList(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTForInStatement.java b/src/FESI/AST/ASTForInStatement.java deleted file mode 100644 index 6e7b3319..00000000 --- a/src/FESI/AST/ASTForInStatement.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTForInStatement.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTForInStatement extends SimpleNode { - public ASTForInStatement(int id) { - super(id); - } - - public ASTForInStatement(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTForInStatement(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTForInStatement(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTForStatement.java b/src/FESI/AST/ASTForStatement.java deleted file mode 100644 index 17beb278..00000000 --- a/src/FESI/AST/ASTForStatement.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTForStatement.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTForStatement extends SimpleNode { - public ASTForStatement(int id) { - super(id); - } - - public ASTForStatement(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTForStatement(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTForStatement(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTForVarInStatement.java b/src/FESI/AST/ASTForVarInStatement.java deleted file mode 100644 index b0128297..00000000 --- a/src/FESI/AST/ASTForVarInStatement.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTForVarInStatement.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTForVarInStatement extends SimpleNode { - public ASTForVarInStatement(int id) { - super(id); - } - - public ASTForVarInStatement(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTForVarInStatement(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTForVarInStatement(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTForVarStatement.java b/src/FESI/AST/ASTForVarStatement.java deleted file mode 100644 index 7f56b6d7..00000000 --- a/src/FESI/AST/ASTForVarStatement.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTForVarStatement.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTForVarStatement extends SimpleNode { - public ASTForVarStatement(int id) { - super(id); - } - - public ASTForVarStatement(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTForVarStatement(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTForVarStatement(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTFormalParameterList.java b/src/FESI/AST/ASTFormalParameterList.java deleted file mode 100644 index 28f7b66d..00000000 --- a/src/FESI/AST/ASTFormalParameterList.java +++ /dev/null @@ -1,39 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTFormalParameterList.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTFormalParameterList extends SimpleNode { - public ASTFormalParameterList(int id) { - super(id); - } - - public ASTFormalParameterList(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTFormalParameterList(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTFormalParameterList(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } - - // JMCL - public String [] getArguments() { - int n = jjtGetNumChildren(); - String [] args = new String[n]; - for (int i=0; i"; - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTIfStatement.java b/src/FESI/AST/ASTIfStatement.java deleted file mode 100644 index d611ccdf..00000000 --- a/src/FESI/AST/ASTIfStatement.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTIfStatement.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTIfStatement extends SimpleNode { - public ASTIfStatement(int id) { - super(id); - } - - public ASTIfStatement(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTIfStatement(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTIfStatement(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTLiteral.java b/src/FESI/AST/ASTLiteral.java deleted file mode 100644 index 1fc0f46c..00000000 --- a/src/FESI/AST/ASTLiteral.java +++ /dev/null @@ -1,210 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTLiteral.java */ - -package FESI.AST; - -import FESI.Parser.*; -import FESI.Data.*; -import FESI.Exceptions.*; - - -public class ASTLiteral extends SimpleNode { - - private ESValue theValue = null; - - public ASTLiteral(int id) { - super(id); - } - - public ASTLiteral(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTLiteral(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTLiteral(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } - - // JMCL - public ESValue getValue() { - return theValue; - } - - static final int hexval(char c) throws ProgrammingError { - switch(c) - { - case '0' : - return 0; - case '1' : - return 1; - case '2' : - return 2; - case '3' : - return 3; - case '4' : - return 4; - case '5' : - return 5; - case '6' : - return 6; - case '7' : - return 7; - case '8' : - return 8; - case '9' : - return 9; - - case 'a' : - case 'A' : - return 10; - case 'b' : - case 'B' : - return 11; - case 'c' : - case 'C' : - return 12; - case 'd' : - case 'D' : - return 13; - case 'e' : - case 'E' : - return 14; - case 'f' : - case 'F' : - return 15; - } - - throw new ProgrammingError("Illegal hex or unicode constant"); // Should never come here - } - static final int octval(char c) throws ProgrammingError { - switch(c) - { - case '0' : - return 0; - case '1' : - return 1; - case '2' : - return 2; - case '3' : - return 3; - case '4' : - return 4; - case '5' : - return 5; - case '6' : - return 6; - case '7' : - return 7; - case '8' : - return 8; - case '9' : - return 9; - - case 'a' : - case 'A' : - return 10; - case 'b' : - case 'B' : - return 11; - case 'c' : - case 'C' : - return 12; - case 'd' : - case 'D' : - return 13; - case 'e' : - case 'E' : - return 14; - case 'f' : - case 'F' : - return 15; - } - - throw new ProgrammingError("Illegal octal constant"); // Should never come here - } - - public void setStringValue(String image) { - int l = image.length(); - StringBuffer sb = new StringBuffer(l); - for (int i=0; i='0' && c <= '7') { - c = (char)(octval(image.charAt(i))); - if ((image.length()>i) && - (image.charAt(i+1)>='0') && (image.charAt(i+1)<='7')) { - i++; - c = (char) ((c<<4) | octval(image.charAt(i))); - } - } - } - sb.append(c); - } - theValue = new ESString(sb.toString()); - } - public void setDecimalValue(String image) { - try { - theValue = new ESNumber(Long.parseLong(image)); - } catch (NumberFormatException e) { - Double value = new Double(image); - theValue = new ESNumber(value.doubleValue()); - } - } - public void setOctalValue(String image) { - try { - String imageWithout0 = image.substring(1); - theValue = new ESNumber(Long.parseLong(imageWithout0,8)); - } catch (NumberFormatException e) { - Double value = new Double(image); - theValue = new ESNumber(value.doubleValue()); - } - } - public void setHexValue(String image) { - try { - String imageWithout0x = image.substring(2); - theValue = new ESNumber(Long.parseLong(imageWithout0x,16)); - } catch (NumberFormatException e) { - Double value = new Double(image); - theValue = new ESNumber(value.doubleValue()); - } - } - public void setFloatingPointValue(String image) { - Double value = new Double(image); - theValue = new ESNumber(value.doubleValue()); - } - public void setBooleanValue(boolean value) { - theValue = ESBoolean.makeBoolean(value); - } - public void setNullValue() { - theValue = ESNull.theNull; - } - - public String toString() { - return "[" + theValue.toString() + "]"; - } - -} \ No newline at end of file diff --git a/src/FESI/AST/ASTOperator.java b/src/FESI/AST/ASTOperator.java deleted file mode 100644 index b39355af..00000000 --- a/src/FESI/AST/ASTOperator.java +++ /dev/null @@ -1,44 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTOperator.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTOperator extends SimpleNode { - - private int operatorCode = EOF; - - public ASTOperator(int id) { - super(id); - } - - public ASTOperator(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTOperator(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTOperator(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } - - // JMCL - public void setOperator(int operatorCode) { - this.operatorCode = operatorCode; - } - public int getOperator() { - return operatorCode; - } - - public String toString() { - return "<" + tokenImage[operatorCode] + ">"; - } - -} \ No newline at end of file diff --git a/src/FESI/AST/ASTOrExpressionSequence.java b/src/FESI/AST/ASTOrExpressionSequence.java deleted file mode 100644 index 435885e7..00000000 --- a/src/FESI/AST/ASTOrExpressionSequence.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTOrExpressionSequence.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTOrExpressionSequence extends SimpleNode { - public ASTOrExpressionSequence(int id) { - super(id); - } - - public ASTOrExpressionSequence(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTOrExpressionSequence(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTOrExpressionSequence(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTPostfixExpression.java b/src/FESI/AST/ASTPostfixExpression.java deleted file mode 100644 index 87039b7d..00000000 --- a/src/FESI/AST/ASTPostfixExpression.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTPostfixExpression.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTPostfixExpression extends SimpleNode { - public ASTPostfixExpression(int id) { - super(id); - } - - public ASTPostfixExpression(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTPostfixExpression(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTPostfixExpression(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTProgram.java b/src/FESI/AST/ASTProgram.java deleted file mode 100644 index eaf5ecbb..00000000 --- a/src/FESI/AST/ASTProgram.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTProgram.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTProgram extends SimpleNode { - public ASTProgram(int id) { - super(id); - } - - public ASTProgram(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTProgram(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTProgram(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTPropertyIdentifierReference.java b/src/FESI/AST/ASTPropertyIdentifierReference.java deleted file mode 100644 index a1b3cf55..00000000 --- a/src/FESI/AST/ASTPropertyIdentifierReference.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTPropertyIdentifierReference.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTPropertyIdentifierReference extends SimpleNode { - public ASTPropertyIdentifierReference(int id) { - super(id); - } - - public ASTPropertyIdentifierReference(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTPropertyIdentifierReference(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTPropertyIdentifierReference(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTPropertyValueReference.java b/src/FESI/AST/ASTPropertyValueReference.java deleted file mode 100644 index aabaf213..00000000 --- a/src/FESI/AST/ASTPropertyValueReference.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTPropertyValueReference.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTPropertyValueReference extends SimpleNode { - public ASTPropertyValueReference(int id) { - super(id); - } - - public ASTPropertyValueReference(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTPropertyValueReference(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTPropertyValueReference(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTReturnStatement.java b/src/FESI/AST/ASTReturnStatement.java deleted file mode 100644 index 065ae925..00000000 --- a/src/FESI/AST/ASTReturnStatement.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTReturnStatement.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTReturnStatement extends SimpleNode { - public ASTReturnStatement(int id) { - super(id); - } - - public ASTReturnStatement(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTReturnStatement(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTReturnStatement(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTStatement.java b/src/FESI/AST/ASTStatement.java deleted file mode 100644 index b3637fd7..00000000 --- a/src/FESI/AST/ASTStatement.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTStatement.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTStatement extends SimpleNode { - public ASTStatement(int id) { - super(id); - } - - public ASTStatement(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTStatement(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTStatement(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTStatementList.java b/src/FESI/AST/ASTStatementList.java deleted file mode 100644 index 092c55dc..00000000 --- a/src/FESI/AST/ASTStatementList.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTStatementList.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTStatementList extends SimpleNode { - public ASTStatementList(int id) { - super(id); - } - - public ASTStatementList(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTStatementList(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTStatementList(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTThisReference.java b/src/FESI/AST/ASTThisReference.java deleted file mode 100644 index 5ed38f5e..00000000 --- a/src/FESI/AST/ASTThisReference.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTThisReference.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTThisReference extends SimpleNode { - public ASTThisReference(int id) { - super(id); - } - - public ASTThisReference(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTThisReference(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTThisReference(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTUnaryExpression.java b/src/FESI/AST/ASTUnaryExpression.java deleted file mode 100644 index 7d94dfec..00000000 --- a/src/FESI/AST/ASTUnaryExpression.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTUnaryExpression.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTUnaryExpression extends SimpleNode { - public ASTUnaryExpression(int id) { - super(id); - } - - public ASTUnaryExpression(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTUnaryExpression(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTUnaryExpression(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTVariableDeclaration.java b/src/FESI/AST/ASTVariableDeclaration.java deleted file mode 100644 index 88ab3a34..00000000 --- a/src/FESI/AST/ASTVariableDeclaration.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTVariableDeclaration.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTVariableDeclaration extends SimpleNode { - public ASTVariableDeclaration(int id) { - super(id); - } - - public ASTVariableDeclaration(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTVariableDeclaration(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTVariableDeclaration(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTWhileStatement.java b/src/FESI/AST/ASTWhileStatement.java deleted file mode 100644 index 4ab28485..00000000 --- a/src/FESI/AST/ASTWhileStatement.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTWhileStatement.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTWhileStatement extends SimpleNode { - public ASTWhileStatement(int id) { - super(id); - } - - public ASTWhileStatement(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTWhileStatement(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTWhileStatement(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } -} \ No newline at end of file diff --git a/src/FESI/AST/ASTWithStatement.java b/src/FESI/AST/ASTWithStatement.java deleted file mode 100644 index d8ca850a..00000000 --- a/src/FESI/AST/ASTWithStatement.java +++ /dev/null @@ -1,40 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. ASTWithStatement.java */ - -package FESI.AST; - -import FESI.Parser.*; - -public class ASTWithStatement extends SimpleNode { - - Object evaluationSource = null; - - public ASTWithStatement(int id) { - super(id); - } - - public ASTWithStatement(EcmaScript p, int id) { - super(p, id); - } - - public static Node jjtCreate(int id) { - return new ASTWithStatement(id); - } - - public static Node jjtCreate(EcmaScript p, int id) { - return new ASTWithStatement(p, id); - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } - - // JMCL - public void setEvaluationSource(Object evaluationSource) { - this.evaluationSource = evaluationSource; - } - - public Object getEvaluationSource() { - return evaluationSource; - } -} \ No newline at end of file diff --git a/src/FESI/AST/EcmaScriptDumpVisitor.java b/src/FESI/AST/EcmaScriptDumpVisitor.java deleted file mode 100644 index 860a2909..00000000 --- a/src/FESI/AST/EcmaScriptDumpVisitor.java +++ /dev/null @@ -1,263 +0,0 @@ -package FESI.AST; - -import FESI.Parser.*; - -public class EcmaScriptDumpVisitor implements EcmaScriptVisitor -{ - private int indent = 0; - - private String indentString() { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < indent; ++i) { - sb.append(" "); - } - return sb.toString(); - } - - public Object visit(SimpleNode node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTProgram node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTStatementList node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTFunctionDeclaration node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTFormalParameterList node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTStatement node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTVariableDeclaration node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTIfStatement node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTWhileStatement node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTForStatement node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTForInStatement node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTForVarStatement node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTForVarInStatement node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTContinueStatement node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTBreakStatement node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTReturnStatement node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTWithStatement node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTThisReference node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTCompositeReference node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTFunctionCallParameters node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTPropertyIdentifierReference node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTPropertyValueReference node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTAllocationExpression node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTOperator node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTPostfixExpression node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTUnaryExpression node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTBinaryExpressionSequence node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTOrExpressionSequence node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTAndExpressionSequence node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTConditionalExpression node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTAssignmentExpression node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTExpressionList node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTEmptyExpression node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTLiteral node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - public Object visit(ASTIdentifier node, Object data) { - System.out.println(indentString() + node); - ++indent; - data = node.childrenAccept(this, data); - --indent; - return data; - } - -} \ No newline at end of file diff --git a/src/FESI/AST/EcmaScriptTreeConstants.java b/src/FESI/AST/EcmaScriptTreeConstants.java deleted file mode 100644 index fe8d6322..00000000 --- a/src/FESI/AST/EcmaScriptTreeConstants.java +++ /dev/null @@ -1,81 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. EcmaScriptTreeConstants.java */ - -package FESI.AST; - -public interface EcmaScriptTreeConstants -{ - public int JJTLITERAL = 0; - public int JJTIDENTIFIER = 1; - public int JJTVOID = 2; - public int JJTTHISREFERENCE = 3; - public int JJTCOMPOSITEREFERENCE = 4; - public int JJTFUNCTIONCALLPARAMETERS = 5; - public int JJTPROPERTYVALUEREFERENCE = 6; - public int JJTPROPERTYIDENTIFIERREFERENCE = 7; - public int JJTALLOCATIONEXPRESSION = 8; - public int JJTOPERATOR = 9; - public int JJTPOSTFIXEXPRESSION = 10; - public int JJTUNARYEXPRESSION = 11; - public int JJTBINARYEXPRESSIONSEQUENCE = 12; - public int JJTANDEXPRESSIONSEQUENCE = 13; - public int JJTOREXPRESSIONSEQUENCE = 14; - public int JJTCONDITIONALEXPRESSION = 15; - public int JJTASSIGNMENTEXPRESSION = 16; - public int JJTEXPRESSIONLIST = 17; - public int JJTSTATEMENT = 18; - public int JJTSTATEMENTLIST = 19; - public int JJTVARIABLEDECLARATION = 20; - public int JJTIFSTATEMENT = 21; - public int JJTWHILESTATEMENT = 22; - public int JJTFORSTATEMENT = 23; - public int JJTEMPTYEXPRESSION = 24; - public int JJTFORVARSTATEMENT = 25; - public int JJTFORINSTATEMENT = 26; - public int JJTFORVARINSTATEMENT = 27; - public int JJTCONTINUESTATEMENT = 28; - public int JJTBREAKSTATEMENT = 29; - public int JJTRETURNSTATEMENT = 30; - public int JJTWITHSTATEMENT = 31; - public int JJTFUNCTIONDECLARATION = 32; - public int JJTFORMALPARAMETERLIST = 33; - public int JJTPROGRAM = 34; - - - public String[] jjtNodeName = { - "Literal", - "Identifier", - "void", - "ThisReference", - "CompositeReference", - "FunctionCallParameters", - "PropertyValueReference", - "PropertyIdentifierReference", - "AllocationExpression", - "Operator", - "PostfixExpression", - "UnaryExpression", - "BinaryExpressionSequence", - "AndExpressionSequence", - "OrExpressionSequence", - "ConditionalExpression", - "AssignmentExpression", - "ExpressionList", - "Statement", - "StatementList", - "VariableDeclaration", - "IfStatement", - "WhileStatement", - "ForStatement", - "EmptyExpression", - "ForVarStatement", - "ForInStatement", - "ForVarInStatement", - "ContinueStatement", - "BreakStatement", - "ReturnStatement", - "WithStatement", - "FunctionDeclaration", - "FormalParameterList", - "Program", - }; -} diff --git a/src/FESI/AST/EcmaScriptVisitor.java b/src/FESI/AST/EcmaScriptVisitor.java deleted file mode 100644 index 116eb4ac..00000000 --- a/src/FESI/AST/EcmaScriptVisitor.java +++ /dev/null @@ -1,42 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. EcmaScriptVisitor.java */ - -package FESI.AST; - -public interface EcmaScriptVisitor -{ - public Object visit(SimpleNode node, Object data); - public Object visit(ASTLiteral node, Object data); - public Object visit(ASTIdentifier node, Object data); - public Object visit(ASTThisReference node, Object data); - public Object visit(ASTCompositeReference node, Object data); - public Object visit(ASTFunctionCallParameters node, Object data); - public Object visit(ASTPropertyValueReference node, Object data); - public Object visit(ASTPropertyIdentifierReference node, Object data); - public Object visit(ASTAllocationExpression node, Object data); - public Object visit(ASTOperator node, Object data); - public Object visit(ASTPostfixExpression node, Object data); - public Object visit(ASTUnaryExpression node, Object data); - public Object visit(ASTBinaryExpressionSequence node, Object data); - public Object visit(ASTAndExpressionSequence node, Object data); - public Object visit(ASTOrExpressionSequence node, Object data); - public Object visit(ASTConditionalExpression node, Object data); - public Object visit(ASTAssignmentExpression node, Object data); - public Object visit(ASTExpressionList node, Object data); - public Object visit(ASTStatement node, Object data); - public Object visit(ASTStatementList node, Object data); - public Object visit(ASTVariableDeclaration node, Object data); - public Object visit(ASTIfStatement node, Object data); - public Object visit(ASTWhileStatement node, Object data); - public Object visit(ASTForStatement node, Object data); - public Object visit(ASTEmptyExpression node, Object data); - public Object visit(ASTForVarStatement node, Object data); - public Object visit(ASTForInStatement node, Object data); - public Object visit(ASTForVarInStatement node, Object data); - public Object visit(ASTContinueStatement node, Object data); - public Object visit(ASTBreakStatement node, Object data); - public Object visit(ASTReturnStatement node, Object data); - public Object visit(ASTWithStatement node, Object data); - public Object visit(ASTFunctionDeclaration node, Object data); - public Object visit(ASTFormalParameterList node, Object data); - public Object visit(ASTProgram node, Object data); -} diff --git a/src/FESI/AST/JJTEcmaScriptState.java b/src/FESI/AST/JJTEcmaScriptState.java deleted file mode 100644 index 023928ed..00000000 --- a/src/FESI/AST/JJTEcmaScriptState.java +++ /dev/null @@ -1,123 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. JJTEcmaScriptState.java */ - -package FESI.AST; - -public class JJTEcmaScriptState { - private java.util.Stack nodes; - private java.util.Stack marks; - - private int sp; // number of nodes on stack - private int mk; // current mark - private boolean node_created; - - public JJTEcmaScriptState() { - nodes = new java.util.Stack(); - marks = new java.util.Stack(); - sp = 0; - mk = 0; - } - - /* Determines whether the current node was actually closed and - pushed. This should only be called in the final user action of a - node scope. */ - public boolean nodeCreated() { - return node_created; - } - - /* Call this to reinitialize the node stack. It is called - automatically by the parser's ReInit() method. */ - public void reset() { - nodes.removeAllElements(); - marks.removeAllElements(); - sp = 0; - mk = 0; - } - - /* Returns the root node of the AST. It only makes sense to call - this after a successful parse. */ - public Node rootNode() { - return (Node)nodes.elementAt(0); - } - - /* Pushes a node on to the stack. */ - public void pushNode(Node n) { - nodes.push(n); - ++sp; - } - - /* Returns the node on the top of the stack, and remove it from the - stack. */ - public Node popNode() { - if (--sp < mk) { - mk = ((Integer)marks.pop()).intValue(); - } - return (Node)nodes.pop(); - } - - /* Returns the node currently on the top of the stack. */ - public Node peekNode() { - return (Node)nodes.peek(); - } - - /* Returns the number of children on the stack in the current node - scope. */ - public int nodeArity() { - return sp - mk; - } - - - public void clearNodeScope(Node n) { - while (sp > mk) { - popNode(); - } - mk = ((Integer)marks.pop()).intValue(); - } - - - public void openNodeScope(Node n) { - marks.push(new Integer(mk)); - mk = sp; - n.jjtOpen(); - } - - - /* A definite node is constructed from a specified number of - children. That number of nodes are popped from the stack and - made the children of the definite node. Then the definite node - is pushed on to the stack. */ - public void closeNodeScope(Node n, int num) { - mk = ((Integer)marks.pop()).intValue(); - while (num-- > 0) { - Node c = popNode(); - c.jjtSetParent(n); - n.jjtAddChild(c, num); - } - n.jjtClose(); - pushNode(n); - node_created = true; - } - - - /* A conditional node is constructed if its condition is true. All - the nodes that have been pushed since the node was opened are - made children of the the conditional node, which is then pushed - on to the stack. If the condition is false the node is not - constructed and they are left on the stack. */ - public void closeNodeScope(Node n, boolean condition) { - if (condition) { - int a = nodeArity(); - mk = ((Integer)marks.pop()).intValue(); - while (a-- > 0) { - Node c = popNode(); - c.jjtSetParent(n); - n.jjtAddChild(c, a); - } - n.jjtClose(); - pushNode(n); - node_created = true; - } else { - mk = ((Integer)marks.pop()).intValue(); - node_created = false; - } - } -} diff --git a/src/FESI/AST/Node.java b/src/FESI/AST/Node.java deleted file mode 100644 index 18fa417a..00000000 --- a/src/FESI/AST/Node.java +++ /dev/null @@ -1,37 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. Node.java */ - -package FESI.AST; - -/* All AST nodes must implement this interface. It provides basic - machinery for constructing the parent and child relationships - between nodes. */ - -public interface Node { - - /** This method is called after the node has been made the current - node. It indicates that child nodes can now be added to it. */ - public void jjtOpen(); - - /** This method is called after all the child nodes have been - added. */ - public void jjtClose(); - - /** This pair of methods are used to inform the node of its - parent. */ - public void jjtSetParent(Node n); - public Node jjtGetParent(); - - /** This method tells the node to add its argument to the node's - list of children. */ - public void jjtAddChild(Node n, int i); - - /** This method returns a child node. The children are numbered - from zero, left to right. */ - public Node jjtGetChild(int i); - - /** Return the number of children the node has. */ - public int jjtGetNumChildren(); - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data); -} \ No newline at end of file diff --git a/src/FESI/AST/SimpleNode.java b/src/FESI/AST/SimpleNode.java deleted file mode 100644 index 3e74dec2..00000000 --- a/src/FESI/AST/SimpleNode.java +++ /dev/null @@ -1,129 +0,0 @@ -/* Generated By:JJTree: Do not edit this line. SimpleNode.java */ - -package FESI.AST; - -import FESI.Parser.*; -import FESI.Exceptions.*; - -public abstract class SimpleNode implements Node, EcmaScriptConstants { - protected Node parent; - protected Node[] children; - protected int id; - protected EcmaScript parser; - protected int line = 0; // JMCL - - public SimpleNode(int i) { - id = i; - } - - public SimpleNode(EcmaScript p, int i) { - this(i); - parser = p; - } - - public void jjtOpen() { - } - - public void jjtClose() { - } - - public void jjtSetParent(Node n) { parent = n; } - public Node jjtGetParent() { return parent; } - - public void jjtAddChild(Node n, int i) { - if (children == null) { - children = new Node[i + 1]; - } else if (i >= children.length) { - Node c[] = new Node[i + 1]; - System.arraycopy(children, 0, c, 0, children.length); - children = c; - } - children[i] = n; - } - - public Node jjtGetChild(int i) { - return children[i]; - } - - public int jjtGetNumChildren() { - return (children == null) ? 0 : children.length; - } - - /** Accept the visitor. **/ - public Object jjtAccept(EcmaScriptVisitor visitor, Object data) { - return visitor.visit(this, data); - } - - /** Accept the visitor. **/ - public Object childrenAccept(EcmaScriptVisitor visitor, Object data) { - if (children != null) { - for (int i = 0; i < children.length; ++i) { - children[i].jjtAccept(visitor, data); - } - } - return data; - } - - /* You can override these two methods in subclasses of SimpleNode to - customize the way the node appears when the tree is dumped. If - your output uses more than one line you should override - toString(String), otherwise overriding toString() is probably all - you need to do. */ - - // JMCL - public String toString() { - return EcmaScriptTreeConstants.jjtNodeName[id]; - } - public String toString(String prefix) { return prefix + toString(); } - - /* Override this method if you want to customize how the node dumps - out its children. */ - - public void dump(String prefix) { - System.out.println(toString(prefix)); - if (children != null) { - for (int i = 0; i < children.length; ++i) { - SimpleNode n = (SimpleNode)children[i]; - if (n != null) { - n.dump(prefix + " "); - } - } - } - } - - // JMCL - public void setLineNumber(int line) { - this.line = line; - } - - public int getLineNumber() { - return line; - } - - public void assertNoChildren() { - if (jjtGetNumChildren()>0) { - throw new ProgrammingError("AST Should have no children"); - } - } - public void assertOneChild() { - if (jjtGetNumChildren()!=1) { - throw new ProgrammingError("AST Should have 1 child"); - } - } - public void assertTwoChildren() { - if (jjtGetNumChildren()!=2) { - throw new ProgrammingError("AST Should have 2 children"); - } - } - public void assertThreeChildren() { - if (jjtGetNumChildren()!=3) { - throw new ProgrammingError("AST Should have 3 children"); - } - } - public void assertFourChildren() { - if (jjtGetNumChildren()!=4) { - throw new ProgrammingError("AST Should have 4 children"); - } - } - -} \ No newline at end of file diff --git a/src/FESI/ClassFile/Attribute.java b/src/FESI/ClassFile/Attribute.java deleted file mode 100644 index a484b19e..00000000 --- a/src/FESI/ClassFile/Attribute.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * - * @(#) Attribute.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.Attribute - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ConstantPoolEntry; -import FESI.ClassFile.UTF8Constant; - -/** - *

- * The Attribute class is an abstract base class for all Attribute types - * found in the Java VM ClassFile format specification. This is a simple - * implementationd designed to support the minimal functionaliuty required - * to emit a valid ClassFile stream. - *

- */ - -abstract class Attribute { - - final static String SOURCEFILE = "SourceFile"; - final static String CONSTANTVALUE = "ConstantValue"; - final static String LOCALVARIABLETABLE = "LocalVariableTable"; - final static String EXCEPTIONS = "Exceptions"; - final static String LINENUMBERTABLE = "LineNumberTable"; - final static String CODE = "Code"; - - private UTF8Constant name; - private ClassFile classFile; - - /** - *

Construct an Attribute, enter it into the ConstantPool.

- */ - - protected Attribute(String n, ClassFile cf) { - UTF8Constant utf8 = (UTF8Constant) - cf.match(ConstantPoolEntry.CONSTANT_UTF8, (Object)n); - - if (utf8 == null) utf8 = new UTF8Constant(n, cf); - - name = utf8; - classFile = cf; - } - - /** - * @return the ClassFile this Attribute is contained within - */ - - ClassFile getClassFile() { return classFile; } - - /** - * @return the "name" of the Attribute. - */ - - String getName() { return name.getString(); } - - /** - * @return get the index of this Attribute in the ConstantPool - */ - - short getNameConstantPoolIndex() { - return name.getConstantPoolIndex(); - } - - /** - * @return the length of the attribute as defined by the concrete subclass. - */ - - abstract int getLength(); - - /** - *

write the concrete Attribute subclass to the stream

- * - * @throws IOException - */ - - abstract void write(DataOutputStream dos) throws IOException; - - /** - *

Compare this Attribute with the object and return equality.

- * - * @return is it equal - */ - - abstract public boolean equals(Object o); - -} diff --git a/src/FESI/ClassFile/ClassConstant.java b/src/FESI/ClassFile/ClassConstant.java deleted file mode 100644 index 2e8dac53..00000000 --- a/src/FESI/ClassFile/ClassConstant.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * - * @(#) ClassConstant.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.ClassConstant - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ConstantPoolEntry; -import FESI.ClassFile.UTF8Constant; - -class ClassConstant extends ConstantPoolEntry { - - private UTF8Constant name; - - /** - *

Construct a CONSTANT_CLASS constant pool entry

- */ - - ClassConstant(String className, ClassFile cf) { - super(CONSTANT_CLASS, cf); - - name = cf.addUTF8Constant(ClassFile.fullyQualifiedForm(className)); - - addToConstantPool(); - } - - /** - *

write the CONSTANT_CLASS to the stream

- * - * @param dos the stream. - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - - if (debug()) { - System.err.println(getConstantPoolIndex() + - " CLASS: " + - name.getConstantPoolIndex() - ); - } - - dos.writeByte(getTag()); - dos.writeShort(name.getConstantPoolIndex()); - } - - /** - *

return the class represented by the CONSTANT_CLASS

- * - * @return the name of the class - */ - - String getClassName() { return name.getString(); } - - /** - *

returns the Class object for the class represented by the constant.

- * - * @return The java.lang.Class object for the class. - */ - - Class getClassObject() throws ClassNotFoundException { - return Class.forName(name.getString()); - } - - /** - *

compare the object, by name or value.

- * - * @param the object for comparison - * - * @return object equality. - */ - - public boolean equals(Object o) { - if (o == null) return false; - - if (o instanceof String) { - return ((String)o).equals(name.getString()); - } else if (o instanceof ClassConstant) { - ClassConstant cc = (ClassConstant)o; - - return name.getString().equals(cc.getClassName()); - } - - return false; - } -} diff --git a/src/FESI/ClassFile/ClassFile.java b/src/FESI/ClassFile/ClassFile.java deleted file mode 100644 index 9e82d9c2..00000000 --- a/src/FESI/ClassFile/ClassFile.java +++ /dev/null @@ -1,469 +0,0 @@ -/* - * - * @(#) ClassFile.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.ClassFile - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import java.util.Vector; - -import FESI.ClassFile.Attribute; -import FESI.ClassFile.ClassConstant; -import FESI.ClassFile.ConstantPoolEntry; -import FESI.ClassFile.FieldDesc; -import FESI.ClassFile.MethodDesc; - -/** - *

- * The ClassFile class is designed to provide lightweight, minimal support - * for the runtime construction of Java VM ClassFile's, or Class - * implementations. - *

- *

- * The ClassFile provides API's to construct an in-core description of a - * Java class implementation, and subsequently write that description to - * a stream which may then be either loaded into the VM via a ClassLoader - * or written to some persistent store. - *

- *

- * It should be noted that the ClassFile provide little or no validation of - * the Class it describes during the construction of that description, and - * therefore users of this class and package should be familiar with the - * contents of the Java VM Specification published by Addison-Wesley. - *

- */ - -final class ClassFile { - - /** - *

the magic number for Java VM class files.

- */ - - final private static int MAGIC = 0xcafebabe; - - /** - *

the major and minor version numbers for Java VM class files.

- */ - - final private static short MAJOR = 45; - final private static short MINOR = 3; - - /** - *

the access flags constants for Java VM class files.

- */ - - final static short ACC_PUBLIC = 0x0001; - final static short ACC_FINAL = 0x0010; - final static short ACC_SUPER = 0x0020; - final static short ACC_INTERFACE = 0x0200; - final static short ACC_ABSTRACT = 0x0400; - - /* - * inst vars represent the format of the classfile itself. - */ - - private Vector constantPool = new Vector(1); - - private short accessFlags = (short)(ACC_PUBLIC | ACC_SUPER); - - private ClassConstant thisClass; - private ClassConstant superClass; - - private Vector interfaces; - private Vector fields; - private Vector methods; - private Vector attributes; - - /** - * @return are we debuging (used to print audit trail). - */ - - static boolean debug() { return false; } - - /** - *

Construct a new ClassFile object.

- * - * @param tClass name of "this" class - * - * @param sClass name of superclass - * - */ - - ClassFile(String tClass, String sClass) { - thisClass = addClassConstant(tClass); - superClass = addClassConstant(sClass); - } - - /** - *

Write the constant pool to the stream

- * - * @param dos the stream to write to. - */ - - private void writeConstantPool(DataOutputStream dos) throws IOException { - - if (debug()) System.err.println("write constant pool: " + constantPool.size()); - - dos.writeShort(constantPool.size() + 1); // for index zero - - for (int i = 0; i < constantPool.size(); i++) { - ((ConstantPoolEntry)constantPool.elementAt(i)).write(dos); - } - } - - /** - *

Write the list of interfaces to the stream

- * - * @param dos the stream to write to. - */ - - private void writeInterfaces(DataOutputStream dos) throws IOException { - if (interfaces != null) { - if (debug()) System.err.println("write interfaces: " + interfaces.size()); - dos.writeShort(interfaces.size()); - - for (int i = 0; i < interfaces.size(); i++) { - dos.writeShort( - ((ConstantPoolEntry)interfaces.elementAt(i)).getConstantPoolIndex() - ); - } - } else dos.writeShort(0); - } - - /** - *

Write the list of Fields defs to the stream

- * - * @param dos the stream to write to. - */ - - private void writeFields(DataOutputStream dos) throws IOException { - if (fields != null) { - if (debug()) System.err.println("write fields: " + fields.size()); - - dos.writeShort(fields.size()); - - for (int i = 0; i < fields.size(); i++) { - ((FieldDesc)fields.elementAt(i)).write(dos); - } - } else dos.writeShort(0); - } - - /** - *

Write the list of Method defs to the stream.

- * - * @param dos the stream to write to. - */ - - private void writeMethods(DataOutputStream dos) throws IOException { - if (methods != null) { - if (debug()) System.err.println("write methods: " + methods.size()); - - dos.writeShort(methods.size()); - - for (int i = 0; i < methods.size(); i++) { - ((MethodDesc)methods.elementAt(i)).write(dos); - } - } else dos.writeShort(0); - - } - - /** - *

Write the list of Attributes to the stream

- * - * @param dos the stream to write to. - */ - - private void writeAttributes(DataOutputStream dos) throws IOException { - if (attributes != null) { - if (debug()) System.err.println("write attributes: " + attributes.size()); - - dos.writeShort(attributes.size()); - - for (int i = 0; i < attributes.size(); i++) { - ((Attribute)attributes.elementAt(i)).write(dos); - } - } else dos.writeShort(0); - } - - /** - *

Write the ClassFile to the Stream

- * - * @param os the stream to write to. - */ - - public synchronized void write(OutputStream os) throws IOException { - DataOutputStream dos = new DataOutputStream(os); - - try { - dos.writeInt(MAGIC); - - dos.writeShort(MINOR); - dos.writeShort(MAJOR); - - writeConstantPool(dos); - - if (debug()) System.err.println("access: " + accessFlags); - - dos.writeShort(accessFlags); - - dos.writeShort(thisClass.getConstantPoolIndex()); - dos.writeShort(superClass.getConstantPoolIndex()); - - writeInterfaces(dos); - - writeFields(dos); - - writeMethods(dos); - - writeAttributes(dos); - - dos.close(); // all done! - } catch (IOException ioe) { - System.err.println("Bad IO"); - } catch (Exception e) { - System.err.println("Oops"); - } - } - - /** - *

Add an entry to the Constant Pool.

- * - * @param cpe the new constant pool entry - * - * @return the index of the new entry in the pool - */ - - public synchronized short addConstantPoolEntry(ConstantPoolEntry cpe) { - if (!constantPool.contains(cpe)) constantPool.addElement(cpe); - - return (short)(constantPool.indexOf(cpe) + 1); - } - - /** - *

Find a matching Constant Pool Entry.

- * - * @param tag The tag value of the constant pool entries to match on. - * @param value The value to match on. - * - * @return the matching entry or null. - */ - - synchronized ConstantPoolEntry match(byte tag, Object value) { - for (int i = 0; i < constantPool.size(); i++) { - ConstantPoolEntry cpe = (ConstantPoolEntry)constantPool.elementAt(i); - - if (cpe.getTag() == tag && cpe.equals(value)) - return cpe; - } - - return null; - } - - /** - * @return the current value of the accessFlags. - */ - - public synchronized short getAccessFlags() { return accessFlags; } - - /** - *

modify the value of the Class File's access flags

- * - * @param newf the new flag values. [NOT VALIDATED] - */ - - public synchronized void setAccessFlags(short newf) { - - // TODO - verify new flag combination. - - accessFlags = newf; - } - - /** - * @param newMethod the method desc to add to the class file. - */ - - public synchronized void addMethodDesc(MethodDesc newMethod) { - if (methods == null) methods = new Vector(1); - - methods.addElement(newMethod); - } - - /** - * @param newField the field desc to add to the class file. - */ - - public synchronized void addFieldDesc(FieldDesc newField) { - if (fields == null) fields = new Vector(1); - - fields.addElement(newField); - } - - /** - * @param sConstant add a CONSTANT_STRING to the ClassFile. - * - * @param sConstant the string value to add. - * - * @return The new StringConstant - */ - - public StringConstant addStringConstant(String sConstant) { - UTF8Constant c = (UTF8Constant)match(ConstantPoolEntry.CONSTANT_UTF8, sConstant); - - if (c == null) { - c = new UTF8Constant(sConstant, this); - } - - StringConstant s = new StringConstant(c, this); - - return s; - } - - /** - *

Add a new CONSTANT_INTEGER to the Constant Pool

- * - * @param iConstant the integer value to add. - * - * @return the new IntegerConstant. - */ - - public IntegerConstant addIntegerConstant(int iConstant) { - IntegerConstant c = (IntegerConstant)match(ConstantPoolEntry.CONSTANT_INTEGER, new Integer(iConstant)); - - if (c == null) { - c = new IntegerConstant(iConstant, this); - } - - return c; - } - - /** - *

Add a new UTF8_CONSTANT to the constant pool

- * - * @param sConstant the string to add. - * - * @return the new UUTF8Constant - */ - - public UTF8Constant addUTF8Constant(String sConstant) { - UTF8Constant c = (UTF8Constant)match(ConstantPoolEntry.CONSTANT_UTF8, sConstant); - - if (c == null) { - c = new UTF8Constant(sConstant, this); - } - - return c; - } - - /** - *

add a new CONSTANT_CLASS to the Constant Pool

- * - * @param classConstant the name of the class to add - * - * @return the newly ClassConstant - */ - - public ClassConstant addClassConstant(String classConstant) { - ClassConstant c = (ClassConstant)match(ConstantPoolEntry.CONSTANT_CLASS, classConstant); - - if (c == null) { - c = new ClassConstant(classConstant, this); - } - - return c; - } - - /** - *

add a CONSTANT_METHOD to the constant pool

- * - * @param cName the name of the defining class - * @param mName the method name - * @param tName the fully qualified type descriptor for the method - * - * @return the new created CONSTANT_METHOD - */ - - public MethodConstant addMethodConstant(String cName, String mName, String tName) { - return new MethodConstant(cName, mName, tName, this); - } - - /** - * - * - * @param cName the name of the defining class - * @param fName the name of the field - * @param tName the fully qualified type descriptor of the field - * - * @return the new created CONSTANT_FIELD - */ - - public FieldConstant addFieldConstant(String cName, String fName, String tName) { - return new FieldConstant(cName, fName, tName, this); - } - - /** - *

add the name of an interface this class implements to the constant pool

- * - * @param iName the name of the interface - */ - - public void addInterface(String iName) { - if (interfaces == null) interfaces = new Vector(1); - - interfaces.addElement((Object)addClassConstant(iName)); - } - - /** - *

- * convenience routine to take a type name and map it to the internal form. - * java.lang.Object -> java/lang/Object - *

- * - * @param str the string to map - * - * @return the mapped string value. - */ - - public static String fullyQualifiedForm(String str) { - return str.replace('.', '/'); - } - - - /** - *

- * convenience routine to construct type descriptors from fully - * qualified names, e.g: java.lang.Object => Ljava/lang/Object; - *

- * - * @param str name of a java "type" - * - * @return the class descriptor. - */ - - public static String fieldType(String str) { - return "L" + ClassFile.fullyQualifiedForm(str) + ";"; - } - -} diff --git a/src/FESI/ClassFile/Code.java b/src/FESI/ClassFile/Code.java deleted file mode 100644 index 9639c761..00000000 --- a/src/FESI/ClassFile/Code.java +++ /dev/null @@ -1,702 +0,0 @@ -/* - * - * @(#) Code.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.Code - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - - -import java.io.DataOutputStream; -import java.io.IOException; - -import java.util.Vector; - -import FESI.ClassFile.Attribute; -import FESI.ClassFile.ClassConstant; - -/** - *

- * The Code attribute is defined to describe the implementation for each - * Method Implementation in a class. In particular it contains the byte - * codes and exception information. - *

- */ - -final class Code extends Attribute { - - final static byte OP_NOP = (byte) 0x00; - final static byte OP_ACONST_NULL = (byte) 0x01; - - // int consts - - final static byte OP_ICONST_m1 = (byte) 0x02; - final static byte OP_ICONST_0 = (byte) 0x03; - final static byte OP_ICONST_1 = (byte) 0x04; - final static byte OP_ICONST_2 = (byte) 0x05; - final static byte OP_ICONST_3 = (byte) 0x06; - final static byte OP_ICONST_4 = (byte) 0x07; - final static byte OP_ICONST_5 = (byte) 0x08; - - // long consts - - final static byte OP_LCONST_0 = (byte) 0x09; - final static byte OP_LCONST_1 = (byte) 0x0A; - - // float consts - - final static byte OP_FCONST_0 = (byte) 0x0B; - final static byte OP_FCONST_1 = (byte) 0x0C; - final static byte OP_FCONST_2 = (byte) 0x0D; - - // double consts - - final static byte OP_DCONST_0 = (byte) 0x0E; - final static byte OP_DCONST_1 = (byte) 0x0F; - - final static byte OP_BIPUSH = (byte) 0x10; - final static byte OP_SIPUSH = (byte) 0x11; - - final static byte OP_LDC = (byte) 0x12; - final static byte OP_LDC_WIDE = (byte) 0x13; - final static byte OP_LDC2_WIDE = (byte) 0x14; - - - // typed loads local - - final static byte OP_ILOAD = (byte) 0x15; - final static byte OP_LLOAD = (byte) 0x16; - final static byte OP_FLOAD = (byte) 0x17; - final static byte OP_DLOAD = (byte) 0x18; - final static byte OP_ALOAD = (byte) 0x19; - - // int loads - - final static byte OP_ILOAD_0 = (byte) 0x1A; - final static byte OP_ILOAD_1 = (byte) 0x1B; - final static byte OP_ILOAD_2 = (byte) 0x1C; - final static byte OP_ILOAD_3 = (byte) 0x1D; - - // long loads - - final static byte OP_LLOAD_0 = (byte) 0x1E; - final static byte OP_LLOAD_1 = (byte) 0x1F; - final static byte OP_LLOAD_2 = (byte) 0x20; - final static byte OP_LLOAD_3 = (byte) 0x21; - - // float loads - - final static byte OP_FLOAD_0 = (byte) 0x22; - final static byte OP_FLOAD_1 = (byte) 0x23; - final static byte OP_FLOAD_2 = (byte) 0x24; - final static byte OP_FLOAD_3 = (byte) 0x25; - - // double loads - - final static byte OP_DLOAD_0 = (byte) 0x26; - final static byte OP_DLOAD_1 = (byte) 0x27; - final static byte OP_DLOAD_2 = (byte) 0x28; - final static byte OP_DLOAD_3 = (byte) 0x29; - - // ref loads - - final static byte OP_ALOAD_0 = (byte) 0x2A; - final static byte OP_ALOAD_1 = (byte) 0x2B; - final static byte OP_ALOAD_2 = (byte) 0x2C; - final static byte OP_ALOAD_3 = (byte) 0x2D; - - final static byte OP_IALOAD = (byte) 0x2E; - final static byte OP_LALOAD = (byte) 0x2F; - - // array loads - - final static byte OP_FALOAD = (byte) 0x30; - final static byte OP_DALOAD = (byte) 0x31; - final static byte OP_AALOAD = (byte) 0x32; - final static byte OP_BALOAD = (byte) 0x33; - final static byte OP_CALOAD = (byte) 0x34; - final static byte OP_SALOAD = (byte) 0x35; - - final static byte OP_ISTORE = (byte) 0x36; - final static byte OP_LSTORE = (byte) 0x37; - final static byte OP_FSTORE = (byte) 0x38; - final static byte OP_DSTORE = (byte) 0x39; - final static byte OP_ASTORE = (byte) 0x3A; - - // int stores - - final static byte OP_ISTORE_0 = (byte) 0x3B; - final static byte OP_ISTORE_1 = (byte) 0x3C; - final static byte OP_ISTORE_2 = (byte) 0x3D; - final static byte OP_ISTORE_3 = (byte) 0x3E; - - // long stores - - final static byte OP_LSTORE_0 = (byte) 0x3F; - final static byte OP_LSTORE_1 = (byte) 0x40; - final static byte OP_LSTORE_2 = (byte) 0x41; - final static byte OP_LSTORE_3 = (byte) 0x42; - - // float stores - - final static byte OP_FSTORE_0 = (byte) 0x43; - final static byte OP_FSTORE_1 = (byte) 0x44; - final static byte OP_FSTORE_2 = (byte) 0x45; - final static byte OP_FSTORE_3 = (byte) 0x46; - - // double stores - - final static byte OP_DSTORE_0 = (byte) 0x47; - final static byte OP_DSTORE_1 = (byte) 0x48; - final static byte OP_DSTORE_2 = (byte) 0x49; - final static byte OP_DSTORE_3 = (byte) 0x4A; - - // ref stores - - final static byte OP_ASTORE_0 = (byte) 0x4B; - final static byte OP_ASTORE_1 = (byte) 0x4C; - final static byte OP_ASTORE_2 = (byte) 0x4D; - final static byte OP_ASTORE_3 = (byte) 0x4E; - - final static byte OP_IASTORE = (byte) 0x4F; - - // array stores - - final static byte OP_LASTORE = (byte) 0x50; - final static byte OP_FASTORE = (byte) 0x51; - final static byte OP_DASTORE = (byte) 0x52; - final static byte OP_AASTORE = (byte) 0x53; - final static byte OP_BASTORE = (byte) 0x54; - final static byte OP_CASTORE = (byte) 0x55; - final static byte OP_SASTORE = (byte) 0x56; - - final static byte OP_POP = (byte) 0x57; - final static byte OP_POP2 = (byte) 0x58; - - // dup's - - final static byte OP_DUP = (byte) 0x59; - final static byte OP_DUP_X1 = (byte) 0x5A; - final static byte OP_DUP_X2 = (byte) 0x5B; - final static byte OP_DUP2 = (byte) 0x5C; - final static byte OP_DUP2_X1 = (byte) 0x5D; - final static byte OP_DUP2_X2 = (byte) 0x5E; - final static byte OP_SWAP = (byte) 0x5F; - - // arith - - final static byte OP_IADD = (byte) 0x60; - final static byte OP_LADD = (byte) 0x61; - final static byte OP_FADD = (byte) 0x62; - final static byte OP_DADD = (byte) 0x63; - - final static byte OP_ISUB = (byte) 0x64; - final static byte OP_LSUB = (byte) 0x65; - final static byte OP_FSUB = (byte) 0x66; - final static byte OP_DSUB = (byte) 0x67; - - final static byte OP_IMUL = (byte) 0x68; - final static byte OP_LMUL = (byte) 0x69; - final static byte OP_FMUL = (byte) 0x6A; - final static byte OP_DMUL = (byte) 0x6B; - - final static byte OP_IDIV = (byte) 0x6C; - final static byte OP_FDIV = (byte) 0x6E; - final static byte OP_LDIV = (byte) 0x6D; - final static byte OP_DDIV = (byte) 0x6F; - - // arith misc - - final static byte OP_IREM = (byte) 0x70; - final static byte OP_LREM = (byte) 0x71; - final static byte OP_FREM = (byte) 0x72; - final static byte OP_DREM = (byte) 0x73; - - final static byte OP_INEG = (byte) 0x74; - final static byte OP_LNEG = (byte) 0x75; - final static byte OP_FNEG = (byte) 0x76; - final static byte OP_DNEG = (byte) 0x77; - - final static byte OP_ISHL = (byte) 0x78; - final static byte OP_LSHL = (byte) 0x79; - - final static byte OP_ISHR = (byte) 0x7A; - final static byte OP_LSHR = (byte) 0x7B; - - final static byte OP_IUSHR = (byte) 0x7C; - final static byte OP_LUSHR = (byte) 0x7D; - - final static byte OP_IAND = (byte) 0x7E; - final static byte OP_LAND = (byte) 0x7F; - - final static byte OP_IOR = (byte) 0x80; - final static byte OP_LOR = (byte) 0x81; - - final static byte OP_IXOR = (byte) 0x82; - final static byte OP_LXOR = (byte) 0x83; - - // local int += const - - final static byte OP_IINC = (byte) 0x84; - - // int conversions - - final static byte OP_I2L = (byte) 0x85; - final static byte OP_I2F = (byte) 0x86; - final static byte OP_I2D = (byte) 0x87; - - // long conversions - - final static byte OP_L2I = (byte) 0x88; - final static byte OP_L2F = (byte) 0x89; - final static byte OP_L2D = (byte) 0x8A; - - // float conversions - - final static byte OP_F2I = (byte) 0x8B; - final static byte OP_F2L = (byte) 0x8C; - final static byte OP_F2D = (byte) 0x8D; - - // double conversions - - final static byte OP_D2I = (byte) 0x8E; - final static byte OP_D2L = (byte) 0x8F; - final static byte OP_D2F = (byte) 0x90; - - // int conversions - - final static byte OP_I2B = (byte) 0x91; - final static byte OP_I2C = (byte) 0x92; - final static byte OP_I2S = (byte) 0x93; - - // long comparision's - - final static byte OP_LCMP = (byte) 0x94; - - // float comparision's - - final static byte OP_FCMPL = (byte) 0x95; - final static byte OP_FCMPG = (byte) 0x96; - - // double comparision's - - final static byte OP_DCMPL = (byte) 0x97; - final static byte OP_DCMPG = (byte) 0x98; - - // int to zero comparisions - - final static byte OP_IFEQ = (byte) 0x99; - final static byte OP_IFNE = (byte) 0x9A; - final static byte OP_IFLT = (byte) 0x9B; - final static byte OP_IFGE = (byte) 0x9C; - final static byte OP_IFGT = (byte) 0x9D; - final static byte OP_IFLE = (byte) 0x9E; - - // int to int comparision's - - final static byte OP_IFICMPEQ = (byte) 0x9F; - final static byte OP_IFICMPNE = (byte) 0xA0; - final static byte OP_IFICMPLT = (byte) 0xA1; - final static byte OP_IFICMPGE = (byte) 0xA2; - final static byte OP_IFICMPGT = (byte) 0xA3; - final static byte OP_IFICMPLE = (byte) 0xA4; - - // ref comparisions - - final static byte OP_IFACMPEQ = (byte) 0xA5; - final static byte OP_IFACMPNE = (byte) 0xA6; - - // goto - - final static byte OP_GOTO = (byte) 0xA7; - - final static byte OP_JSR = (byte) 0xA8; - - final static byte OP_RET = (byte) 0xA9; - - final static byte OP_TABLESWITCH = (byte) 0xAA; - - final static byte OP_LOOKUP_SWITCH = (byte) 0xAB; - - - // return's - - final static byte OP_IRETURN = (byte) 0xAC; - final static byte OP_LRETURN = (byte) 0xAD; - final static byte OP_FRETURN = (byte) 0xAE; - final static byte OP_DRETURN = (byte) 0xAF; - final static byte OP_ARETURN = (byte) 0xB0; - final static byte OP_RETURN = (byte) 0xB1; - - - // getfield's - - final static byte OP_GETSTATIC = (byte) 0xB2; - final static byte OP_GETFIELD = (byte) 0xB4; - - // invoke virtual - - final static byte OP_INVOKE_VIRTUAL = (byte) 0xB6; - - // invoke static - - final static byte OP_INVOKE_STATIC = (byte) 0xB8; - - // method invocation - - final static byte OP_INVOKE_SPECIAL = (byte) 0xB7; - - // invoke interface - - final static byte OP_INVOKE_INTERFACE = (byte) 0xB9; - - // new - - final static byte OP_NEW = (byte) 0xBB; - - // array misc - - final static byte OP_NEWARRAY = (byte) 0xBD; - - final static byte ARRAY_T_BOOLEAN = (byte) 0x4; - final static byte ARRAY_T_CHAR = (byte) 0x5; - final static byte ARRAY_T_FLOAT = (byte) 0x6; - final static byte ARRAY_T_DOUBLE = (byte) 0x7; - final static byte ARRAY_T_BYTE = (byte) 0x8; - final static byte ARRAY_T_SHORT = (byte) 0x9; - final static byte ARRAY_T_INT = (byte) 0xA; - final static byte ARRAY_T_LONG = (byte) 0xB; - - // putfield's - - final static byte OP_PUTSTATIC = (byte) 0xB3; - final static byte OP_PUTFIELD = (byte) 0xB5; - - // array's - - final static byte OP_ANEWARRAY = (byte) 0xBD; - final static byte OP_ARRAYLENGTH = (byte) 0xBE; - - // exceptions - - final static byte OP_ATHROW = (byte) 0xBF; - - // cast - - final static byte OP_CHECKCAST = (byte) 0xC0; - - // instanceof - - final static byte OP_INSTANCEOF = (byte) 0xC1; - - // monitor - - final static byte OP_MONITOR_ENTER = (byte) 0xC2; - final static byte OP_MONITOR_EXIT = (byte) 0xC3; - - // wide - - final static byte OP_WIDE = (byte) 0xC4; - - // arrays - - final static byte OP_MULTI_NEW_ARRAY = (byte) 0xC5; - - // compare to null - - final static byte OP_IFNULL = (byte) 0xc6; - final static byte OP_IFNONNULL = (byte) 0xc7; - - // goto wide - - final static byte OP_GOTO_WIDE = (byte) 0xc8; - - final static byte OP_JSR_WIDE = (byte) 0xc9; - - - /* - * inst vars - */ - - private Vector attributes; - - private int length = 12; // starting value - - private short currentPC; - - private short maxLocals; - - private short maxStack; - - private Vector byteCodes = new Vector(1); - - private Vector exceptions; - - /** - *

construct a Code Attribute

- * - * @param locals number of words used to describe local vars - * @param maxstack max number of stack words used. - * - */ - - Code(ClassFile cf, short locals, short stack) { - super(CODE, cf); - - maxLocals = (locals >= 0 ? locals : 0); - maxStack = (stack > 2 ? stack : 2); - } - - /** - *

write the code attribute to the stream

- * - * @param dos the output stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - int i; - - dos.writeShort(getNameConstantPoolIndex()); - dos.writeInt(getLength()); - dos.writeShort(maxStack); - dos.writeShort(maxLocals); - - // write the code ... - - dos.writeInt(byteCodes.size()); - - for (i = 0; i < byteCodes.size(); i++) { - dos.writeByte(((Byte)byteCodes.elementAt(i)).byteValue()); - } - - // write exceptions (if any) - - if (exceptions != null) { - dos.writeShort(exceptions.size()); - - for (i = 0; i < exceptions.size(); i++) { - ((ExceptionTableEntry)exceptions.elementAt(i)).write(dos); - } - } else dos.writeShort(0); - - // write attributes (if any) - - if (attributes != null) { - dos.writeShort(attributes.size()); - - for (i = 0; i < attributes.size(); i ++) { - ((Attribute)attributes.elementAt(i)).write(dos); - } - } else dos.writeShort(0); - } - - /** - *

returns the length of the Code attribute in bytes

- * - * @return the length of the attribute. - */ - - int getLength() { return length; } - - /** - * @return object equality. - */ - - public boolean equals(Object o) { - return ((Object)this).equals(o); - } - - /** - * @return the current PC offset from the start of the method. - */ - - short getCurrentPC() { return currentPC; } - - /** - *

- * adds per Code attribute, can be used for SourceFile, LocalVariable, - * and LineNumberTable attributes etc. - *

- * - * @param attr Attribte to be added. - */ - - void addAttribute(Attribute attr) { - if (attributes == null) attributes = new Vector(1); - - attributes.addElement(attr); - length += attr.getLength() + 6; // sizeof(Attribute) - } - - /** - *

- * Adds an entry to the Exception handler table for this Code attribute. - * An entry describes the start and stop pc offset within the Code fragment - * for which an exception handler is provided, the start pc of the handler - * code within the fragment itself, and the class of the exception type - * for this handler. - *

- * - * @param start start pc offset for this exception handler range - * @param stop stop pc offset for this exception handler range - * @param handler handler pc start offset for this exception - * @param ct CONSTANT_CLASS describing the exception class handled - */ - - void addExceptionTableEntry(short start, short stop, - short handler, ClassConstant ct) { - exceptions.addElement( - new ExceptionTableEntry(start, stop, handler, ct) - ); - - length += 8; // sizeof(ExceptionTableEntry) - } - - /** - *

add an opcode to the implementation

- */ - - void addOp(byte opCode) { - byteCodes.addElement(new Byte(opCode)); - currentPC++; - length++; - } - - /** - *

add an opcode and a 1 byte operand

- */ - - void addOp1(byte opCode, byte op1) { - byteCodes.addElement(new Byte(opCode)); - byteCodes.addElement(new Byte(op1)); - currentPC += 2; - length += 2; - } - - /** - *

add an opcode and 2, 1 byte operands

- */ - - void addOp2(byte opCode, byte op1, byte op2) { - byteCodes.addElement(new Byte(opCode)); - byteCodes.addElement(new Byte(op1)); - byteCodes.addElement(new Byte(op2)); - currentPC += 3; - length += 3; - } - - /** - *

add an opcode and 4, 1 byte operands

- */ - - void addOp4(byte opCode, byte op1, byte op2, byte op3, byte op4) { - byteCodes.addElement(new Byte(opCode)); - byteCodes.addElement(new Byte(op1)); - byteCodes.addElement(new Byte(op2)); - byteCodes.addElement(new Byte(op3)); - byteCodes.addElement(new Byte(op4)); - currentPC += 5; - length += 5; - - } - - /** - *

add an opcode and a 2 byte operand

- */ - - void addOpShort(byte opCode,short op) { - addOp2(opCode, - (byte)((op >>> 8) & 0xff), - (byte)( op & 0xff) - ); - } - - /** - *

add an opcode and a 4 byte operand

- */ - - void addOpInt(byte opCode,int op) { - addOp4(opCode, - (byte)((op >>> 24) & 0xff), - (byte)((op >>> 16) & 0xff), - (byte)((op >>> 8) & 0xff), - (byte)( op & 0xff) - ); - } - - /** - *

increment the local word count

- * - * @param n the number of local words to increment by. - */ - - void incrLocals(short n) { maxLocals += n; } - - /** - *

increment the max operand stack word count

- * - * @param n the number of words to increment the max stack count by - */ - - void incrMaxStack(short n) { maxStack += n; } -} - -/* - * private implementation class to represent exception table entries. - */ - -final class ExceptionTableEntry { - private short startPC; - private short stopPC; - private short handlerPC; - private ClassConstant exceptionType; - - /* - * construct and Exception Table Entry - */ - - ExceptionTableEntry(short start, short stop, - short handler, ClassConstant eType) { - super(); - - startPC = start; - stopPC = stop; - handlerPC = handler; - exceptionType = eType; - } - - /* - * wrote the exception table entry to the stream - */ - - void write(DataOutputStream dos) throws IOException { - dos.writeShort(startPC); - dos.writeShort(stopPC); - dos.writeShort(handlerPC); - if (exceptionType != null) - dos.writeShort(exceptionType.getConstantPoolIndex()); - else - dos.writeShort(0); - } -} \ No newline at end of file diff --git a/src/FESI/ClassFile/ConstantPoolEntry.java b/src/FESI/ClassFile/ConstantPoolEntry.java deleted file mode 100644 index 726543e2..00000000 --- a/src/FESI/ClassFile/ConstantPoolEntry.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * - * @(#) ConstantPoolEntry.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.ConstantPoolEntry - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; - -/** - *

- * The ConstantPoolEntry is an abstract base class representing common - * behaviors of specific subtypes, as defined below and in the VM spec. - *

- * - *

- * In particular this class handles, equality, sharing, output and indexing - * of all subtypes. - *

- */ - -abstract class ConstantPoolEntry { - - /* - * subtype tag values. - */ - - final static byte CONSTANT_UTF8 = 1; - final static byte CONSTANT_UNICODE = 2; - final static byte CONSTANT_INTEGER = 3; - final static byte CONSTANT_FLOAT = 4; - final static byte CONSTANT_LONG = 5; - final static byte CONSTANT_DOUBLE = 6; - final static byte CONSTANT_CLASS = 7; - final static byte CONSTANT_STRING = 8; - final static byte CONSTANT_FIELDREF = 9; - final static byte CONSTANT_METHODREF = 10; - final static byte CONSTANT_INTERFACEMETHODREF = 11; - final static byte CONSTANT_NAMEANDTYPE = 12; - - /* - * - */ - - private byte tag; - - private ClassFile classFile; - - private short index = -1; - - /** - *

construct the CPE, set the type tag and class file

- */ - - ConstantPoolEntry(byte t, ClassFile cf) { - tag = t; - classFile = cf; - } - - /** - * - */ - - byte getTag() { return tag; } - - /** - * @return the CPE's constant pool index. - */ - - short getConstantPoolIndex() { - if (index == -1) index = classFile.addConstantPoolEntry(this); - - return (short)index; - } - - /** - * @return the Class File this CPE is contained within. - */ - - ClassFile getClassFile() { return classFile; }; - - /** - *

* write the CPE to the stream

- * - * @throws IOException - */ - - abstract void write(DataOutputStream dos) throws IOException; - - /** - *

test the CPE for equality

- * - * @return object's equality. - */ - - public abstract boolean equals(Object o); - - /** - *

add the CPE into the Class File's constant pool

- */ - - protected void addToConstantPool() { - if (index == -1) index = classFile.addConstantPoolEntry(this); - } - - /** - * @return are we in debug mode? - */ - - protected static boolean debug() { return ClassFile.debug(); } -} diff --git a/src/FESI/ClassFile/ConstantValue.java b/src/FESI/ClassFile/ConstantValue.java deleted file mode 100644 index fbbe4d9d..00000000 --- a/src/FESI/ClassFile/ConstantValue.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * - * @(#) ConstantValue.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.ConstantValue - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.Attribute; -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ConstantPoolEntry; -import FESI.ClassFile.IntegerConstant; -import FESI.ClassFile.FloatConstant; -import FESI.ClassFile.DoubleConstant; -import FESI.ClassFile.LongConstant; -import FESI.ClassFile.StringConstant; - -/** - *

- * This class provides Constant Pool support for all the simple constant - * value data types supported in the class file format. - *

- */ - -class ConstantValue extends Attribute { - - private ConstantPoolEntry constant; - - /** - *

construct an Attribute describing a Constant

- * - * @param cf the class file - * @param cpe the cpe of the constant - */ - - private ConstantValue(ClassFile cf, ConstantPoolEntry cpe) { - super(Attribute.CONSTANTVALUE, cf); - constant = cpe; - } - - /** - *

Integer Constant

- * - * @param cf the class file - * @param ic the Integer Constant - */ - - ConstantValue(ClassFile cf, IntegerConstant ic) { - this(cf, (ConstantPoolEntry)ic); - } - - /** - *

Long Constant

- * - * @param cf the class file - * @param lc the Long Constant - */ - - ConstantValue(ClassFile cf, LongConstant lc) { - this(cf, (ConstantPoolEntry)lc); - } - - /** - *

Float Constant

- * - * @param cf the class file - * @param fc the Float Constant - */ - - ConstantValue(ClassFile cf, FloatConstant fc) { - this(cf, (ConstantPoolEntry)fc); - } - - /** - *

Double Constant

- * - * @param cf the class file - * @param dc the Double Constant - */ - - ConstantValue(ClassFile cf, DoubleConstant dc) { - this(cf, (ConstantPoolEntry)dc); - } - - /** - *

String Constant

- * - * @param cf the class file - * @param sc the String Constant - */ - - ConstantValue(ClassFile cf, StringConstant sc) { - this(cf, (ConstantPoolEntry)sc); - } - - /** - * @return the length of this ConstantValue Attribute (minus header) - */ - - int getLength() { return 2; } - - /** - * @return the CPE of the constant represented - */ - - ConstantPoolEntry getConstant() { return constant; } - - /** - * @return the CPE type tag of the constant represented - */ - - byte getConstantTag() { return constant.getTag(); } - - /** - *

write the Attribute to the stream

- * - * @param dos the output stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - dos.writeShort(getNameConstantPoolIndex()); - dos.writeInt(getLength()); - dos.writeShort(constant.getConstantPoolIndex()); - } - - /** - * @return the objects equality. - */ - - public boolean equals(Object o) { - return constant.equals(o); - } -} diff --git a/src/FESI/ClassFile/DoubleConstant.java b/src/FESI/ClassFile/DoubleConstant.java deleted file mode 100644 index f821e165..00000000 --- a/src/FESI/ClassFile/DoubleConstant.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * - * @(#) DoubleConstant.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.DoubleConstant - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ConstantPoolEntry; - -/** - *

implements a DOUBLE_CONSTANT CPE

- */ - -class DoubleConstant extends ConstantPoolEntry { - - private double doubler; - - /** - *

construct a DOUBLE_CONSTANT CPE

- * - * @param d the double constant - * @param cf the class file - */ - - DoubleConstant(double d, ClassFile cf) { - super(CONSTANT_DOUBLE, cf); - - doubler = d; - - addToConstantPool(); - } - - /** - *

write the constant CPE to the stream

- * - * @param dos the stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - dos.writeByte(getTag()); - dos.writeDouble(doubler); - } - - /** - * @return the double constant value. - */ - - double getValue() { return doubler; } - - /** - * @return the object's equality. - */ - - public boolean equals(Object o) { - if (o instanceof Double) { - return doubler == ((Double)o).doubleValue(); - } else if (o instanceof DoubleConstant) { - DoubleConstant dc = (DoubleConstant)o; - - return doubler == dc.getValue(); - } - - return false; - } -} diff --git a/src/FESI/ClassFile/EventAdaptorClassFile.java b/src/FESI/ClassFile/EventAdaptorClassFile.java deleted file mode 100644 index 2d6c7384..00000000 --- a/src/FESI/ClassFile/EventAdaptorClassFile.java +++ /dev/null @@ -1,809 +0,0 @@ -/* - * - * @(#) EncapsulatedEventAdaptorClassFile.java 1.3@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.EncapsulatedEventAdaptorClassFile - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - -package FESI.ClassFile; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.FileOutputStream; -import java.io.OutputStream; - -import java.io.IOException; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -import java.util.Vector; - -import FESI.Interpreter.EventAdaptor; -import FESI.Interpreter.EventAdaptorGenerator; - -import FESI.ClassFile.Attribute; -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ClassConstant; -import FESI.ClassFile.Code; -import FESI.ClassFile.ConstantPoolEntry; -import FESI.ClassFile.Exceptions; -import FESI.ClassFile.IntegerConstant; -import FESI.ClassFile.FieldDesc; -import FESI.ClassFile.FieldConstant; -import FESI.ClassFile.MethodDesc; -import FESI.ClassFile.MethodConstant; -import FESI.ClassFile.StringConstant; - -/** - *

- * This class is used by the EventAdaptorGenerator to author the - * implementation of the EventAdaptor classes that it is responsible - * for generating and loading. - *

- * - *

- * This class wraps all the ClassFile generic support classes and provides - * the adaptor specific implemenetation. - *

- * - * @see FESI.Interpreter.EventAdaptorGenerator - */ - -public final class EventAdaptorClassFile { - - private static String superClassName = - "FESI.Interpreter.EventAdaptor"; - - /* - * - */ - - private String listenerName; - private Class listenerClass; - - private String adaptorName; - private ClassFile classFile; - - private Method[] listenerMethods; - - /* - * - */ - - private StringConstant listenerNameConst; - - private FieldConstant methodsField; - private FieldConstant clazzField; - - private MethodConstant fireMethod; - private MethodConstant crackedFireMethod; - - private MethodConstant forNameMethod; - - private MethodConstant getMethodsMethod; - - /** - *

- * This statis function creates the class file implementation and writes - * it to the stream for loading ... - *

- * - * @param className the name of the adaptor class to synthesize. - * @param os the stream to write the class file into - * @exception IOException If any IO error occured during class loading - * @exception ClassNotFoundException If the class could not be loaded - * - * @returns - */ - - public EventAdaptorClassFile(String className, OutputStream os) - throws IOException, ClassNotFoundException { - - adaptorName = className; - listenerName = EventAdaptorGenerator.getBaseNameFromAdaptorName(className); - - listenerClass = Class.forName(listenerName); - - listenerMethods = listenerClass.getMethods(); - - classFile = new ClassFile(className, superClassName); - - // generate the misc class descriptions ... - - generateClassSundries(); - - // generate the class initializer - - generateInitializer(); - - // now the constructor ... - - generateConstructor(); - - // now the methods ... - - generateListenerMethods(); - - // write the resulting adaptor class to the stream provided. - - write(os); - } - - /** - * Are we running debug for this Adaptor generation? - */ - - private boolean debug() { return false; } - - /** - * Generate misc constant pool entries etc etc ... - */ - - private void generateClassSundries() { - - // the adaptor implements the Listener interface. - - classFile.addInterface(ClassFile.fullyQualifiedForm(listenerName)); - - listenerNameConst = classFile.addStringConstant(listenerName); - - /* - * private static java.lang.reflect.Method[] methods; - */ - - classFile.addFieldDesc( - new FieldDesc( - "methods", - "[Ljava/lang/reflect/Method;", - (short)(FieldDesc.ACC_STATIC | FieldDesc.ACC_PRIVATE), - classFile, - (Attribute[])null - ) - ); - - methodsField = classFile.addFieldConstant(adaptorName, - "methods", - "[Ljava/lang/reflect/Method;" - ); - - /* - * java.lang.reflect.Method[] java.lang.reflect.Method.getMethods(); - */ - - getMethodsMethod = classFile.addMethodConstant( - "java/lang/Class", - "getMethods", - "()[Ljava/lang/reflect/Method;" - ); - - /* - * java.lang.Class java.lang.Class.forName(); - */ - - forNameMethod = classFile.addMethodConstant( - "java/lang/Class", - "forName", - "(Ljava/lang/String;)Ljava/lang/Class;" - ); - /* - * private static java.lang.Class clazz; - */ - - classFile.addFieldDesc( - new FieldDesc( - "clazz", - "Ljava/lang/Class;", - (short)(FieldDesc.ACC_STATIC | FieldDesc.ACC_PRIVATE), - classFile, - (Attribute[])null - ) - ); - - clazzField = classFile.addFieldConstant(adaptorName, - "clazz", - "Ljava/lang/Class;" - ); - - /* - * these are superclass methods called from listener stubs ... - */ - - fireMethod = classFile.addMethodConstant( - adaptorName, - "fire", - "(Ljava/util/EventObject;Ljava/lang/reflect/Method;)V" - ); - - crackedFireMethod = classFile.addMethodConstant( - adaptorName, - "fire", - "([Ljava/lang/Object;Ljava/lang/reflect/Method;)V" - ); - - /* - * stub out base class abstract method: - * - * public static Class getListenerClass() { return clazz; } - * - */ - - Code c = new Code(classFile, (short)1, (short)2); - - c.addOpShort(Code.OP_GETSTATIC, clazzField.getConstantPoolIndex()); - c.addOp (Code.OP_ARETURN); - - Code[] ary = { c }; - - classFile.addMethodDesc( - new MethodDesc( - "getListenerClass", - "()Ljava/lang/Class;", - (short)MethodDesc.ACC_PUBLIC, - classFile, - ary - ) - ); - } - - /** - *

Generate class Initializer method

- */ - - private void generateInitializer() { - Code c = new Code(classFile, (short)0, (short)3); - Code[] ary = { c }; - short i = listenerNameConst.getConstantPoolIndex(); - - - // clazz = Class.forName( ); - - if (i <= 255) - c.addOp1(Code.OP_LDC, (byte)i); - else - c.addOpShort(Code.OP_LDC_WIDE, i); - - c.addOpShort(Code.OP_INVOKE_STATIC, - forNameMethod.getConstantPoolIndex() - ); - - c.addOp(Code.OP_DUP); - - c.addOpShort(Code.OP_PUTSTATIC, - clazzField.getConstantPoolIndex() - ); - - - // methods = clazz.getMethods(); - - c.addOpShort(Code.OP_INVOKE_VIRTUAL, - getMethodsMethod.getConstantPoolIndex() - ); - - c.addOpShort(Code.OP_PUTSTATIC, - methodsField.getConstantPoolIndex() - ); - - c.addOp (Code.OP_RETURN); - - classFile.addMethodDesc( - new MethodDesc( - "", - "()V", - (short)(MethodDesc.ACC_PRIVATE | MethodDesc.ACC_STATIC), - classFile, - ary - ) - ); - } - - /** - * Author the no-args public constructor for this Adaptor - * - * public void () { super(); } - */ - - private void generateConstructor() { - Code c = new Code(classFile, (short)1, (short)2); - Code[] ary = { c }; - MethodConstant mc; - - // get a MethodConstant for the superclass constructor - - mc = classFile.addMethodConstant( - ClassFile.fullyQualifiedForm(superClassName), - "", - "()V" - ); - - // push this onto the stack - - c.addOp (Code.OP_ALOAD_0); - - // call the superclass constructor - - c.addOpShort(Code.OP_INVOKE_SPECIAL, mc.getConstantPoolIndex()); - - c.addOp (Code.OP_RETURN); - - - // now add a method to the class file describing the constructor ... - - classFile.addMethodDesc( - new MethodDesc( - "", - "()V", - (short)MethodDesc.ACC_PUBLIC, - classFile, - ary - ) - ); - } - - /** - * Author the Listener Method Stubs for the EventListener interface - * this class is adapting to the EventListener interface. - */ - - private void generateListenerMethods() { - for (int i = 0; i < listenerMethods.length; i++) { - - /* we can only generate code for EventListener methods of - * the form: - * - * void ( ) - * or: - * void ( {} ) - * - * if we dont match these patterns we drop the method on the - * floor. - */ - - if (!Void.TYPE.equals(listenerMethods[i].getReturnType())) { - System.err.println( - "Detected unexpected method signature: " + - listenerMethods[i] + - " in interface: " + - listenerName - ); - } else { - Class[] lmParams = listenerMethods[i].getParameterTypes(); - Class[] lmExceptions = listenerMethods[i].getExceptionTypes(); - - - if (lmParams != null && - lmParams.length == 1 && - java.util.EventObject.class.isAssignableFrom(lmParams[0])) { - generateSimpleListenerMethodStub(listenerMethods[i], - lmParams[0], - lmExceptions, - i - ); - } else { - generateCrackedListenerMethodStub(listenerMethods[i], - lmParams, - lmExceptions, - i - ); - } - } - } - } - - /** - * Generate a simple EventListener interface method stub - */ - - private void generateSimpleListenerMethodStub(Method listenerMethod, Class listenerParam, Class[] listenerExceptions, int listenerMethodTableIndex) { - Code c = new Code(classFile, (short)2, (short)4); - Attribute[] ary; - - /* - * public void ( e) - * { - * EncapsulatedEvent t = new EncapsulatedEvent(e); - * Method m = findListenerMethod(); - * - * fire(t, m); - * } - */ - - c.addOp (Code.OP_ALOAD_0); // this - c.addOp (Code.OP_ALOAD_1); // event object - - c.addOpShort(Code.OP_GETSTATIC, - methodsField.getConstantPoolIndex() - ); - - if (listenerMethodTableIndex <= 255) { - c.addOp1(Code.OP_BIPUSH, (byte)listenerMethodTableIndex); - } else { - short i = classFile.addIntegerConstant(listenerMethodTableIndex).getConstantPoolIndex(); - - if (i <= 255) - c.addOp1(Code.OP_LDC, (byte)i); - else - c.addOpShort(Code.OP_LDC_WIDE, i); - } - - c.addOp (Code.OP_AALOAD); - - c.addOpShort(Code.OP_INVOKE_VIRTUAL, - fireMethod.getConstantPoolIndex() - ); // call fire(); - - c.addOp (Code.OP_RETURN); // get out of here - - if (listenerExceptions != null && listenerExceptions.length > 0) { - ary = new Attribute[2]; - - ary[1] = new Exceptions(listenerExceptions, classFile); - } else { - ary = new Attribute[1]; - } - - ary[0] = c; - - // define the listener method - - classFile.addMethodDesc( - new MethodDesc( - listenerMethod.getName(), - "(" + ClassFile.fieldType(listenerParam.getName()) + ")V", - (short)(listenerMethod.getModifiers() & ~MethodDesc.ACC_ABSTRACT), - classFile, - ary - ) - ); - } - - /** - * Generate a cracked EventListener interface method stub - */ - - private void generateCrackedListenerMethodStub(Method listenerMethod, Class[] listenerParams, Class[] listenerExceptions, int listenerMethodTableIndex) { - Code c = new Code(classFile, - (short)(listenerParams.length * 2 + 1), - (short)9 - ); - Attribute[] ary; - String methodPDesc = ""; - boolean wasDoubleWord; // was the last param processed double? - - c.addOp (Code.OP_ALOAD_0); // this - - /* - * For cracked Event listener methods we construct an array of Objects - * to contain the cracked actual parameters ... primitive types are - * wrapped in a container object suitable for their type. - */ - - if (listenerParams.length <= 255) { - c.addOp1(Code.OP_BIPUSH, (byte)listenerParams.length); - } else { - short i = classFile.addIntegerConstant(listenerParams.length).getConstantPoolIndex(); - - if (i <= 255) - c.addOp1(Code.OP_LDC, (byte)i); - else - c.addOpShort(Code.OP_LDC_WIDE, (short)i); - } - - c.addOpShort(Code.OP_ANEWARRAY, - classFile.addClassConstant("java.lang.Object").getConstantPoolIndex() - ); - - /* - * we've now constructed and array of java/lang/Object ... now populate - * it with the actual params. - */ - - int lvarIdx = 1; // because locals[0] == this - - /* - * for each formal parameter, generate code to load the actual - * param from this methods local vars, then if it is a primitive - * type, then construct a container object and initialize it - * to the primitives value. - * - * as a side effect of this loop we also construct the methods - * descriptor to optimise processing of the type info - */ - - for (int i = 0; i < listenerParams.length; i++, lvarIdx += (wasDoubleWord ? 2 : 1)) { - - c.addOp(Code.OP_DUP); // the array reference - - if (lvarIdx <= 255) { // the array index - c.addOp1(Code.OP_BIPUSH, (byte)i); - } else { - short ic = classFile.addIntegerConstant(i).getConstantPoolIndex(); - if (ic < 255) - c.addOp1(Code.OP_LDC, (byte)ic); - else - c.addOpShort(Code.OP_LDC_WIDE, (short)ic); - } - - /* - * get the param value onto TOS - * as a side effect gather method descriptor string. - */ - - String s = processParam(c, listenerParams[i], lvarIdx); - - c.addOp(Code.OP_AASTORE); // arrayref, index, value - - wasDoubleWord = s.equals("J") || s.equals("D"); - - methodPDesc += s; - } - - // that's the array constructed ... now lets call my superclass fire - - // but first we need to tell that method which listener is firing ... - - c.addOpShort(Code.OP_GETSTATIC, - methodsField.getConstantPoolIndex() - ); - - if (listenerMethodTableIndex <= 255) { - c.addOp1(Code.OP_BIPUSH, (byte)listenerMethodTableIndex); - } else { - short i = classFile.addIntegerConstant(listenerMethodTableIndex).getConstantPoolIndex(); - - if (i <= 255) - c.addOp1(Code.OP_LDC, (byte)i); - else - c.addOpShort(Code.OP_LDC_WIDE, i); - } - - c.addOp (Code.OP_AALOAD); // this, array, method - - // now we can call the fire method - - c.addOpShort(Code.OP_INVOKE_VIRTUAL, - crackedFireMethod.getConstantPoolIndex() - ); // call fire(); - - c.addOp (Code.OP_RETURN); // get out of here - - if (listenerExceptions != null && listenerExceptions.length > 0) { - ary = new Attribute[2]; - - ary[1] = new Exceptions(listenerExceptions, classFile); - } else { - ary = new Attribute[1]; - } - - ary[0] = c; - - // define the listener method - - classFile.addMethodDesc( - new MethodDesc( - listenerMethod.getName(), - "(" + methodPDesc + ")V", - (short)(listenerMethod.getModifiers() & ~MethodDesc.ACC_ABSTRACT), - classFile, - ary - ) - ); - } - - /* - * This method is used to generate code for cracked event listener - * stubs. Its job is to generate code to load the appropriate parameter - * data type onto the stack, create a wrapper object if needed and leave - * the appropriate value on TOS for storing into the objects array. - */ - - private String processParam(Code c, Class pClass, int pIdx) { - ClassConstant cc = null; - MethodConstant mc = null; - byte ldOpCode = Code.OP_ALOAD; // load ref by default - byte convOpCode = 0; - boolean singleWordParam = true; - Class pType = pClass; - boolean isPrimitive; - boolean isArrayRef; - - String pDesc = ""; - - // is this an array reference? - - while (pType.isArray()) { // side - effect: construct array param desc - pType = pType.getComponentType(); - pDesc += "["; - } - - isPrimitive = pType.isPrimitive(); - isArrayRef = pClass.isArray(); - - if (isPrimitive) { // builtin datatype - if (pType.equals(java.lang.Long.TYPE)) { - pDesc += "J"; - - if (!isArrayRef) { - cc = classFile.addClassConstant("java/lang/Long"); - - mc = classFile.addMethodConstant( - "java/lang/Long", - "", - "(J)V" - ); - - ldOpCode = Code.OP_LLOAD; - singleWordParam = false; - } - } else if (pType.equals(java.lang.Float.TYPE)) { - pDesc += "F"; - - if (!isArrayRef) { - cc = classFile.addClassConstant("java/lang/Float"); - - mc = classFile.addMethodConstant( - "java/lang/Float", - "", - "(F)V" - ); - - ldOpCode = Code.OP_FLOAD; - } - } else if (pType.equals(java.lang.Double.TYPE)) { - pDesc += "D"; - - if (!isArrayRef) { - cc = classFile.addClassConstant("java/lang/Double"); - - mc = classFile.addMethodConstant( - "java/lang/Double", - "", - "(D)V" - ); - - ldOpCode = Code.OP_DLOAD; - singleWordParam = false; - } - } else { // integer, array or objref computational types ... - - ldOpCode = Code.OP_ILOAD; - - if (pType.equals(java.lang.Boolean.TYPE)) { - pDesc += "Z"; - - if (!isArrayRef) { - cc = classFile.addClassConstant("java/lang/Boolean"); - - mc = classFile.addMethodConstant( - "java/lang/Boolean", - "", - "(Z)V" - ); - - convOpCode = Code.OP_I2B; - } - } else if (pType.equals(java.lang.Character.TYPE)) { - pDesc += "C"; - - if (!isArrayRef) { - cc = classFile.addClassConstant("java/lang/Character"); - - mc = classFile.addMethodConstant( - "java/lang/Character", - "", - "(C)V" - ); - - convOpCode = Code.OP_I2C; - } - } else if (pType.equals(java.lang.Byte.TYPE)) { - pDesc += "B"; - - if (!isArrayRef) { - cc = classFile.addClassConstant("java/lang/Byte"); - - mc = classFile.addMethodConstant( - "java/lang/Character", - "", - "(C)V" - ); - - convOpCode = Code.OP_I2B; - } - } else if (pType.equals(java.lang.Short.TYPE)) { - pDesc += "S"; - - if (!isArrayRef) { - cc = classFile.addClassConstant("java/lang/Short"); - - mc = classFile.addMethodConstant( - "java/lang/Short", - "", - "(S)V" - ); - - convOpCode = Code.OP_I2S; - } - } else if (pType.equals(java.lang.Integer.TYPE)) { - pDesc += "I"; - - if (!isArrayRef) { - cc = classFile.addClassConstant("java/lang/Integer"); - - mc = classFile.addMethodConstant( - "java/lang/Integer", - "", - "(I)V" - ); - } - } - } - } else { // handle descriptors for non-primitives ... - pDesc += ClassFile.fieldType(pType.getName()); - } - - // now load the param value onto TOS ... - - if (pIdx < 255) - c.addOp1(ldOpCode, (byte)pIdx); - else { - c.addOp(Code.OP_WIDE); - c.addOpShort(ldOpCode, (short)pIdx); - } - - if (isPrimitive && !isArrayRef) { // additional processing for primitives - if (convOpCode != 0) { // narrow Int? - c.addOp(convOpCode); // then widen the reference - } - - // we now have the param's value of TOS, - // construct a container object for it - - c.addOpShort(Code.OP_NEW, (short)cc.getConstantPoolIndex()); - - if (singleWordParam) { - c.addOp(Code.OP_DUP_X1); // this, , this - c.addOp(Code.OP_SWAP); // this, - } else { - c.addOp(Code.OP_DUP_X2); // this, , this - c.addOp(Code.OP_DUP_X2); // this, this, , this - c.addOp(Code.OP_POP); // this, this, - } - - c.addOpShort(Code.OP_INVOKE_SPECIAL, mc.getConstantPoolIndex()); - } - - // param value on TOS - - return pDesc; // type descriptor - side effect - } - - /** - *

write the class file to the stream

- * - * @param os the output stream - * - * @throws IOException - */ - - private void write(OutputStream os) throws IOException { - classFile.write(os); - } -} \ No newline at end of file diff --git a/src/FESI/ClassFile/Exceptions.java b/src/FESI/ClassFile/Exceptions.java deleted file mode 100644 index c11ecb1a..00000000 --- a/src/FESI/ClassFile/Exceptions.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * - * @(#) Exceptions.java 1.3@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.Exceptions - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.Attribute; -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ClassConstant; - -/** - *

- * The Exceptions class extends the Attribute class to enumerate the - * exception types generated by method implementations in a class file - *

- */ - -class Exceptions extends Attribute { - - private ClassConstant[] exceptions; - - /** - *

construct an Exceptions attribute that enumerates the exceptions

- * - * @param exs[] an array of exception class constants - * @param cf the containing class file - */ - - Exceptions(ClassConstant[] exs, ClassFile cf) { - super(Attribute.EXCEPTIONS, cf); - - // we should validate that the ClassConstants are all - // subclasses of Exception here ... - - exceptions = exs; - } - - /** - *

construct an Exceptions attribute that enumerates the exceptions

- * - * @param exs[] an array of exception class types - * @param cf the containing class file - * - */ - Exceptions(Class[] exs, ClassFile cf) { - super(Attribute.EXCEPTIONS, cf); - - // we should validate that the ClassConstants are all - // subclasses of Exception here ... - - ClassConstant[] cc = new ClassConstant[exs.length]; - - for (int i = 0; i < exs.length; i++) - cc[i] = cf.addClassConstant(exs[i].getName()); - - exceptions = cc; - } - - /** - *

write the Exceptions attribute to the stream

- * - * @param dos the output stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - dos.writeShort(getNameConstantPoolIndex()); - dos.writeInt(getLength()); - - if (exceptions != null && exceptions.length > 0) { - dos.writeShort(exceptions.length); - - for (int i = 0; i < exceptions.length; i++) { - dos.writeShort(exceptions[i].getConstantPoolIndex()); - } - } else dos.writeShort(0); - } - - /** - * @return the Object's equality - */ - - public boolean equals(Object o) { - if (o instanceof Exceptions) { - Exceptions other = (Exceptions)o; - - if (exceptions.length == other.exceptions.length) { - for (int i = 0; i < exceptions.length; i++) { - if (!exceptions[i].equals(other.exceptions[i])) - return false; - } - - return true; - } - } - - return false; - } - - /** - * @return the length of the Attribute in bytes - */ - - int getLength() { return exceptions.length * 2 + 2; } - - /** - *

adds exception class to the attribute.

- * - * @param a class constant to add to the attribute - * - */ - - void addException(ClassConstant ex) { - - // should verify that ClassConstant is exception subclass and not - // already in the attribute - - if (exceptions == null) { - exceptions = new ClassConstant[1]; - - exceptions[0] = ex; - } else { - ClassConstant[] temp = new ClassConstant[exceptions.length + 1]; - int i; - - for (i = 0; i < exceptions.length; i++) { - temp[i] = exceptions[i]; - } - - temp[i] = ex; - - exceptions = temp; - } - } -} diff --git a/src/FESI/ClassFile/FieldConstant.java b/src/FESI/ClassFile/FieldConstant.java deleted file mode 100644 index 59dfea99..00000000 --- a/src/FESI/ClassFile/FieldConstant.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * - * @(#) FieldConstant.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.FieldConstant - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.RefConstant; - -/** - *

implements a CONSTANT_FIELDREF CPE

- */ - -final class FieldConstant extends RefConstant { - - /** - *

construct a CONSTANT_FIELDREF CPE

- * - * @param cName the class name - * @param nName the name of the field - * @param tName the type descriptor for the field - * @param cf the class file - */ - - FieldConstant(String cName, String nName, String tName, ClassFile cf) { - super(CONSTANT_FIELDREF, cName, nName, tName, cf); - } -} diff --git a/src/FESI/ClassFile/FieldDesc.java b/src/FESI/ClassFile/FieldDesc.java deleted file mode 100644 index 27ec3ceb..00000000 --- a/src/FESI/ClassFile/FieldDesc.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * - * @(#) FieldDesc.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.FieldDesc - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.UTF8Constant; -import FESI.ClassFile.Attribute; - -/** - *

- * Implements the field_info structure of a class file, used to describe - * the attributes of all fields implemented by this class. The class provides - * minimal support to write the formatted structure to the stream. - *

- */ - -final class FieldDesc { - - final static short ACC_PUBLIC = 0x0001; - final static short ACC_PRIVATE = 0x0002; - final static short ACC_PROTECTED = 0x0004; - final static short ACC_STATIC = 0x0008; - final static short ACC_FINAL = 0x0010; - final static short ACC_VOLATILE = 0x0040; - final static short ACC_TRANSIENT = 0x0080; - - private UTF8Constant name; - private UTF8Constant descriptor; - - private short accessFlags; - - private ClassFile classFile; - - private Attribute[] attributes; - - /** - *

construct a descriptor for a field.

- * - * @param field name - * @param desc its type descriptor - * @param flags access flags - * @param cf the class file - * @param attrs any associated attributes - * - */ - - FieldDesc(String field, String desc, short flags, ClassFile cf, Attribute[] attrs) { - super(); - - // we would validate here ... - - name = new UTF8Constant(field, cf); - descriptor = new UTF8Constant(desc, cf); - accessFlags = flags; - classFile = cf; - attributes = attrs; - } - - /** - *

write the field to the stream

- * - * @param dos the output stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - dos.writeShort(accessFlags); - dos.writeShort(name.getConstantPoolIndex()); - dos.writeShort(descriptor.getConstantPoolIndex()); - - if (attributes != null && attributes.length == 0) { - dos.writeShort(attributes.length); - - for (int i = 0; i < attributes.length; i++) { - attributes[i].write(dos); - } - } else dos.writeShort(0); - } -} diff --git a/src/FESI/ClassFile/FloatConstant.java b/src/FESI/ClassFile/FloatConstant.java deleted file mode 100644 index ab0e260b..00000000 --- a/src/FESI/ClassFile/FloatConstant.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * - * @(#) FloatConstant.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.FloatConstant - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ConstantPoolEntry; - - /** - *

provides minimal support for FLOAT_CONSTANT CPE

- */ - -class FloatConstant extends ConstantPoolEntry { - - private float floating; - - /** - *

construct a CONSTANT_FLOAT

- * - * @param f the float value - * @param cf the class file - */ - - FloatConstant(float f, ClassFile cf) { - super(CONSTANT_FLOAT, cf); - - floating = f; - - addToConstantPool(); - } - - /** - *

write the CONSTANT_FLOAT to the stream

- * - * @param dos the output stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - dos.writeByte(getTag()); - dos.writeFloat(floating); - } - - /** - *

return the value of the constant

- * - * @return the value of the CONSTANT_FLOAT - */ - - float getValue() { return floating; } - - /** - * @return object equality - */ - - public boolean equals(Object o) { - if (o instanceof Float) { - return floating == ((Float)o).floatValue(); - } else if (o instanceof FloatConstant) { - FloatConstant fc = (FloatConstant)o; - - return floating == fc.getValue(); - } - - return false; - } -} diff --git a/src/FESI/ClassFile/IntegerConstant.java b/src/FESI/ClassFile/IntegerConstant.java deleted file mode 100644 index ce14be27..00000000 --- a/src/FESI/ClassFile/IntegerConstant.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * - * @(#) IntegerConstant.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.IntegerConstant - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ConstantPoolEntry; - -/** - *

this class provides minimal support for the CONSTANT_INTEGER CPE

- */ - -class IntegerConstant extends ConstantPoolEntry { - - private int integer; - - /** - *

construct a CONSTANT_INTEGER CPE

- * - * @param i the integer constant - * @param cf the class file - */ - - IntegerConstant(int i, ClassFile cf) { - super(CONSTANT_INTEGER, cf); - - integer = i; - - addToConstantPool(); - } - - /** - *

write the CONSTANT_INTEGER to the stream

- * - * @param dos the output stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - dos.writeByte(getTag()); - dos.writeInt(integer); - } - - /** - * @return the value of the CONSTANT_INTEGER - */ - - int getValue() { return integer; } - - /** - * @return object equality - */ - - public boolean equals(Object o) { - if (o instanceof Integer) { - return integer == ((Integer)o).intValue(); - } else if (o instanceof IntegerConstant) { - IntegerConstant ic = (IntegerConstant)o; - - return integer == ic.getValue(); - } - - return false; - } -} diff --git a/src/FESI/ClassFile/InterfaceMethodConstant.java b/src/FESI/ClassFile/InterfaceMethodConstant.java deleted file mode 100644 index a5c6dd38..00000000 --- a/src/FESI/ClassFile/InterfaceMethodConstant.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * - * @(#) InterfaceMethodConstant.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.InterfaceMethodConstant - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.RefConstant; - -/** - *

this class provides minimal support for CONSTANT_INTERFACEMETHODREF CPE's

- */ - -class InterfaceMethodConstant extends RefConstant { - - /** - *

construct a CONSTANT_INTERFACEMETHODREF

- * - * @param cName name of interface - * @param nName name of method - * @param tName method type descriptor - * @param cf class file - * - */ - - InterfaceMethodConstant(String cName, String nName, String tName, ClassFile cf) { - super(CONSTANT_INTERFACEMETHODREF, cName, nName, tName, cf); - } -} diff --git a/src/FESI/ClassFile/LongConstant.java b/src/FESI/ClassFile/LongConstant.java deleted file mode 100644 index 8a1a1713..00000000 --- a/src/FESI/ClassFile/LongConstant.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * - * @(#) LongConstant.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.LongConstant - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ConstantPoolEntry; - -/** - *

this class provides minimal support for CONSTANT_LONG CPE's

- */ - -class LongConstant extends ConstantPoolEntry { - - private long longish; - - /** - *

construct a CONSTANT_LONG

- * - * @param l the long constant - * @param cf the class file - */ - - LongConstant(long l, ClassFile cf) { - super(CONSTANT_LONG, cf); - - longish = l; - - addToConstantPool(); - } - - /** - *

write the CONSTANT_LONG to the stream

- * - * @param dos the output stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - dos.writeByte(getTag()); - dos.writeLong(longish); - } - - /** - * @return the long constant value - */ - - long getValue() { return longish; } - - /** - * @return object equality - */ - - public boolean equals(Object o) { - if (o instanceof Long) { - return longish == ((Long)o).longValue(); - } else if (o instanceof LongConstant) { - LongConstant lc = (LongConstant)o; - - return longish == lc.getValue(); - } - - return false; - } -} diff --git a/src/FESI/ClassFile/MethodConstant.java b/src/FESI/ClassFile/MethodConstant.java deleted file mode 100644 index eb30187e..00000000 --- a/src/FESI/ClassFile/MethodConstant.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * - * @(#) MethodConstant.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.MethodConstant - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.RefConstant; - -/** - *

this class provides minimal support for the CONSTANT_METHODREF CPE

- */ - -class MethodConstant extends RefConstant { - - /** - *

construct a CONSTANT_METHODREF

- * - * @param cName the name of the implementing class - * @param nName the name of the method - * @param tName the type descriptor of the method - * @param cf the class file - */ - - MethodConstant(String cName, String nName, String tName, ClassFile cf) { - super(CONSTANT_METHODREF, cName, nName, tName, cf); - } -} diff --git a/src/FESI/ClassFile/MethodDesc.java b/src/FESI/ClassFile/MethodDesc.java deleted file mode 100644 index 4fd3cd84..00000000 --- a/src/FESI/ClassFile/MethodDesc.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * - * @(#) MethodDesc.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.MethodDesc - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.UTF8Constant; -import FESI.ClassFile.Attribute; - -/** - *

this class provides minimal support for method_info structures

- */ - -final class MethodDesc { - - final static short ACC_PUBLIC = 0x0001; - final static short ACC_PRIVATE = 0x0002; - final static short ACC_PROTECTED = 0x0004; - final static short ACC_STATIC = 0x0008; - final static short ACC_FINAL = 0x0010; - final static short ACC_SYNCHRONIZED = 0x0020; - final static short ACC_NATIVE = 0x0100; - final static short ACC_ABSTRACT = 0x0400; - - private UTF8Constant name; - private UTF8Constant descriptor; - - private short accessFlags; - - private ClassFile classFile; - - private Attribute[] attributes; - - /** - *

construct a descriptor for a method

- * - * @param method the name of the method - * @param desc a type descriptor for its signature - * @param flags access flags - * @param cf the class file - * @param attrs arbitrary attributes - * - */ - - MethodDesc(String method, String desc, short flags, ClassFile cf, Attribute[] attrs) { - super(); - - // we would validate here ... - - name = new UTF8Constant(method, cf); - descriptor = new UTF8Constant(desc, cf); - accessFlags = flags; - classFile = cf; - attributes = attrs; - } - - /** - *

write the method to the stream

- * - * @param dos the output stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - dos.writeShort(accessFlags); - dos.writeShort(name.getConstantPoolIndex()); - dos.writeShort(descriptor.getConstantPoolIndex()); - - if (attributes != null && attributes.length > 0) { - dos.writeShort(attributes.length); - - for (int i = 0; i < attributes.length; i++) { - attributes[i].write(dos); - } - } else dos.writeShort(0); - } -} diff --git a/src/FESI/ClassFile/NameAndTypeConstant.java b/src/FESI/ClassFile/NameAndTypeConstant.java deleted file mode 100644 index 1db88c26..00000000 --- a/src/FESI/ClassFile/NameAndTypeConstant.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * - * @(#) NameAndTypeConstant.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.NameAndTypeConstant - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ConstantPoolEntry; -import FESI.ClassFile.UTF8Constant; - -/** - *

this class provides minimal support for NAME_AND_TYPE CPE's

- */ - -class NameAndTypeConstant extends ConstantPoolEntry { - - private UTF8Constant name; - private UTF8Constant desc; - - /** - *

construct a CONSTANT_NAMEANDTYPE CPE

- * - * @param n the name - * @param d the type - * @param cf the class file - */ - - NameAndTypeConstant(String n, String d, ClassFile cf) { - super(CONSTANT_NAMEANDTYPE, cf); - - name = new UTF8Constant(n, cf); - desc = new UTF8Constant(d, cf); - - addToConstantPool(); - } - - /** - *

write the CPE to the stream

- * - * @param dos the output stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - - if (debug()) { - System.err.println(getConstantPoolIndex() + - " NAME: " + - name.getConstantPoolIndex() + - " TYPE: " + - desc.getConstantPoolIndex() - ); - } - - dos.writeByte(getTag()); - dos.writeShort(name.getConstantPoolIndex()); - dos.writeShort(desc.getConstantPoolIndex()); - } - - /** - * @return the name string - */ - - String getName() { return name.getString(); } - - /** - * @return the type descriptor string - */ - - String getDescriptor() { return desc.getString(); } - - /** - * @return object equality - */ - - public boolean equals(Object o) { - if (o instanceof String) { - return name.getString().equals(o) || - desc.getString().equals(o); - } else if (o instanceof NameAndTypeConstant) { - NameAndTypeConstant nandt = (NameAndTypeConstant)o; - - return name.equals(nandt.getName()) && - desc.equals(nandt.getDescriptor()); - - } - - return false; - } -} diff --git a/src/FESI/ClassFile/RefConstant.java b/src/FESI/ClassFile/RefConstant.java deleted file mode 100644 index 6a871378..00000000 --- a/src/FESI/ClassFile/RefConstant.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * - * @(#) RefConstant.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.RefConstant - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ConstantPoolEntry; -import FESI.ClassFile.ClassConstant; -import FESI.ClassFile.NameAndTypeConstant; - -/** - *

- * this base class provides minimal support for METHODREF, FIELDREF, and - * INTERFACEMETHODREF CPE's - *

- */ - -class RefConstant extends ConstantPoolEntry { - - private ClassConstant clazz; - private NameAndTypeConstant nandt; - - /** - *

construct a CPE

- * - * @param t the CPE tag value - * @param cName the class name - * @param nName the name of the referenced field or method - * @param tName the type descriptor of the field or method - * @param cf the class file - * - */ - - protected RefConstant(byte t, String cName, - String nName, String tName, ClassFile cf) { - super(t, cf); - - clazz = new ClassConstant(cName, cf); - nandt = new NameAndTypeConstant(nName, tName, cf); - - addToConstantPool(); - } - - /** - *

write the referenced object to the stream

- * - * @param dos the output stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - dos.writeByte(getTag()); - dos.writeShort(clazz.getConstantPoolIndex()); - dos.writeShort(nandt.getConstantPoolIndex()); - } - - /** - * @return the class constant for the referenced object - */ - - ClassConstant getClassObject() { return clazz; } - - /** - * @return the name and type CPE for the referenced object - */ - - NameAndTypeConstant getNameAndType() { return nandt; } - - /** - * @return object equality - */ - - public boolean equals(Object o) { - if (o instanceof String) { - return ((String)o).equals(nandt.getName()); - } else if (o instanceof RefConstant) { - RefConstant rc = (RefConstant)o; - - return clazz.equals(rc.getClassObject()) && - nandt.equals(rc.getNameAndType()); - } - - return false; - } - -} diff --git a/src/FESI/ClassFile/StringConstant.java b/src/FESI/ClassFile/StringConstant.java deleted file mode 100644 index 28dca795..00000000 --- a/src/FESI/ClassFile/StringConstant.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * - * @(#) StringConstant.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.StringConstant - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ConstantPoolEntry; -import FESI.ClassFile.UTF8Constant; - -/** - *

this class provides minimal support for CONSTANT_STRING CPE's

- */ - -final class StringConstant extends ConstantPoolEntry { - - private UTF8Constant string; - - /** - *

construct a CONSTANT_STRING CPE

- * - * @param str the constant - * @param cf the class file - */ - - StringConstant(String str, ClassFile cf) { - super(CONSTANT_STRING, cf); - - string = new UTF8Constant(str, cf); - - addToConstantPool(); - } - - /** - *

construct a CONSTANT_STRING CPE

- * - * @param utf8 the utf8 constant - * @param cf the class file - */ - - StringConstant(UTF8Constant utf8, ClassFile cf) { - super(CONSTANT_STRING, cf); - - string = utf8; - - addToConstantPool(); - } - - /** - *

write the constant to the stream

- * - * @param dos the output stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - dos.writeByte(getTag()); - dos.writeShort(string.getConstantPoolIndex()); - } - - /** - * @return the string constant - */ - - String getString() { return string.getString(); } - - /** - * @return object equality - */ - - public boolean equals(Object o) { - if (o instanceof String) { - return string.equals(o); - } else if (o instanceof StringConstant) { - return string.equals(((StringConstant)o).getString()); - } - - return false; - } -} diff --git a/src/FESI/ClassFile/UTF8Constant.java b/src/FESI/ClassFile/UTF8Constant.java deleted file mode 100644 index 35ad763f..00000000 --- a/src/FESI/ClassFile/UTF8Constant.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * - * @(#) UTF8Constant.java 1.2@(#) - * - * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE - * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES - * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING - * THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -/** - *

- * FESI.ClassFile.UTF8Constant - *

- * - * @version 1.0 - * @author Laurence P. G. Cable - */ - - -package FESI.ClassFile; - -import java.io.DataOutputStream; -import java.io.IOException; - -import FESI.ClassFile.ClassFile; -import FESI.ClassFile.ConstantPoolEntry; - -/** - *

this class provides minimal support for CONSTANT_UTF8 CPE's

- */ - -class UTF8Constant extends ConstantPoolEntry { - - private String string; - - /** - *

construct a CONSTANT_UTF8 CPE

- * - * @param s the string - * @param cf the class file - */ - - UTF8Constant(String s, ClassFile cf) { - super(CONSTANT_UTF8, cf); - - string = s; - - addToConstantPool(); - } - - /** - *

write the CPE to the output stream

- * - * @param dos the output stream - * - * @throws IOException - */ - - void write(DataOutputStream dos) throws IOException { - dos.writeByte(getTag()); - dos.writeUTF(string); - } - - /** - * @return the string constant - */ - - String getString() { return string; } - - /** - * @return object equality - */ - - public boolean equals(Object o) { - if (o instanceof String) { - return string.equals((String)o); - } else if (o instanceof UTF8Constant) { - return string.equals(((UTF8Constant)o).getString()); - } - - return false; - } -} diff --git a/src/FESI/Data/ArrayObject.java b/src/FESI/Data/ArrayObject.java deleted file mode 100644 index 724b909f..00000000 --- a/src/FESI/Data/ArrayObject.java +++ /dev/null @@ -1,185 +0,0 @@ -// ArrayObject.java -// FESI Copyright (c) Jean-Marc Lugrin, 1999 -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2 of the License, or (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. - -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -package FESI.Data; - -import java.util.Hashtable; -import FESI.Exceptions.*; -import FESI.Interpreter.*; - -/** - * Implements the Array EcmaScript object. This is a singleton - */ -public class ArrayObject extends BuiltinFunctionObject { - - private static final String JOINstring = ("join").intern(); - private static final int JOINhash = JOINstring.hashCode(); - private static final String LENGTHstring = ("length").intern(); - private static final int LENGTHhash = LENGTHstring.hashCode(); - private static final String ZEROstring = ("0").intern(); - private static final int ZEROhash = ZEROstring.hashCode(); - - /** - * Create a new Array object - used by makeArrayObject - * - * @param prototype Must be an ArrayPrototype - * @param evaluator the evaluator - */ - private ArrayObject(ESObject prototype, Evaluator evaluator) { - super(prototype, evaluator, "Array", 1); - } - - - // overrides - public ESValue callFunction(ESObject thisObject, - ESValue[] arguments) - throws EcmaScriptException { - return doConstruct(thisObject, arguments); - } - - - // overrides - public ESObject doConstruct(ESObject thisObject, - ESValue[] arguments) - throws EcmaScriptException { - ESObject ap = evaluator.getArrayPrototype(); - ArrayPrototype theArray = new ArrayPrototype(ap, evaluator); - if (arguments.length > 1) { - for (int i=0; i 0) { - separator = arguments[0].toString(); - } - int length = (thisObject.getProperty(ArrayObject.LENGTHstring, ArrayObject.LENGTHhash)).toInt32(); - for (int i =0; i0) buffer.append(separator); - String iString = Integer.toString(i); - ESValue value = thisObject.getProperty(iString,iString.hashCode()); - if (value!=ESUndefined.theUndefined && value!=ESNull.theNull) { - buffer.append(value.toString()); - } - } - return new ESString(buffer.toString()); - } - } - class ArrayPrototypeReverse extends BuiltinFunctionObject { - ArrayPrototypeReverse(String name, Evaluator evaluator, FunctionPrototype fp) { - super(fp, evaluator, name, 0); - } - public ESValue callFunction(ESObject thisObject, - ESValue[] arguments) - throws EcmaScriptException { - if (!(thisObject instanceof ArrayPrototype)) { - throw new EcmaScriptException ("reverse only implemented for arrays"); - } - return ((ArrayPrototype) thisObject).reverse(); - } - } - class ArrayPrototypeSort extends BuiltinFunctionObject { - ArrayPrototypeSort(String name, Evaluator evaluator, FunctionPrototype fp) { - super(fp, evaluator, name, 1); - } - public ESValue callFunction(ESObject thisObject, - ESValue[] arguments) - throws EcmaScriptException { - if (!(thisObject instanceof ArrayPrototype)) { - throw new EcmaScriptException ("sort only implemented for arrays"); - } - ESValue compareFn = null; - if (arguments.length>0) compareFn = arguments[0]; - return ((ArrayPrototype) thisObject).sort(compareFn); - } - } - - arrayObject.putHiddenProperty("prototype",arrayPrototype); - arrayObject.putHiddenProperty(LENGTHstring,new ESNumber(1)); - - arrayPrototype.putHiddenProperty("constructor",arrayObject); - arrayPrototype.putHiddenProperty("toString", - new ArrayPrototypeToString("toString", evaluator, functionPrototype)); - arrayPrototype.putHiddenProperty("join", - new ArrayPrototypeJoin("join", evaluator, functionPrototype)); - arrayPrototype.putHiddenProperty("reverse", - new ArrayPrototypeReverse("reverse", evaluator, functionPrototype)); - arrayPrototype.putHiddenProperty("sort", - new ArrayPrototypeSort("sort", evaluator, functionPrototype)); - } catch (EcmaScriptException e) { - e.printStackTrace(); - throw new ProgrammingError(e.getMessage()); - } - - evaluator.setArrayPrototype(arrayPrototype); - - return arrayObject; - } -} \ No newline at end of file diff --git a/src/FESI/Data/ArrayPrototype.java b/src/FESI/Data/ArrayPrototype.java deleted file mode 100644 index c9b4d495..00000000 --- a/src/FESI/Data/ArrayPrototype.java +++ /dev/null @@ -1,585 +0,0 @@ -// ArrayPrototype.java -// FESI Copyright (c) Jean-Marc Lugrin, 1999 -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2 of the License, or (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. - -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -package FESI.Data; - -import FESI.Exceptions.*; -import FESI.Interpreter.*; - -import java.util.Vector; -import java.util.Enumeration; -import java.lang.reflect.Array; - -/** - * Implements the prototype and is the class of all Array objects - */ -public class ArrayPrototype extends ESObject { - - private static final String LENGTHstring = ("length").intern(); - private static final int LENGTHhash = LENGTHstring.hashCode(); - - // The array value - // We could use a non synchronized vector or directly and array - protected Vector theArray = new Vector(); - - /** - * Create a new empty array - * @param prototype the ArrayPrototype - * @param evaluator The evaluator - */ - public ArrayPrototype(ESObject prototype, Evaluator evaluator) { - super(prototype, evaluator); - } - - // overrides - public String getESClassName() { - return "Array"; - } - - /** - * Return a Java array object which is the object to pass to Java routines - * called by FESI. - * @ param componentType the type of the component of the array - * @return a java array object - */ - public Object toJavaArray(Class componentType) throws EcmaScriptException { - int l = size(); - Object array = Array.newInstance(componentType, l); - if (l ==0) return array; - for (int i =0; i0) { - Vector reversed = new Vector(size); - reversed.setSize(size); - for (int i = 0, j=size-1; i b) return a number > 0; - * if (a == b) return 0; - * if (a < b) return a number < 0. - **/ - int compare(ESValue a, ESValue b) throws EcmaScriptException; - } - - static class DefaultComparer implements Comparer { - public int compare(ESValue v1, ESValue v2) throws EcmaScriptException { - ESValue v1p = v1.toESPrimitive(ESValue.EStypeNumber); - ESValue v2p = v2.toESPrimitive(ESValue.EStypeNumber); - if (v1p == ESUndefined.theUndefined && v2p == ESUndefined.theUndefined) return 0; - if (v1p == ESUndefined.theUndefined ) return 1; - if (v2p == ESUndefined.theUndefined ) return -1; - //System.out.println("v1p = " + v1 + " v2p = " + v2); - String s1 = v1.toString(); - String s2 = v2.toString(); - //System.out.println("s1 = " + s1 + " s2 = " + s2); - return s1.compareTo(s2); - } - } - - /** - * This is the main sort() routine. It performs a quicksort on the elements - * of array a between the element from and the element to. - * The Comparer argument c is used to perform - * comparisons between elements of the array. - **/ - private void sort(int from, int to, - Comparer c) throws EcmaScriptException - { - // If there is nothing to sort, return - if (theArray.size() < 2) return; - - // This is the basic quicksort algorithm, stripped of frills that can make - // it faster but even more confusing than it already is. You should - // understand what the code does, but don't have to understand just - // why it is guaranteed to sort the array... - // Note the use of the compare() method of the Comparer object. - int i = from, j = to; - ESValue center = (ESValue) theArray.elementAt((from + to) / 2); - do { - ESValue ai = (ESValue) theArray.elementAt(i); - ESValue aj = (ESValue) theArray.elementAt(j); - while((i < to) && (c.compare(center, ai) > 0)) { i++; ai = (ESValue) theArray.elementAt(i);} - while((j > from) && (c.compare(center, aj) < 0)) {j--; aj = (ESValue) theArray.elementAt(j);} - if (i < j) { - Object tmp = ai; theArray.setElementAt(aj,i); theArray.setElementAt(tmp, j); - } - if (i <= j) { i++; j--; } - } while(i <= j); - if (from < j) sort(from, j, c); // recursively sort the rest - if (i < to) sort(i, to, c); - } - - /** - * Sort the array with a specified compare routine - * @param compareFn A function returning a comparer - * @return the sorted array (in place) - */ - public ESValue sort(ESValue compareFn) throws EcmaScriptException { - if ((compareFn != null) && - (!(compareFn instanceof FunctionPrototype))) { - throw new EcmaScriptException("Compare function not a function: " + compareFn); - } - Comparer c = null; - if (compareFn != null) - c = new FunctionComparer((FunctionPrototype) compareFn); - else - c = new DefaultComparer(); - - sort(0, theArray.size()-1, c); - return this; - } - - // overrides - public void putProperty(String propertyName, ESValue propertyValue, int hash) - throws EcmaScriptException { - if (hash==LENGTHhash && propertyName.equals(LENGTHstring)) { - int length = (int) (((ESPrimitive) propertyValue).doubleValue()); - if (length<0) { - throw new EcmaScriptException("Invalid length value: " + propertyValue); - } - theArray.setSize(length); - } else { - int index = -1; // indicates not a valid index value - try { - index = Integer.parseInt(propertyName); // should be uint - } catch (NumberFormatException e) { - } - if (index<0) { - super.putProperty(propertyName, propertyValue, hash); - } else { - putProperty(index, propertyValue); - } - } - } - - // overrides - public void putProperty(int index, ESValue propertyValue) - throws EcmaScriptException { - - if (index>=theArray.size()) { - theArray.setSize(index+1); - } - theArray.setElementAt(propertyValue, index); - } - - // overrides - public ESValue getPropertyInScope(String propertyName, ScopeChain previousScope, int hash) - throws EcmaScriptException { - if (hash==LENGTHhash && propertyName.equals(LENGTHstring)) { - return new ESNumber(theArray.size()); - } - if (hasProperty(propertyName, hash)) { - return getProperty(propertyName, hash); - } - if (previousScope == null) { - throw new EcmaScriptException("global variable '" + propertyName + "' does not have a value"); - } else { - return previousScope.getValue(propertyName, hash); - } - } - - // overrides - public ESValue getProperty(String propertyName, int hash) - throws EcmaScriptException { - if (hash==LENGTHhash && propertyName.equals(LENGTHstring)) { - return new ESNumber(theArray.size()); - } else { - int index = -1; // indicates not a valid index value - try { - index = Integer.parseInt(propertyName); // should be uint - } catch (NumberFormatException e) { - } - if (index<0) { - return super.getProperty(propertyName, hash); - } else { - return getProperty(index); - } - } - } - - // overrides - public ESValue getProperty(int index) - throws EcmaScriptException { - Object theElement = null; - if (index Skip elements which were never set (are null), as Netscape - * SHOULD USE SUPER INSTEAD ! - * @return the enumerator - */ - public Enumeration getProperties() { - return new Enumeration() { - Enumeration props = properties.keys(); - Object currentKey = null; - int currentHash = 0; - int nextIndex = 0; - boolean inside = false; - ESObject prototype = ArrayPrototype.this.getPrototype(); - public boolean hasMoreElements() { - // Check if hasMoreElements was already called - if (currentKey != null) return true; - - // Check if a numeric key is appropriate - while ( (nextIndex