You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2018/08/13 10:06:26 UTC
[4/4] groovy-examples git commit: initial version
initial version
Project: http://git-wip-us.apache.org/repos/asf/groovy-examples/repo
Commit: http://git-wip-us.apache.org/repos/asf/groovy-examples/commit/3bd1e181
Tree: http://git-wip-us.apache.org/repos/asf/groovy-examples/tree/3bd1e181
Diff: http://git-wip-us.apache.org/repos/asf/groovy-examples/diff/3bd1e181
Branch: refs/heads/master
Commit: 3bd1e1811c5306b0d8dbf65c9bde6091596a1307
Parents: 4007783
Author: Paul King <pa...@asert.com.au>
Authored: Sun Aug 12 15:20:11 2018 +1000
Committer: Paul King <pa...@asert.com.au>
Committed: Sun Aug 12 15:20:11 2018 +1000
----------------------------------------------------------------------
README.md | 5 +
build.gradle | 34 +
gradle.properties | 5 +
gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 54417 bytes
gradle/wrapper/gradle-wrapper.properties | 5 +
gradlew | 172 +++++
gradlew.bat | 84 +++
src/main/groovy/astbuilder/Main.groovy | 38 ++
src/main/groovy/astbuilder/MainExample.groovy | 34 +
.../astbuilder/MainIntegrationTest.groovy | 44 ++
.../groovy/astbuilder/MainTransformation.groovy | 80 +++
src/main/groovy/astbuilder/build.xml | 43 ++
src/main/groovy/astbuilder/readme.txt | 42 ++
src/main/groovy/commandLineTools/AntMap.groovy | 84 +++
.../groovy/commandLineTools/BigTests.groovy | 51 ++
.../groovy/commandLineTools/ListFiles.groovy | 43 ++
.../groovy/commandLineTools/Reflections.groovy | 36 ++
.../commandLineTools/SimpleWebServer.groovy | 90 +++
.../groovy/console/MortgageCalculator.groovy | 95 +++
src/main/groovy/console/knowYourTables.groovy | 34 +
src/main/groovy/console/thinkOfANumber.groovy | 39 ++
src/main/groovy/groovy/j2ee/CreateData.groovy | 41 ++
src/main/groovy/groovy/j2ee/J2eeConsole.java | 78 +++
src/main/groovy/groovy/model/MvcDemo.groovy | 61 ++
src/main/groovy/groovy/swing/Demo.java | 55 ++
src/main/groovy/groovy/swing/MyTableModel.java | 123 ++++
src/main/groovy/groovy/swing/SwingDemo.groovy | 127 ++++
src/main/groovy/groovy/swing/TableDemo.groovy | 72 +++
.../groovy/groovy/swing/TableLayoutDemo.groovy | 76 +++
.../groovy/groovy2d/paintingByNumbers.groovy | 66 ++
.../groovy/groovyShell/ArithmeticShell.groovy | 157 +++++
.../groovyShell/ArithmeticShellTest.groovy | 108 ++++
.../groovy/groovyShell/BlacklistingShell.groovy | 96 +++
.../groovyShell/BlacklistingShellTest.groovy | 82 +++
.../DefaultGrailsDomainClassInjector.java | 264 ++++++++
.../grails/compiler/injection/DomainClass.java | 38 ++
src/main/groovy/osgi/build.properties | 28 +
src/main/groovy/osgi/build.xml | 140 +++++
.../org/codehaus/groovy/osgi/Activator.groovy | 59 ++
.../codehaus/groovy/osgi/GroovyGreeter.groovy | 30 +
.../groovy/osgi/GroovyGreeterImpl.groovy | 31 +
.../groovy/osgi/harness/HarnessActivator.groovy | 50 ++
src/main/groovy/osgi/readme.txt | 140 +++++
src/main/groovy/searchEngine/Indexer.groovy | 83 +++
src/main/groovy/searchEngine/Searcher.groovy | 61 ++
src/main/groovy/swing/BindingExample.groovy | 63 ++
src/main/groovy/swing/BloglinesClient.groovy | 188 ++++++
src/main/groovy/swing/ModelNodeExample.groovy | 89 +++
src/main/groovy/swing/RegexCoach.groovy | 126 ++++
.../groovy/swing/RegexCoachController.groovy | 107 ++++
src/main/groovy/swing/RegexCoachView.groovy | 55 ++
src/main/groovy/swing/Widgets.groovy | 220 +++++++
.../swing/binding/caricature/Caricature.groovy | 79 +++
.../swing/binding/caricature/JCaricature.java | 220 +++++++
.../binding/caricature/resources/eyes1.gif | Bin 0 -> 1789 bytes
.../binding/caricature/resources/eyes2.gif | Bin 0 -> 1925 bytes
.../binding/caricature/resources/eyes3.gif | Bin 0 -> 1969 bytes
.../binding/caricature/resources/eyes4.gif | Bin 0 -> 2355 bytes
.../binding/caricature/resources/eyes5.gif | Bin 0 -> 1829 bytes
.../binding/caricature/resources/face1.gif | Bin 0 -> 2548 bytes
.../binding/caricature/resources/face2.gif | Bin 0 -> 2395 bytes
.../binding/caricature/resources/face3.gif | Bin 0 -> 2707 bytes
.../binding/caricature/resources/face4.gif | Bin 0 -> 2324 bytes
.../binding/caricature/resources/face5.gif | Bin 0 -> 2445 bytes
.../binding/caricature/resources/glasses.gif | Bin 0 -> 2092 bytes
.../caricature/resources/glassesWEyes.gif | Bin 0 -> 2209 bytes
.../binding/caricature/resources/hair1.gif | Bin 0 -> 3449 bytes
.../binding/caricature/resources/hair2.gif | Bin 0 -> 2477 bytes
.../binding/caricature/resources/hair3.gif | Bin 0 -> 2409 bytes
.../binding/caricature/resources/hair4.gif | Bin 0 -> 2771 bytes
.../binding/caricature/resources/hair5.gif | Bin 0 -> 4387 bytes
.../binding/caricature/resources/mouth1.gif | Bin 0 -> 971 bytes
.../binding/caricature/resources/mouth2.gif | Bin 0 -> 1046 bytes
.../binding/caricature/resources/mouth3.gif | Bin 0 -> 1639 bytes
.../binding/caricature/resources/mouth4.gif | Bin 0 -> 1014 bytes
.../binding/caricature/resources/mouth5.gif | Bin 0 -> 1303 bytes
.../binding/caricature/resources/nose1.gif | Bin 0 -> 1230 bytes
.../binding/caricature/resources/nose2.gif | Bin 0 -> 1345 bytes
.../binding/caricature/resources/nose3.gif | Bin 0 -> 1366 bytes
.../binding/caricature/resources/nose4.gif | Bin 0 -> 1200 bytes
.../binding/caricature/resources/nose5.gif | Bin 0 -> 1399 bytes
src/main/groovy/swing/greet/Greet.groovy | 153 +++++
src/main/groovy/swing/greet/TwitterAPI.groovy | 162 +++++
src/main/groovy/swing/greet/View.groovy | 175 ++++++
.../groovy/swing/timelog/TimeLogMain.groovy | 46 ++
.../groovy/swing/timelog/TimeLogModel.groovy | 62 ++
.../groovy/swing/timelog/TimeLogView.groovy | 67 ++
.../global/CompiledAtASTTransformation.groovy | 66 ++
.../transforms/global/CompiledAtExample.groovy | 33 +
.../global/CompiledAtIntegrationTest.groovy | 39 ++
.../global/LoggingASTTransformation.groovy | 73 +++
.../transforms/global/LoggingExample.groovy | 48 ++
....codehaus.groovy.transform.ASTTransformation | 17 +
src/main/groovy/transforms/global/build.xml | 52 ++
src/main/groovy/transforms/global/readme.txt | 48 ++
.../local/LoggingASTTransformation.groovy | 74 +++
.../transforms/local/LoggingExample.groovy | 64 ++
.../groovy/transforms/local/WithLogging.groovy | 37 ++
src/main/groovy/transforms/local/build.xml | 44 ++
src/main/groovy/transforms/local/readme.txt | 40 ++
.../WEB-INF/groovy/Animal.groovy | 23 +
.../WEB-INF/groovy/zoo/Fish.groovy | 27 +
.../WEB-INF/groovy/zoo/fish/Shark.groovy | 29 +
.../WEB-INF/groovy/zoo/fish/Trout.groovy | 27 +
.../webapps/groovlet-examples/WEB-INF/web.xml | 89 +++
.../groovlet-examples/codehaus-style.css | 626 +++++++++++++++++++
.../groovlet-examples/hello/hello.groovy | 51 ++
.../webapps/groovlet-examples/images/code.gif | Bin 0 -> 292 bytes
.../groovlet-examples/images/execute.gif | Bin 0 -> 1242 bytes
.../webapps/groovlet-examples/images/groovy.png | Bin 0 -> 12303 bytes
.../webapps/groovlet-examples/images/return.gif | Bin 0 -> 1231 bytes
.../webapps/groovlet-examples/index.groovy | 107 ++++
.../groovy/webapps/groovlet-examples/readme.txt | 32 +
.../webapps/groovlet-examples/xml/index.xhtml | 58 ++
.../zoo/HommingbergerGepardenforelle.groovy | 27 +
.../webapps/groovlet-examples/zoo/visit.groovy | 37 ++
.../webapps/groovlet-examples/zoo/zoo.groovy | 48 ++
src/main/groovy/webapps/gsp-examples/readme.txt | 20 +
.../template-examples/3.times.HelloWorld.html | 33 +
.../WEB-INF/lib/groovy-all-xyz.jar.placeholder | 18 +
.../webapps/template-examples/WEB-INF/web.xml | 46 ++
.../template-examples/javasystemproperties.htm | 42 ++
.../groovy/webapps/template-examples/readme.txt | 32 +
123 files changed, 6943 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/README.md
----------------------------------------------------------------------
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..0636388
--- /dev/null
+++ b/README.md
@@ -0,0 +1,5 @@
+Groovy examples
+===============
+
+This is a repository of Groovy source files using common (at some point) libraries.
+It is expected that all the source files at least compile with the current version of Groovy.
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/build.gradle
----------------------------------------------------------------------
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 0000000..7b54e45
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,34 @@
+plugins {
+// id 'com.github.spotbugs' version '1.6.2'
+ id "com.github.ben-manes.versions" version '0.20.0'
+}
+apply plugin: 'groovy'
+apply plugin: 'idea'
+
+repositories {
+ mavenCentral()
+ maven { url 'https://repository.jboss.org/nexus/content/groups/m2-release-proxy/' }
+ maven { url 'https://oss.jfrog.org/oss-snapshot-local/' }
+}
+
+dependencies {
+ compile "org.codehaus.groovy:groovy-all:$groovyVersion"
+
+ compile "org.apache.lucene:lucene-core:$luceneVersion"
+ compile "org.apache.lucene:lucene-analyzers-common:$luceneVersion"
+ compile "org.apache.lucene:lucene-queryparser:$luceneVersion"
+ compile "org.eclipse:osgi:$eclipseOsgiVersion"
+ compile("commons-httpclient:commons-httpclient:$commonsHttpClientVersion") {
+ exclude(module: 'junit')
+ exclude(module: 'commons-logging')
+ exclude(module: 'commons-codec')
+ }
+ runtime("openejb:openejb-loader:$openejbVersion") {
+ exclude(module: 'log4j')
+ exclude(module: 'openejb-core')
+ exclude(module: 'geronimo-jta_1.0.1B_spec')
+ exclude(module: 'geronimo-servlet_2.4_spec')
+ exclude(module: 'geronimo-ejb_2.1_spec')
+ exclude(module: 'geronimo-j2ee-connector_1.5_spec')
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/gradle.properties
----------------------------------------------------------------------
diff --git a/gradle.properties b/gradle.properties
new file mode 100644
index 0000000..0277b23
--- /dev/null
+++ b/gradle.properties
@@ -0,0 +1,5 @@
+groovyVersion=3.0.0-SNAPSHOT
+luceneVersion=7.4.0
+eclipseOsgiVersion=3.10.0-v20140606-1445
+commonsHttpClientVersion=3.1
+openejbVersion=1.0
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/gradle/wrapper/gradle-wrapper.jar
----------------------------------------------------------------------
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..758de96
Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/gradle/wrapper/gradle-wrapper.properties
----------------------------------------------------------------------
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..a95009c
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/gradlew
----------------------------------------------------------------------
diff --git a/gradlew b/gradlew
new file mode 100644
index 0000000..cccdd3d
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,172 @@
+#!/usr/bin/env sh
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn () {
+ echo "$*"
+}
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+ NONSTOP* )
+ nonstop=true
+ ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Escape application args
+save () {
+ for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
+ echo " "
+}
+APP_ARGS=$(save "$@")
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
+if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
+ cd "$(dirname "$0")"
+fi
+
+exec "$JAVACMD" "$@"
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/gradlew.bat
----------------------------------------------------------------------
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..f955316
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,84 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windows variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/astbuilder/Main.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/astbuilder/Main.groovy b/src/main/groovy/astbuilder/Main.groovy
new file mode 100644
index 0000000..03ffa46
--- /dev/null
+++ b/src/main/groovy/astbuilder/Main.groovy
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package astbuilder
+
+import org.codehaus.groovy.transform.GroovyASTTransformationClass
+import java.lang.annotation.ElementType
+import java.lang.annotation.Target
+import java.lang.annotation.RetentionPolicy
+import java.lang.annotation.Retention
+
+/**
+ * Marker interface to mark a method as something that should be invokable
+ * as a main() method. An AST transformation will later wire this together.
+ *
+ * @author Hamlet D'Arcy
+ */
+
+@Retention (RetentionPolicy.SOURCE)
+@Target ([ElementType.METHOD])
+@GroovyASTTransformationClass (["examples.astbuilder.MainTransformation"])
+public @interface Main {
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/astbuilder/MainExample.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/astbuilder/MainExample.groovy b/src/main/groovy/astbuilder/MainExample.groovy
new file mode 100644
index 0000000..2469a2c
--- /dev/null
+++ b/src/main/groovy/astbuilder/MainExample.groovy
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package astbuilder
+
+/**
+ * Exists to test the @Main annotation. At compile time, there will be a main()
+ * method added to this class that has the same body as the greet() method.
+ * It can be invoked either by using either Java or Groovy to run the class.
+ *
+ * @author Hamlet D'Arcy
+ */
+class MainExample {
+
+ @Main
+ public void greet() {
+ println "Hello from the greet() method!"
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/astbuilder/MainIntegrationTest.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/astbuilder/MainIntegrationTest.groovy b/src/main/groovy/astbuilder/MainIntegrationTest.groovy
new file mode 100644
index 0000000..92052e4
--- /dev/null
+++ b/src/main/groovy/astbuilder/MainIntegrationTest.groovy
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package astbuilder
+
+import org.codehaus.groovy.tools.ast.TransformTestHelper
+import org.codehaus.groovy.control.CompilePhase
+
+/**
+ *
+ * This TestCase shows how to invoke an AST Transformation from a unit test.
+ * An IDE will let you step through the AST Transformation using this approach.
+ *
+ * @author Hamlet D'Arcy
+ */
+
+class MainIntegrationTest extends GroovyTestCase {
+
+ public void testInvokeUnitTest() {
+ def invoker = new TransformTestHelper(new MainTransformation(), CompilePhase.CANONICALIZATION)
+
+ def file = new File('./MainExample.groovy')
+ assert file.exists()
+
+ def clazz = invoker.parse(file)
+ def tester = clazz.newInstance()
+ tester.main(null) // main method added with AST transform
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/astbuilder/MainTransformation.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/astbuilder/MainTransformation.groovy b/src/main/groovy/astbuilder/MainTransformation.groovy
new file mode 100644
index 0000000..ce07916
--- /dev/null
+++ b/src/main/groovy/astbuilder/MainTransformation.groovy
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package astbuilder
+
+import org.codehaus.groovy.ast.*
+import org.codehaus.groovy.control.CompilePhase
+import org.codehaus.groovy.transform.GroovyASTTransformation
+import org.codehaus.groovy.transform.ASTTransformation
+import org.codehaus.groovy.control.SourceUnit
+import org.codehaus.groovy.ast.builder.AstBuilder
+
+/**
+ * If there is a method in a class with the @Main annotation on it, then this
+ * transformation adds a real main(String[]) method to the class with the same
+ * method body as the annotated class.
+ *
+ * @author Hamlet D'Arcy
+ */
+@GroovyASTTransformation(phase = CompilePhase.INSTRUCTION_SELECTION)
+public class MainTransformation implements ASTTransformation {
+
+ // normally defined in org.objectweb.asm.Opcodes, but there duplicated
+ // here to make the build script simpler.
+ static int PUBLIC = 1
+ static int STATIC = 8
+
+ void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
+
+ // use guard clauses as a form of defensive programming.
+ if (!astNodes) return
+ if (!astNodes[0]) return
+ if (!astNodes[1]) return
+ if (!(astNodes[0] instanceof AnnotationNode)) return
+ if (astNodes[0].classNode?.name != Main.class.name) return
+ if (!(astNodes[1] instanceof MethodNode)) return
+
+ MethodNode annotatedMethod = astNodes[1]
+ ClassNode declaringClass = annotatedMethod.declaringClass
+ MethodNode mainMethod = makeMainMethod(annotatedMethod)
+ declaringClass.addMethod(mainMethod)
+ }
+
+ /**
+ * Uses the AstBuilder to synthesize a main method, and then sets the body of
+ * the method to that of the source method. Notice how Void.TYPE is used as
+ * a return value instead of Void.class. This is required so that resulting method
+ * is void and not Void.
+ */
+ MethodNode makeMainMethod(MethodNode source) {
+ def className = source.declaringClass.name
+ def methodName = source.name
+
+ def ast = new AstBuilder().buildFromString(CompilePhase.INSTRUCTION_SELECTION, false, """
+ package $source.declaringClass.packageName
+
+ class $source.declaringClass.nameWithoutPackage {
+ public static void main(String[] args) {
+ new $className().$methodName()
+ }
+ }
+ """)
+ ast[1].methods.find { it.name == 'main' }
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/astbuilder/build.xml
----------------------------------------------------------------------
diff --git a/src/main/groovy/astbuilder/build.xml b/src/main/groovy/astbuilder/build.xml
new file mode 100644
index 0000000..3f31815
--- /dev/null
+++ b/src/main/groovy/astbuilder/build.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+<project name="groovy-astbuilder-usage-example" default="compile-transform">
+
+ <!-- necessary groovy jars are assumed to be on your classpath. -->
+ <taskdef name="groovyc" classname="org.codehaus.groovy.ant.Groovyc" />
+
+ <target name="init" description="cleanup old class files">
+ <delete dir="examples"/>
+ </target>
+
+ <target name="compile-transform" depends="init" description="Compiles the AST Transformation">
+
+ <groovyc destdir="."
+ srcdir="."
+ includes="Main.groovy,MainTransformation.groovy"
+ listfiles="true">
+ </groovyc>
+
+ <echo>You can now run "groovy MainExample.groovy", "groovyc MainExample.groovy", or "groovy MainIntegrationTest.groovy" to see that the transformation worked.</echo>
+ </target>
+
+</project>
+
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/astbuilder/readme.txt
----------------------------------------------------------------------
diff --git a/src/main/groovy/astbuilder/readme.txt b/src/main/groovy/astbuilder/readme.txt
new file mode 100644
index 0000000..25f7f99
--- /dev/null
+++ b/src/main/groovy/astbuilder/readme.txt
@@ -0,0 +1,42 @@
+====
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+====
+
+AstBuilder and AST Transformation Example
+
+This example shows how to use the AstBuilder to add a public static void main(String[])
+method to a class.
+
+The example requires ant in your path and the Groovy 1.7 (or greater)
+Jar in your classpath.
+
+To build the example run "ant" from the current directory. The default
+target will compile the classes needed. The last step of the build
+script prints out the command needed to run the example.
+
+To run the example perform either of the following from the command lines:
+ groovy MainExample.groovy
+ groovyc MainExample.groovy (and then invoke with java or view with javap)
+
+The example should print:
+ Hello from the greet() method!
+
+No exceptions should occur.
+
+The MainIntegrationTest.groovy file shows how to invoke an ASTTransformation
+from a unit test. An IDE should be able to debug this.
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/commandLineTools/AntMap.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/commandLineTools/AntMap.groovy b/src/main/groovy/commandLineTools/AntMap.groovy
new file mode 100644
index 0000000..741c817
--- /dev/null
+++ b/src/main/groovy/commandLineTools/AntMap.groovy
@@ -0,0 +1,84 @@
+#!/bin/env groovy
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//
+// convert an ant build file into a format suitable for http://sf.net/projects/freemind
+//
+// by Jeremy Rayner - 2 Dec 2004
+// inspired by Sam Newman ( http://www.magpiebrain.com/archives/2004/12/02/antgui )
+//
+// usage: groovy AntMap > build.mm
+
+buildFileName = "build.xml" // default
+
+// handle command line params
+if (args.length > 0) {
+ buildFileName = args[0]
+}
+
+// header
+println "<map version='0.7.1'>"
+project = new XmlParser().parse(buildFileName)
+name = project['@name']
+println "<node TEXT='${name}'>"
+level = 0
+
+printChildren(project,level)
+
+
+
+def void printChildren(node,level) {
+ level++
+ node.each {
+ name = huntForName(it)
+ if (name != null) {
+ if (level > 1) {
+ println "<node TEXT='${name}' POSITION='right'>"
+ } else if (it.name() == 'property' || it.name() == 'path' ) {
+ if (it.children().size() > 0) {
+ println "<node TEXT='${name}' POSITION='left' FOLDED='true'>"
+ } else {
+ println "<node TEXT='${name}' POSITION='left'>"
+ }
+ } else if (it.children().size() > 0) {
+ println "<node TEXT='${name}' POSITION='right' FOLDED='true'>"
+ } else {
+ println "<node TEXT='${name}' POSITION='right'>"
+ }
+ }
+ if (it.children().size() > 0) printChildren(it,level)
+ if (name!=null) println "</node>"
+ }
+}
+
+// footer
+println "</node></map>"
+
+
+def String huntForName(node) {
+ preferNodeNames = ["junitreport"]
+ if (node == null) return null
+ if (preferNodeNames.contains(node.name())) return node.name()
+ if (node['@name'] != null) return node['@name']
+ if (node['@todir'] != null) return node['@todir']
+ if (node['@dir'] != null) return node['@dir']
+ if (node['@refid'] != null) return node['@refid']
+ return node.name()
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/commandLineTools/BigTests.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/commandLineTools/BigTests.groovy b/src/main/groovy/commandLineTools/BigTests.groovy
new file mode 100644
index 0000000..85fa13b
--- /dev/null
+++ b/src/main/groovy/commandLineTools/BigTests.groovy
@@ -0,0 +1,51 @@
+#!/bin/env groovy
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+//
+// output tests in a junit xml report that took greater than specified time
+//
+// by Jeremy Rayner - 15 Dec 2004
+//
+// usage: groovy BigTests.groovy <TEST.xml> <time in secs>
+
+fileName = "" // default
+timeCutOff = new Float("1.0")
+
+if (args.length > 1) {
+ fileName = args[0]
+ timeCutOff = new Float(args[1])
+} else {
+ println "usage: groovy BigTests.groovy <TEST.xml> <time in secs>"
+}
+
+testSuite = new XmlParser().parse(fileName)
+name = testSuite['@name']
+println "TestSuite: ${name}"
+bigTests = [:]
+testSuite.each {
+ if ("testcase" == it.name()) {
+ classname = it['@classname']
+ name = it['@name']
+ time = new Float(it['@time'])
+ if (time > timeCutOff) {
+ println " ${time} - ${classname}.${name}()"
+ }
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/commandLineTools/ListFiles.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/commandLineTools/ListFiles.groovy b/src/main/groovy/commandLineTools/ListFiles.groovy
new file mode 100644
index 0000000..e3d1f71
--- /dev/null
+++ b/src/main/groovy/commandLineTools/ListFiles.groovy
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+public class ListFilesManualTest {
+
+ static void main(args) {
+ println("Called main with ${args}")
+ listFiles(Arrays.asList(args))
+ }
+
+ static String getPath(file) {
+ return file.absolutePath
+ }
+
+ static void listFiles(dirs) {
+ println("called with ${dirs}")
+
+ for(dir in dirs) {
+ println("dir: ${dir}")
+
+ def files = new java.io.File(dir).listFiles()
+
+ for (f in files) {
+ println(getPath(f))
+ }
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/commandLineTools/Reflections.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/commandLineTools/Reflections.groovy b/src/main/groovy/commandLineTools/Reflections.groovy
new file mode 100644
index 0000000..4be7551
--- /dev/null
+++ b/src/main/groovy/commandLineTools/Reflections.groovy
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Echoes back whatever is thrown at it (with a <br> at end for browsers) ...
+ * @author <a href="mailto:jeremy.rayner@gmail.com">Jeremy Rayner</a>
+ *
+ * invoke using
+ * groovy -l 80 Reflections.groovy
+ *
+ * (where 80 is the port to listen for requests upon)
+ */
+
+// echo, echo, echo...
+println "${line} <br>"
+
+//assume no input means we've finished...
+if (line == "") {
+ // clean up gracefully, closing sockets etc
+ return "success"
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/commandLineTools/SimpleWebServer.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/commandLineTools/SimpleWebServer.groovy b/src/main/groovy/commandLineTools/SimpleWebServer.groovy
new file mode 100644
index 0000000..09835d7
--- /dev/null
+++ b/src/main/groovy/commandLineTools/SimpleWebServer.groovy
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Simple web server
+ * @author <a href="mailto:jeremy.rayner@gmail.com">Jeremy Rayner</a>
+ *
+ * invoke using
+ * groovy -l 80 SimpleWebServer.groovy
+ *
+ * (where 80 is the port to listen for requests upon)
+ */
+if (init) {
+ headers = [:]
+ binaryTypes = ["gif","jpg","png"]
+ mimeTypes = [
+ "css" : "text/css",
+ "gif" : "image/gif",
+ "htm" : "text/html",
+ "html": "text/html",
+ "jpg" : "image/jpeg",
+ "png" : "image/png"
+ ]
+}
+
+// parse the request
+if (line.toLowerCase().startsWith("get")) {
+ content = line.tokenize()[1]
+} else {
+ h = line.tokenize(":")
+ headers[h[0]] = h[1]
+}
+
+// all done, now process request
+if (line.size() == 0) {
+ processRequest()
+ return "success"
+}
+
+// ------------------------
+
+def processRequest() {
+ if (content.indexOf("..") < 0) { //simplistic security
+ // simple file browser rooted from current dir
+ f = new File("." + content)
+ if (f.isDirectory()) {
+ printDirectoryListing(f)
+ } else {
+ extension = content.substring(content.lastIndexOf(".") + 1)
+ printHeaders(mimeTypes.get(extension,"text/plain"))
+
+ if (binaryTypes.contains(extension)) {
+ socket.outputStream.write(f.readBytes())
+ } else {
+ println(f.text)
+ }
+ }
+ }
+}
+
+def printDirectoryListing(f) {
+ printHeaders("text/html")
+ println "<html><head></head><body>"
+ for (i in f.list().toList().sort()) {
+ if ("/" == content) { content = "" } // special case for root document
+ println "<a href='${content}/${i}'>${i}</a><br>"
+ }
+ println "</body></html>"
+}
+
+def printHeaders(mimeType) {
+ println "HTTP/1.0 200 OK"
+ println "Content-Type: ${mimeType}"
+ println ""
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/console/MortgageCalculator.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/console/MortgageCalculator.groovy b/src/main/groovy/console/MortgageCalculator.groovy
new file mode 100644
index 0000000..375e244
--- /dev/null
+++ b/src/main/groovy/console/MortgageCalculator.groovy
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Mortgage Calculator
+ * @author: Jeremy Rayner
+ * based on algorithms by Jeff Louie, Dr W Carlini and Newton
+ */
+
+println "__..::~~'''~~::..__"
+println "Mortgage Calculator"
+println "~~~~~~~~~~~~~~~~~~~"
+println "Please input 3 of the 4 values in your mortgage calculation"
+println "This program will then calculate the value you leave blank"
+println ""
+
+def variables = [
+ "Amount of mortgage" : 0.0,
+ "Annual interest rate (%)" : 0.0,
+ "Loan duration (months)" : 0.0,
+ "Monthly payments" : 0.0
+]
+
+for (entry in variables.entrySet()) {
+ print("${entry.key}:")
+ def userInput = System.in.readLine()
+ if ("" == userInput) {
+ valueToCalculate = entry.key
+ } else {
+ entry.value = userInput.toDouble()
+ }
+}
+
+println "$valueToCalculate = ${calculateValueOf(valueToCalculate)}"
+
+
+
+
+
+def calculateValueOf(valueToCalculate) {
+ def result = 0
+ def principal = variables["Amount of mortgage"]
+ def interest = variables["Annual interest rate (%)"] / 1200
+ def months = variables["Loan duration (months)"]
+ def payment = variables["Monthly payments"]
+
+ switch (valueToCalculate) {
+ case "Amount of mortgage":
+ result = 1 + interest
+ result = 1/Math.pow(result,months)
+ result = ((1-result)/interest) * payment
+ break
+ case "Loan duration (months)":
+ result = (1 - (principal * interest / payment))
+ result = Math.log(result)
+ result = - result / Math.log(1 + interest)
+ break
+ case "Monthly payments":
+ result = 1 + interest
+ result = 1 / Math.pow(result,months)
+ result = (principal * interest) / (1 - result)
+ break
+ case "Annual interest rate (%)":
+ result = payment / principal
+ def diff = 100; def accuracy = 0.00001; def maxIterations = 1000
+ def index = 0
+ while ((diff > accuracy) && (index < maxIterations)) {
+ def temp = result
+ def numerator = (principal * temp / payment) + Math.pow((1 + temp), -months) - 1
+ def denominator= (principal / payment) - months * Math.pow((1 + temp), (-months - 1))
+ result = temp - (numerator / denominator)
+ diff = result - temp
+ diff = Math.abs(diff)
+ index++
+ }
+ result *= 1200
+ break
+ }
+ return result
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/console/knowYourTables.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/console/knowYourTables.groovy b/src/main/groovy/console/knowYourTables.groovy
new file mode 100644
index 0000000..1343365
--- /dev/null
+++ b/src/main/groovy/console/knowYourTables.groovy
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Simple mathematics quiz
+ * @author: Jeremy Rayner
+ * based on algorithms from INPUT/Marshall Cavendish/1984
+ */
+while (true) {
+ try {
+ def n = (int)(Math.random() * 12) + 1
+ println "What is $n times 9?"
+ def a = System.in.readLine().toInteger()
+ if (a == n * 9) println "Correct"
+
+ } catch (Exception e) {
+ println "The computer didn't understand your input"
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/console/thinkOfANumber.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/console/thinkOfANumber.groovy b/src/main/groovy/console/thinkOfANumber.groovy
new file mode 100644
index 0000000..7a42cf9
--- /dev/null
+++ b/src/main/groovy/console/thinkOfANumber.groovy
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Simple game
+ * @author: Jeremy Rayner
+ * based on algorithms from INPUT/Marshall Cavendish/1984
+ */
+while (true) {
+ try {
+ int x = Math.random() * 6
+ print "The computer has chosen a number between 0 and 5. Can you guess it?"
+
+ def line = System.in.readLine()
+ int g = line.toInteger()
+ if (g == x) {
+ println "Well done"
+ } else {
+ println "Tough luck - you're wrong"
+ }
+ } catch (NumberFormatException e) {
+ println "The computer didn't understand '$line'"
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/groovy/j2ee/CreateData.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/groovy/j2ee/CreateData.groovy b/src/main/groovy/groovy/j2ee/CreateData.groovy
new file mode 100644
index 0000000..a0bef2a
--- /dev/null
+++ b/src/main/groovy/groovy/j2ee/CreateData.groovy
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+println("Called with context: " + context)
+
+db = context.lookup("/client/tools/DatabaseHome").create()
+
+println("About to do queries on: " + db)
+
+queries = [
+ "CREATE TABLE account ( ssn CHAR(11) PRIMARY KEY, first_name CHAR(20), last_name CHAR(20), balance INT)",
+ "CREATE TABLE entity ( id INT PRIMARY KEY AUTO INCREMENT, first_name CHAR(20), last_name CHAR(20) )"
+]
+
+for (sql in queries) {
+ println("evaluating: " + sql)
+ db.execute(sql)
+}
+
+println("creating entity bean")
+
+context.lookup("/client/tests/entity/bmp/BasicBmpHome").create("Groovy Dain")
+
+println("Done")
+
+"OK"
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/groovy/j2ee/J2eeConsole.java
----------------------------------------------------------------------
diff --git a/src/main/groovy/groovy/j2ee/J2eeConsole.java b/src/main/groovy/groovy/j2ee/J2eeConsole.java
new file mode 100644
index 0000000..538ebf6
--- /dev/null
+++ b/src/main/groovy/groovy/j2ee/J2eeConsole.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.j2ee;
+
+import groovy.lang.GroovyObject;
+import groovy.lang.GroovyShell;
+import org.codehaus.groovy.runtime.InvokerHelper;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import java.util.Properties;
+
+/**
+ * A J2EE console
+ *
+ * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
+ */
+public class J2eeConsole {
+
+ public static void main(String[] args) {
+ if (args.length <= 0) {
+ System.out.println("Usage: home [configuaration] [localcopy]");
+ return;
+ }
+
+ String home = args[0];
+
+ Properties p = new Properties();
+ System.setProperty("openejb.home", home);
+ p.put(Context.INITIAL_CONTEXT_FACTORY, "org.openejb.client.LocalInitialContextFactory");
+ p.put("openejb.loader", "embed");
+ p.put("openejb.home", home);
+
+ if (args.length > 1) {
+ String conf = args[1];
+ System.setProperty("openejb.configuration", conf);
+ p.put("openejb.configuration", conf);
+ }
+ if (args.length > 2) {
+ String copy = args[2];
+ System.setProperty("openejb.localcopy", copy);
+ p.put("openejb.localcopy", copy);
+ }
+ try {
+ InitialContext ctx = new InitialContext(p);
+
+ GroovyShell shell = new GroovyShell();
+ shell.setVariable("context", ctx);
+ //shell.evaluate("src/test/groovy/j2ee/CreateData.groovy");
+
+ //shell.evaluate("src/main/groovy/ui/Console.groovy");
+ GroovyObject console = (GroovyObject) InvokerHelper.invokeConstructorOf("groovy.ui.Console", null);
+ console.setProperty("shell", shell);
+ console.invokeMethod("run", null);
+ /*
+ */
+ }
+ catch (Exception e) {
+ System.out.println("Caught: " + e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/groovy/model/MvcDemo.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/groovy/model/MvcDemo.groovy b/src/main/groovy/groovy/model/MvcDemo.groovy
new file mode 100644
index 0000000..dc31126
--- /dev/null
+++ b/src/main/groovy/groovy/model/MvcDemo.groovy
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.model
+
+import groovy.swing.SwingBuilder
+/**
+ *
+ */
+class MvcDemo {
+
+ def frame
+ def swing
+
+ void run() {
+ swing = new SwingBuilder()
+
+ def frame = swing.frame(title:'MVC Demo', location:[200,200], size:[300,200]) {
+ menuBar {
+ menu(text:'Help') {
+ menuItem() {
+ action(name:'About', closure:{ showAbout() })
+ }
+ }
+ }
+ panel {
+ borderLayout()
+ scrollPane(constraints:CENTER) {
+ table() {
+ tableModel(list:[ ['name':'James', 'location':'London'], ['name':'Bob', 'location':'Atlanta'] ]) {
+ propertyColumn(header:'Name', propertyName:'name')
+ propertyColumn(header:'Location', propertyName:'location')
+ }
+ }
+ }
+ }
+ }
+ frame.show()
+ }
+
+ void showAbout() {
+ def pane = swing.optionPane(message:'This demo shows how you can create UI models from simple MVC models')
+ def dialog = pane.createDialog(frame, 'About MVC Demo')
+ dialog.show()
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/groovy/swing/Demo.java
----------------------------------------------------------------------
diff --git a/src/main/groovy/groovy/swing/Demo.java b/src/main/groovy/groovy/swing/Demo.java
new file mode 100644
index 0000000..db997ca
--- /dev/null
+++ b/src/main/groovy/groovy/swing/Demo.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.swing;
+
+import groovy.lang.GroovyObject;
+import groovy.lang.GroovyCodeSource;
+import groovy.lang.GroovyClassLoader;
+import groovy.util.GroovyTestCase;
+
+import java.io.File;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+
+/**
+ *
+ * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
+ */
+public class Demo extends GroovyTestCase {
+ ClassLoader parentLoader = getClass().getClassLoader();
+ protected GroovyClassLoader loader =
+ (GroovyClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ return new GroovyClassLoader(parentLoader);
+ }
+ });
+
+ public static void main(String[] args) throws Exception {
+ Demo demo = new Demo();
+ GroovyObject object = demo.compile("src/examples/groovy/swing/SwingDemo.groovy");
+ object.invokeMethod("run", null);
+ }
+
+ protected GroovyObject compile(String fileName) throws Exception {
+ Class groovyClass = loader.parseClass(new GroovyCodeSource(new File(fileName)));
+ GroovyObject object = (GroovyObject) groovyClass.newInstance();
+ assertTrue(object != null);
+ return object;
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/groovy/swing/MyTableModel.java
----------------------------------------------------------------------
diff --git a/src/main/groovy/groovy/swing/MyTableModel.java b/src/main/groovy/groovy/swing/MyTableModel.java
new file mode 100644
index 0000000..fa28bf5
--- /dev/null
+++ b/src/main/groovy/groovy/swing/MyTableModel.java
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.swing;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.swing.table.AbstractTableModel;
+
+/**
+ * A sample table model
+ *
+ * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
+ */
+public class MyTableModel extends AbstractTableModel {
+
+ private static final Logger log = Logger.getLogger(MyTableModel.class.getName());
+
+ public MyTableModel() {
+ }
+
+ final String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" };
+ final Object[][] data = { { "Mary", "Campione", "Snowboarding", Integer.valueOf(5), new Boolean(false)}, {
+ "Alison", "Huml", "Rowing", Integer.valueOf(3), new Boolean(true)
+ }, {
+ "Kathy", "Walrath", "Chasing toddlers", Integer.valueOf(2), new Boolean(false)
+ }, {
+ "Mark", "Andrews", "Speed reading", Integer.valueOf(20), new Boolean(true)
+ }, {
+ "Angela", "Lih", "Teaching high school", Integer.valueOf(4), new Boolean(false)
+ }
+ };
+
+ public int getColumnCount() {
+ return columnNames.length;
+ }
+
+ public int getRowCount() {
+ return data.length;
+ }
+
+ public String getColumnName(int col) {
+ return columnNames[col];
+ }
+
+ public Object getValueAt(int row, int col) {
+ return data[row][col];
+ }
+
+ /*
+ * JTable uses this method to determine the default renderer/
+ * editor for each cell. If we didn't implement this method,
+ * then the last column would contain text ("true"/"false"),
+ * rather than a check box.
+ */
+ public Class getColumnClass(int c) {
+ return getValueAt(0, c).getClass();
+ }
+
+ /*
+ * Don't need to implement this method unless your table's
+ * editable.
+ */
+ public boolean isCellEditable(int row, int col) {
+ //Note that the data/cell address is constant,
+ //no matter where the cell appears onscreen.
+ if (col < 2) {
+ return false;
+ }
+ else {
+ return true;
+ }
+ }
+
+ /*
+ * Don't need to implement this method unless your table's
+ * data can change.
+ */
+ public void setValueAt(Object value, int row, int col) {
+ if (log.isLoggable(Level.FINE)) {
+ log.fine(
+ "Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")");
+ }
+
+ if (data[0][col] instanceof Integer && !(value instanceof Integer)) {
+ //With JFC/Swing 1.1 and JDK 1.2, we need to create
+ //an Integer from the value; otherwise, the column
+ //switches to contain Strings. Starting with v 1.3,
+ //the table automatically converts value to an Integer,
+ //so you only need the code in the 'else' part of this
+ //'if' block.
+ //XXX: See TableEditDemo.java for a better solution!!!
+ try {
+ data[row][col] = Integer.valueOf(value.toString());
+ fireTableCellUpdated(row, col);
+ }
+ catch (NumberFormatException e) {
+ log.log(Level.SEVERE, "The \"" + getColumnName(col) + "\" column accepts only integer values.");
+ }
+ }
+ else {
+ data[row][col] = value;
+ fireTableCellUpdated(row, col);
+ }
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/groovy/swing/SwingDemo.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/groovy/swing/SwingDemo.groovy b/src/main/groovy/groovy/swing/SwingDemo.groovy
new file mode 100644
index 0000000..6158032
--- /dev/null
+++ b/src/main/groovy/groovy/swing/SwingDemo.groovy
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.swing
+
+import java.awt.BorderLayout
+import javax.swing.BorderFactory
+import groovy.model.MvcDemo
+import groovy.swing.SwingBuilder
+
+class SwingDemo {
+
+ def swing = new SwingBuilder()
+ def frame
+
+ static void main(args) {
+ def demo = new SwingDemo()
+ demo.run()
+ }
+
+ void run() {
+ def frame = swing.frame(
+ title:'This is a Frame',
+ location:[100,100],
+ size:[800,400],
+ defaultCloseOperation:javax.swing.WindowConstants.EXIT_ON_CLOSE) {
+
+ menuBar {
+ menu(text:'File') {
+ menuItem() {
+ action(name:'New', closure:{ println("clicked on the new menu item!") })
+ }
+ menuItem() {
+ action(name:'Open', closure:{ println("clicked on the open menu item!") })
+ }
+ separator()
+ menuItem() {
+ action(name:'Save', enabled:false, closure:{ println("clicked on the Save menu item!") })
+ }
+ }
+ menu(text:'Demos') {
+ menuItem() {
+ action(name:'Simple TableModel Demo', closure:{ showGroovyTableDemo() })
+ }
+ menuItem() {
+ action(name:'MVC Demo', closure:{ showMVCDemo() })
+ }
+ menuItem() {
+ action(name:'TableLayout Demo', closure:{ showTableLayoutDemo() })
+ }
+ }
+ menu(text:'Help') {
+ menuItem() {
+ action(name:'About', closure:{ showAbout() })
+ }
+ }
+ }
+ splitPane {
+ panel(border:BorderFactory.createTitledBorder(BorderFactory.createLoweredBevelBorder(), 'titled border')) {
+ borderLayout()
+ vbox(constraints:NORTH) {
+ panel {
+ borderLayout()
+ label(text:'Name', constraints:WEST, toolTipText:'This is the name field')
+ textField(text:'James', constraints:CENTER, toolTipText:'Enter the name into this field')
+ }
+ panel {
+ borderLayout()
+ label(text:'Location', constraints:WEST, toolTipText:'This is the location field')
+ comboBox(items:['Atlanta', 'London', 'New York'], constraints:CENTER, toolTipText:'Choose the location into this field')
+ }
+ button(text:'Click Me', actionPerformed:{event -> println("closure fired with event: " + event) })
+ }
+ scrollPane(constraints:CENTER, border:BorderFactory.createRaisedBevelBorder()) {
+ textArea(text:'Some text goes here', toolTipText:'This is a large text area to type in text')
+ }
+ }
+ scrollPane {
+ table(model:new MyTableModel())
+ }
+ }
+ }
+ frame.show()
+ }
+
+ void showAbout() {
+ // this version doesn't auto-size & position the dialog
+ /*
+ def dialog = swing.dialog(owner:frame, title:'About GroovySwing') {
+ optionPane(message:'Welcome to the wonderful world of GroovySwing')
+ }
+ */
+ def pane = swing.optionPane(message:'Welcome to the wonderful world of GroovySwing')
+ def dialog = pane.createDialog(frame, 'About GroovySwing')
+ dialog.show()
+ }
+
+ void showGroovyTableDemo() {
+ def demo = new TableDemo()
+ demo.run()
+ }
+
+ void showMVCDemo() {
+ def demo = new MvcDemo()
+ demo.run()
+ }
+
+ void showTableLayoutDemo() {
+ def demo = new TableLayoutDemo()
+ demo.run()
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/groovy/swing/TableDemo.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/groovy/swing/TableDemo.groovy b/src/main/groovy/groovy/swing/TableDemo.groovy
new file mode 100644
index 0000000..abc2659
--- /dev/null
+++ b/src/main/groovy/groovy/swing/TableDemo.groovy
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.swing
+
+import java.awt.BorderLayout
+import javax.swing.BorderFactory
+import groovy.swing.SwingBuilder
+
+/**
+ * Demonstrates the use of the Groovy TableModels for viewing tables of any List of objects
+ */
+class TableDemo {
+
+ // properties
+ def frame
+ def swing
+
+ static void main(args) {
+ def demo = new TableDemo()
+ demo.run()
+ }
+
+ void run() {
+ swing = new SwingBuilder()
+
+ frame = swing.frame(title:'Groovy TableModel Demo', location:[200,200], size:[300,200]) {
+ menuBar {
+ menu(text:'Help') {
+ menuItem() {
+ action(name:'About', closure:{ showAbout() })
+ }
+ }
+ }
+ panel {
+ borderLayout()
+ scrollPane(constraints:CENTER) {
+ table() {
+ def model = [['name':'James', 'location':'London'], ['name':'Bob', 'location':'Atlanta'], ['name':'Geir', 'location':'New York']]
+
+ tableModel(list:model) {
+ closureColumn(header:'Name', read:{row -> return row.name})
+ closureColumn(header:'Location', read:{row -> return row.location})
+ }
+ }
+ }
+ }
+ }
+ frame.show()
+ }
+
+ void showAbout() {
+ def pane = swing.optionPane(message:'This demo shows how GroovySwing can use Groovy closures to create simple table models')
+ def dialog = pane.createDialog(frame, 'About GroovySwing')
+ dialog.show()
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/groovy/swing/TableLayoutDemo.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/groovy/swing/TableLayoutDemo.groovy b/src/main/groovy/groovy/swing/TableLayoutDemo.groovy
new file mode 100644
index 0000000..df2c223
--- /dev/null
+++ b/src/main/groovy/groovy/swing/TableLayoutDemo.groovy
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.swing
+
+import java.awt.BorderLayout
+import javax.swing.BorderFactory
+import groovy.swing.SwingBuilder
+
+/**
+ * Demonstrates the use of the table layout
+ */
+class TableLayoutDemo {
+
+ def frame
+ def swing
+
+ void run() {
+ swing = new SwingBuilder()
+
+ frame = swing.frame(title:'TableLayout Demo', location:[200,200], size:[300,200]) {
+ menuBar {
+ menu(text:'Help') {
+ menuItem() {
+ action(name:'About', closure:{ showAbout() })
+ }
+ }
+ }
+ tableLayout {
+ tr {
+ td {
+ label(text:'name')
+ }
+ td(colfill:true) {
+ textField(text:'James')
+ }
+ }
+ tr {
+ td {
+ label(text:'location')
+ }
+ td(colfill:true) {
+ textField(text:'London')
+ }
+ }
+ tr {
+ td(colspan:2, align:'center') {
+ button(text:'OK')
+ }
+ }
+ }
+ }
+ frame.show()
+ }
+
+ void showAbout() {
+ def pane = swing.optionPane(message:'This demo shows how you can use HTML style table layouts with Swing components')
+ def dialog = pane.createDialog(frame, 'About TableLayout Demo')
+ dialog.show()
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/groovy2d/paintingByNumbers.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/groovy2d/paintingByNumbers.groovy b/src/main/groovy/groovy2d/paintingByNumbers.groovy
new file mode 100644
index 0000000..5a69baf
--- /dev/null
+++ b/src/main/groovy/groovy2d/paintingByNumbers.groovy
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Simple patchwork graphics demo
+ * @author: Jeremy Rayner, changes by Dierk Koenig
+ */
+import javax.swing.WindowConstants as WC
+import groovy.swing.SwingBuilder
+
+def width = 500, height = 400, blockSize = 10
+def g = createGraphics(width, height)
+
+// main loop
+while (true) {
+ drawBlock(width, height, blockSize, g)
+}
+
+// random integer
+def rnd(upperBound){
+ (int)(Math.random() * upperBound)
+}
+
+// draw a random coloured square within bounds
+def drawBlock(w, h, b, g) {
+ def row = rnd(h / b)
+ def column = rnd(w / b)
+ def colour = new java.awt.Color(rnd(255),rnd(255),rnd(255))
+ g.color = colour
+ g.fillRect(column * b, row * b, b, b)
+}
+
+// create a new frame and clear screen
+def createGraphics(w, h) {
+ def frame = new SwingBuilder().frame(
+ title:'Painting by numbers',
+ location:[20,20],
+ size:[w, h],
+ defaultCloseOperation:WC.EXIT_ON_CLOSE
+ )
+ frame.show()
+
+ // obtain graphics context
+ def gfx = frame.graphics
+
+ // clear screen
+ gfx.color = java.awt.Color.BLACK
+ gfx.fillRect(0, 0, w, h)
+
+ return gfx
+}
http://git-wip-us.apache.org/repos/asf/groovy-examples/blob/3bd1e181/src/main/groovy/groovyShell/ArithmeticShell.groovy
----------------------------------------------------------------------
diff --git a/src/main/groovy/groovyShell/ArithmeticShell.groovy b/src/main/groovy/groovyShell/ArithmeticShell.groovy
new file mode 100644
index 0000000..d1a5659
--- /dev/null
+++ b/src/main/groovy/groovyShell/ArithmeticShell.groovy
@@ -0,0 +1,157 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import org.codehaus.groovy.control.CompilerConfiguration
+import org.codehaus.groovy.control.MultipleCompilationErrorsException
+import org.codehaus.groovy.control.customizers.ImportCustomizer
+import org.codehaus.groovy.control.customizers.SecureASTCustomizer
+import org.codehaus.groovy.control.messages.ExceptionMessage
+import static org.codehaus.groovy.syntax.Types.*
+import org.codehaus.groovy.ast.stmt.BlockStatement
+import org.codehaus.groovy.ast.stmt.ExpressionStatement
+import org.codehaus.groovy.ast.expr.BinaryExpression
+import org.codehaus.groovy.ast.expr.ConstantExpression
+import org.codehaus.groovy.ast.expr.MethodCallExpression
+import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
+import org.codehaus.groovy.ast.expr.ArgumentListExpression
+import org.codehaus.groovy.ast.expr.PropertyExpression
+import org.codehaus.groovy.ast.expr.UnaryMinusExpression
+import org.codehaus.groovy.ast.expr.UnaryPlusExpression
+import org.codehaus.groovy.ast.expr.PrefixExpression
+import org.codehaus.groovy.ast.expr.PostfixExpression
+import org.codehaus.groovy.ast.expr.TernaryExpression
+import org.codehaus.groovy.ast.expr.ElvisOperatorExpression
+import org.codehaus.groovy.ast.expr.BooleanExpression
+import org.codehaus.groovy.ast.expr.ClassExpression
+
+/**
+ * The arithmetic shell is similar to a GroovyShell in that it can evaluate text as
+ * code and return a result. It is not a subclass of GroovyShell because it does not widen
+ * the contract of GroovyShell, instead it narrows it. Using one of these shells like a
+ * GroovyShell would result in many runtime errors.
+ *
+ * @author Hamlet D'Arcy (hamletdrc@gmail.com)
+ * @author Guillaume Laforge
+ */
+class ArithmeticShell {
+
+ /**
+ * Compiles the text into a Groovy object and then executes it, returning the result.
+ * @param text
+ * the script to evaluate typed as a string
+ * @throws SecurityException
+ * most likely the script is doing something other than arithmetic
+ * @throws IllegalStateException
+ * if the script returns something other than a number
+ */
+ Number evaluate(String text) {
+ try {
+ final ImportCustomizer imports = new ImportCustomizer().addStaticStars('java.lang.Math') // add static import of java.lang.Math
+ final SecureASTCustomizer secure = new SecureASTCustomizer()
+ secure.with {
+ closuresAllowed = false
+ methodDefinitionAllowed = false
+
+ importsWhitelist = []
+ staticImportsWhitelist = []
+ staticStarImportsWhitelist = ['java.lang.Math'] // only java.lang.Math is allowed
+
+ tokensWhitelist = [
+ PLUS,
+ MINUS,
+ MULTIPLY,
+ DIVIDE,
+ MOD,
+ POWER,
+ PLUS_PLUS,
+ MINUS_MINUS,
+ COMPARE_EQUAL,
+ COMPARE_NOT_EQUAL,
+ COMPARE_LESS_THAN,
+ COMPARE_LESS_THAN_EQUAL,
+ COMPARE_GREATER_THAN,
+ COMPARE_GREATER_THAN_EQUAL,
+ ].asImmutable()
+
+ constantTypesClassesWhiteList = [
+ Integer,
+ Float,
+ Long,
+ Double,
+ BigDecimal,
+ Integer.TYPE,
+ Long.TYPE,
+ Float.TYPE,
+ Double.TYPE
+ ].asImmutable()
+
+ receiversClassesWhiteList = [
+ Math,
+ Integer,
+ Float,
+ Double,
+ Long,
+ BigDecimal
+ ].asImmutable()
+
+ statementsWhitelist = [
+ BlockStatement,
+ ExpressionStatement
+ ].asImmutable()
+
+ expressionsWhitelist = [
+ BinaryExpression,
+ ConstantExpression,
+ MethodCallExpression,
+ StaticMethodCallExpression,
+ ArgumentListExpression,
+ PropertyExpression,
+ UnaryMinusExpression,
+ UnaryPlusExpression,
+ PrefixExpression,
+ PostfixExpression,
+ TernaryExpression,
+ ElvisOperatorExpression,
+ BooleanExpression,
+ // ClassExpression needed for processing of MethodCallExpression, PropertyExpression
+ // and StaticMethodCallExpression
+ ClassExpression
+ ].asImmutable()
+
+ }
+ CompilerConfiguration config = new CompilerConfiguration()
+ config.addCompilationCustomizers(imports, secure)
+ GroovyClassLoader loader = new GroovyClassLoader(this.class.classLoader, config)
+ Class clazz = loader.parseClass(text)
+ Script script = (Script) clazz.newInstance();
+ Object result = script.run()
+ if (!(result instanceof Number)) throw new IllegalStateException("Script returned a non-number: $result");
+ return (Number) result
+ } catch (SecurityException ex) {
+ throw new SecurityException("Could not evaluate script: $text", ex)
+ } catch (MultipleCompilationErrorsException mce) {
+ //this allows compilation errors to be seen by the user
+ mce.errorCollector.errors.each {
+ if (it instanceof ExceptionMessage && it.cause instanceof SecurityException) {
+ throw it.cause
+ }
+ }
+ throw mce
+ }
+ }
+}