You are on page 1of 105

Introduction To JudoScript

A Powerful, Intuitive,
All-In-One Scripting Tool

James J.B. Huang

Copyright 2005 James J.B. Huang 1


Perlis's Postulate

The computing field is always


in need of new clichés.

Copyright 2005 James J.B. Huang 2


About the Author
„ Academic experience
„ Industry experience
„ Invented two language tools:
„ JudoScript – an all-in-one scripting tool
http://www.judoscript.com/judo.html
„ Jamaica – the JVM Macro Assembly Language
http://www.judoscript.com/jamaica.html

Copyright 2005 James J.B. Huang 3


How to Use The Slides
„ The slides here can be used for presentation
and/or learning JudoScript.
„ Presentations won't cover all slides.
„ The first part provides one way of understanding
JudoScript, its idea and vision.
„ The second part lists most of the key language
features. You may pick and view whatever you
are interested in.
„ The last part presents some general language
discussion. It may be interesting but is not
important.
Copyright 2005 James J.B. Huang 4
About This Presentation
I. Vision and JudoScript Design
II. JudoScript Strengths
III. Language Design Discussion

Copyright 2005 James J.B. Huang 5


I. Vision and JudoScript Design

I. Vision and JudoScript Design


II. JudoScript Strengths
III. Language Design Discussion

Copyright 2005 James J.B. Huang 6


What's the Problem?
„ We use many scripting tools for a task: e.g.
Ant, shell scripts, Perl/Python, SQL scripts,
even Java or C programs.
„ Common belief: "different tools have
different strengths for the job."
„ BUT, why those strengths have to scatter
across different scripting tools in the 21st
century?
Copyright 2005 James J.B. Huang 7
The Vision

Imagine

ONE SCRIPTING TOOL


with all those strengths and beyond …

Copyright 2005 James J.B. Huang 8


Benefits of One-Tool-For-All
1. Single mind — synergy
„ No context switching from tool to tool
„ No data passing from tool to tool
2. 1 + 1 > 2 — Gestalt
3. Single install and configuration
4. Productivity
5. Maintainability
6. Lower stress level

Copyright 2005 James J.B. Huang 9


Vocabulary: synergy
Mutually advantageous conjunction or
compatibility of distinct business participants
or elements.
— Merrian-Webster

"Coherence."
— James Huang

Copyright 2005 James J.B. Huang 10


Vocabulary: Gestalt
Something so integrated as to constitute a
functional unit with properties not derivable
by summation of its parts.
— Merrian-Webster

"Chemistry."
— James Huang

Copyright 2005 James J.B. Huang 11


Is this Vision Feasible?

POSITIVE!

Because we know what we need.

Copyright 2005 James J.B. Huang 12


What Do We Need Today?
„ RDBMS processing and reporting
„ Common data formats, e.g. SGML, XML
„ Work with file systems and archives
such as zip, tar and gzip
„ Run executables in various ways
„ Network clients, e.g. e-mail, WSDL,
HTTP, etc.
(to be continued)

Copyright 2005 James J.B. Huang 13


What Do We Need Today? cont'd

„ Script popular resources such as Ant Tasks and


Hibernate
„ Create and use Graphical User Interfaces
„ Script Java resources
„ Script Windows resources including
COM/ActiveX
„ Algorithmic and O-O programming
„ Having all these together!

Copyright 2005 James J.B. Huang 14


The Ambitions
„ JudoScript is an attempt for such an all-
in-one scripting tool in the 21st century.
„ It should excel in these strengths, including
programming.
„ Some features are really specialized tools,
such as a universal RDBMS scripting client,
SGML scraper, files and archives tools, etc.
„ It shall be as easy and intuitive as possible.

Copyright 2005 James J.B. Huang 15


Is JudoScript the 1st Such Attempt?
„ Perl was intended for similar goals.
„ Perl [V1:V5]=>[1987, 88, 89, 91, 94].
„ The idea behind Perl: "Perl is designed to make
the easy jobs easy, without making the hard jobs
impossible."
„ "And what are these 'easy jobs'? The ones you do
everyday. You want a language that makes it easy to manipulate
numbers and text, files and directories, computers and networks, and
especially programs." Programming Perl Edition 2 (Covers
Perl 5), ISBN: 1-56592-149-6

Copyright 2005 James J.B. Huang 16


The Perl 6 Vision
"The vision for Perl 6 is more than simply a rewrite
of Perl 5. By separating the parsing from the
compilation and the runtime, we're opening the
doors for multiple languages to cooperate. You'll be
able to write your program in Perl 6, Perl 5, TCL,
Python, or any other language that there's a parser
written for. Interchangeable runtime engines let you
interpret your byte-code or convert it to something
else (e.g., Java, C, or even back to Perl)."

Copyright 2005 James J.B. Huang 17


The JudoScript Design Goals
1. Useful, powerful
2. Easy, intuitive
3. Contemporary
4. Comprehensive, progressive

Copyright 2005 James J.B. Huang 18


High-Level Requirements
1. Provide all the mentioned strengths
2. Easy to read, write and maintain
3. NOT to re-invent programming ̶ uses
JavaScript as its base syntax
4. Strong programming support

Copyright 2005 James J.B. Huang 19


Language Features (Domain Support)
„ Powerful algorithmic and „ Hibernate scripting
O-O programming/scripting „ Windows COM scripting
„ Potent Java scripting „ WSDL scripting
„ SQL scripting „ Internet clients
„ SGML and XML scripting „ Send mail
„ I/O and logging „ GUI scripting
„ File system and archive „ Ant task scripting
„ Run executables „ Other features

These are language features, not library features.


Copyright 2005 James J.B. Huang 20
Some Quick Code Samples [I]
copy ‘*.java’ listFiles
in ‘src.jar’ ‘*.java,*.properties’
recursive in ‘src.jar’
to ‘c:/tmp/src’; recursive; // result in $_

copy ‘*.java’ do ‘com/judoscript/RT.java’


except ‘*/save/*’ in ‘src.jar’ as lines
in ‘c:/tmp/src’ {
recursive lineNo = loopIndex()+1;
into ‘src.jar’; println lineNo:>3,‘: ‘,$_;
}

Copyright 2005 James J.B. Huang 21


Some Quick Code Samples [II]
mail::send do 'index.html' as sgml {
from: ‘a@x.com’ <a>: println $_.href;
to: ‘c@y.com, d@y.com’ <img>: println $_.src;
cc: ‘e@z.com’ }
subject: ‘Test test’
attach: ‘judo.jar, src.jar’ do $$local as xml {
body: [[* <book>: println $_.author;
This is a test! </book>: println '-------';
*]]; <title>TEXT: println $_;
}
htmlBody: [[*
EndScript ===================
This is a
<book author="Dan Brown">
<u>test</u>!
<title>Da Vinci Code</title>
*]]; </book>
Copyright 2005 James J.B. Huang 22
Some Quick Code Samples [III]
db::sql {
INSERT INTO emp(num,name) VALUES(101,'James');
INSERT INTO emp(num,name) VALUES(102,'Daniel');
}
db::batch {
INSERT INTO emp(num,name) VALUES(103,'Lisa');
INSERT INTO emp(num,name) VALUES(104,'Mary');
}
db::query qry:
SELECT name, bday FROM emp WHERE bday>?
; with @1:date = Date(2005,1,1);
while qry.next() {
println qry.name:<20, qry[2].fmtDate(‘yyyy’);
}
Copyright 2005 James J.B. Huang 23
Targeted Uses
„ OS shell functions
„ Universal RDBMS client and reporting
„ Multiple format text processors
„ Java, COM and WSDL glue language
„ Software build, package, test and deploy
„ Internet clients
„ Documentation generator
„ Java-based GUI toolkit
„ General-purpose programming/scripting language
Copyright 2005 James J.B. Huang 24
Components of JudoScript
„ JudoScript consists of 3 components:
„ Syntactic support
„ Built-in data structures and object types
„ System functions
„ Each functional feature may involve one
or more of these components.

Copyright 2005 James J.B. Huang 25


I. Vision and JudoScript Design

I. Vision and JudoScript Design


II. JudoScript Strengths
III. Language Design Discussion

Copyright 2005 James J.B. Huang 26


II. JudoScript Strengths

I. Vision and JudoScript Design


II. JudoScript Strengths
III. Language Design Discussion

Copyright 2005 James J.B. Huang 27


JudoScript Domain Support
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 28


Topic: SQL Scripting
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 29


[sql] SQL Scripting
„ Run SQL statements in groups/batches.
„ Run parameterized SQL with easy
parameter binding.
„ Run dynamically constructed SQL.
„ Invoke stored procedures.
„ Heuristic JDBC connections.
„ Multiple simultaneous connections.

Copyright 2005 James J.B. Huang 30


[sql] Run SQL Statements
db::connect 'jdbc:mysql://localhost/db','user','pass';
db::sql {
INSERT INTO emp(num,name) VALUES(104, 'Monier');
INSERT INTO emp(num,name) VALUES(105, 'Tan');
}
db::batch {
INSERT INTO emp(num,name) VALUES(106, 'Lin');
INSERT INTO emp(num,name) VALUES(107, 'Patel');
}
db::disconnect;

Copyright 2005 James J.B. Huang 31


[sql] Run Parameterized SQL
db::connect dbUrl, dbUser, dbPass;
db::prepare upd:
INSERT INTO emp(num,name) VALUES(:num,:name);
do $$local as lines {
var data = $_.csv('|');
db::sql upd with num:int=data[0], name=data[1];
}
db::disconnect;
EndScript ======================================
101|James
102|Daniel
103|Linda

Copyright 2005 James J.B. Huang 32


[sql] Run Constructed SQL
names = ['James', 'Daniel', 'Linda'];

db::connect dbUrl, dbUser, dbPass;


db::query qry:
SELECT num, name FROM emp WHERE name IN
((* names.concat( ',', {x|return "'${x}'";} ) *));
// => WHERE name IN ('James','Daniel','Linda')
while qry.next() {
println qry.num, ' ', qry.name;
}
db::disconnect;

Copyright 2005 James J.B. Huang 33


[sql] Call Stored Procedure
db::connect anOracleUrl, dbUser, dbPass;
db::any [[*
CREATE OR REPLACE PROCEDURE test_proc
(p_io IN OUT NUMBER, p_i IN VARCHAR, p_o OUT VARCHAR)
AS BEGIN
p_o := p_i;
IF p_io IS NOT NULL THEN
p_io := p_io + 1;
ELSE
p_io := -1000;
END IF;
END;
*]]; // to be continued …

Copyright 2005 James J.B. Huang 34


[sql] Call Stored Procedure cont'd

db::prepareCall:
{ call test_proc( :pIO, :pIn, :pOut) };

x = null;
y = 'abcd';
db::sql with @pIO :int <=> x,
@pIn :varchar = y,
@pOut:varchar => z;
println 'x = ', x;
println 'z = ', z;

db::disconnect;

Copyright 2005 James J.B. Huang 35


Topic: SGML and XML Scripting
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 36


[sgml] SGML and XML Scripting
„ Event-driven statements for processing
SGML, XML and JSP/ASP pages:

do src as sgml { … }
do src as xml { … }
do src as jsp { … }

Copyright 2005 James J.B. Huang 37


[sgml] SGML/HTML Scraping
do 'http://www.yahoo.com' as sgml
{
<a>: if ($_.href) println '<a>: ', $_.href;
:TEXT: println 'TEXT: length=', $_.length();
<>: println 'Tag: ', $_.getName();
<!>: println 'Special Tag: ', $_;
}

Copyright 2005 James J.B. Huang 38


[sgml] An Internet Robot
urls = Set[ 'http://yahoo.com' ];
visited = Set[];
while urls.size()>0 {
var url = urls.getOne();
if visited.contains(url) {
urls.remove(url);
} else {
visited.add(url);
do url as sgml {
<a>: if($_.href) urls.add($_.href);
<iframe>: if($_.src) urls.add($_.src);
}
}
}
Copyright 2005 James J.B. Huang 39
[sgml] XML Scripting: Easy SAX
do $$local as xml {
<book>: println 'Book by: ', $_.author;
</book>: println '-----------------';
<title>TEXT: println 'Titlte: ', $_;
}
EndScript =======================================

<book author="Dan Brown">


<title>The Da Vinci Code</title>
</book>

Copyright 2005 James J.B. Huang 40


Topic: F.S. and Archives
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 41


[fs] F.S. and Archives
„ The versatile copy command.
„ The powerful listFiles command.
„ Directory commands: mkdir, rmdir, cd,
pushd, popd.
„ The String object is also used to represent
file and directory paths.

Copyright 2005 James J.B. Huang 42


[fs] Copy Files between
Directories and/or Archives
copy '*.java, *.properties' except '*/save/*, *~'
in 'c:/src' recursive to 'c:/backup/src';

copy '*.java, *.properties' except '*/save/*, *~'


in 'c:/src' recursive into 'c:/backup.tar.gz';

copy '*.java, *.properties' except '*/save/*, *~'


in 'c:/src' recursive into 'c:/backup.zip';

copy '*' in 'c:/backup.zip' recursive


to 'c:/src' Echo;

Copyright 2005 James J.B. Huang 43


[fs] Copy Many Directory Trees
into One Archive
zipName =
'c:/backup-' + Date().fmtDate('yyyyMMdd') + '.zip';

arch = createZip(zipName);
copy '*.java, *.properties' except '*/save/*, *~'
in 'c:/src' recursive into arch under 'src';
copy '*' except '*/save/*'
in 'e:/doc' recursive into arch under 'doc';
//copy more trees ...
arch.close();

Copyright 2005 James J.B. Huang 44


[fs] Create Executable Jar
copy '*.java, *.properties' in 'c:/temp/classes/' recursive
into 'c:/judo.jar' store manifest
[[*
Manifest-Version: 1.0
Main-Class: judo
Created-By: James Jianbo Huang (c) 2001-(* #year *)
*]];

Copyright 2005 James J.B. Huang 45


[fs] The listFiles Command
„ It returns the result in $_.
„ It can return files and directories, or return
stats about them.
„ It allows you to perform any actions on
files and directories.

Copyright 2005 James J.B. Huang 46


[fs] Find Files
ls 'c:/src/com/judoscript/*.java' recursive;

listFiles 'com/judoscript/*.java' except '*/save/*'


in 'c:/src' recursive
order by date // size/name/extension
limit 500;
for f in $_ { println f; }

listFiles 'com/judoscript/*.java'
in 'c:/src' recursive as tree;
for f in $_.bfsAllNodes() { println f.path; }

Copyright 2005 James J.B. Huang 47


[fs] Get File Stats
listFiles '*.java' recursive size;

listFiles '*.java' recursive count;

listFiles '*.java' recursive lines;

listFiles '*.java' recursive words;

listFiles '*.java' in 'src.zip' recursive


compressedSize;

Copyright 2005 James J.B. Huang 48


[fs] Operate on Files
listFiles '*.java' setFileTime;
listFiles '*.java' setFileTime Date(2002,4,5,11,30);
listFiles '*.java' setReadOnly;

listFiles '*.java' // arbitrary shell operation


exec isWindows() ? 'attrib +r $_' : 'chmod a+r $_';

listFiles '*.java' { // arbitrary operation


if getFileAsString($_).contains('Judo') {
println 'File $_ contains "Judo".';
}
}

Copyright 2005 James J.B. Huang 49


Topic: I/O and Logging
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 50


[io] The Print Family Commands
„ The print, println and flush
commands.
„ Can write text to stdout, stderr, log
and any text files and output streams.
„ Easy and powerful formatting: alignment
and repeating options.

Copyright 2005 James J.B. Huang 51


[io] Printing to different targets
println 'Hello, world!';
println<out> 'Hello, world!';
println<err> 'Well, shit happens.';
println<log> 'Oh yeah!';

f = openTextFile('foo.txt', 'w');
println<f> 'Lah lah lah lah laah lah.';
f.close();

sw = createStringWriter();
for x from 1 to 10 { println<sw> '#', x, ' '; };
println sw.toString();

Copyright 2005 James J.B. Huang 52


[io] Printing with formatting
println 'abcdefg':<9, 123:>5, 123.45:*5.3, '*'{5};

name = 'James Huang';


println name, nl, '-'{name.length()};

// print a text file with line numbers:


do 'judo.java' as lines {
println loopIndex()+1:>3, ': ', $_;
}

Copyright 2005 James J.B. Huang 53


Topic: Run Executables
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 54


[exec] The exec Command
„ Supports sophisticated command-lines, including
piping and redirections.
„ Can take multiple lines for readability.
„ Can specify the starting directory and
environment variables.
„ Run asynchronously and synchronously, and
return the executable exit value.
„ Can pump input to and read output from the
executable, simultaneously or individually.

Copyright 2005 James J.B. Huang 55


[exec] Run javac
exec /bg 'javac *.java';

exec 'javac *.java'


with CLASSPATH='${CLASSPATH}${:}${lib}/mylibs.jar';

exec [[* javac ${src}/*.java


${src}/com/judoscript/*.java
${src}/com/judoscript/util/*.java
*]]
from '${JDK13HOME}/bin/';

Copyright 2005 James J.B. Huang 56


[exec] Command-lines
exec 'java test.Echo < out_err.judo > alfa';

prg = 'java test.Echo';


exec '${prg} < tee.judo > a.dump | ${prg}';

Copyright 2005 James J.B. Huang 57


[exec] Interact with executables
exec <a> 'java test.Hello';
println 'Return status code: ', a;

exec /needSystemIn 'java test.ToLower'


output {
while (line=readPipe()) != eof {
println ' #', loopIndex()+1, ': ', line;
}
}

println `dir *.java`;

for x in ``dir *.java`` { println x; }

Copyright 2005 James J.B. Huang 58


[exec] Pump and Read Executable
exec 'java test.ToLower | java test.Echo'
input {
println <pipe> 'Cheers!';
}

exec 'java test.ToLower | java test.Echo'


input { // feed input to the cmdline
println <pipe> 'Hello, World!';
}
output { // read output from the cmdline
while (line = readPipe()) != eof {
println 'Line #', loopIndex()+1, ': ', line;
}
}

Copyright 2005 James J.B. Huang 59


Topic: Java Scripting
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 60


[java] Use and Extend Java
„ Use all public Java classes and arrays.
„ Can extend Java classes, including
anonymous Java adapters.
„ Can alias Java static methods into
JudoScript functions.
„ Field accesses for Java getter/setters.
„ Consistent syntactic sugar for major Java
container data structures.

Copyright 2005 James J.B. Huang 61


[java] Create/Use Java Objects
list = new java::ArrayList;
list.add('abc'); list.add(1); list.add(2.5);
for x in list { println x; }

Int = new java::Integer(1);


println Int.class.name; // = Int.getClass().getName()

import javax.swing.*;
frm = new java::JFrame('Simplest GUI');
frm.setVisible(true);

Copyright 2005 James J.B. Huang 62


[java] Create/Use Java Arrays
arr = new java::int[]{ 1, 2, 3 };
for x in arr { println x; }
arr = new java::byte[3];
arr[0]=2; arr[1]=4; arr[2]=6;

arr = new java::String[]{ 'aa', 'bb', 'cc' };

import javax.swing.*;
arr = new java::Button[5];
arr[0] = new java::Button('button 1');
arr[1] = new java::Button('button 2');

Copyright 2005 James J.B. Huang 63


[java] Use Java Static Members
println (java::System).currentTimeMillis();
println System::currentTimeMillis();
cls = java::System;
cls.out.println('Hello, World!');

import java.sql.Types;
for sqlType in [ 'BIT', 'TINYINT', 'SMALLINT' ] {
println sqlType, ' = ', Types.(sqlType);
}

function pickTrash for System::gc; // aliasing


pickTrash();
Copyright 2005 James J.B. Huang 64
[java] Extend Classes/Interfaces
import javax.swing.JButton;
class MyButton extends java::JButton {
boolean isSubmit;
constructor title {
super(title);
isSubmit = false;
}
void setText(String title) {
super.setText(title);
isSubmit = title.equalsIgnoreCase('submit');
}
}

Copyright 2005 James J.B. Huang 65


[java] Java Adapters
import java.awt.event.*;

listner = new java::ActionListner, textListener {


void actionPerformed(ActionEvent ae) {
println 'Action done: ', ae.getActionCommand();
}
void textValueChanged(TextEvent te) {
println 'Text changed: ', te.paramString();
}
}

Copyright 2005 James J.B. Huang 66


Topic: Programming
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 67


[prog] General Programming
„ Superset of JavaScript programming.
„ Genuine O-O programming support.
„ Very powerful data structures.
„ Thread programming.
„ More intuitive syntactic sugar.
We have seen programming in various demos, so here we
just show very few specific programming examples.

Copyright 2005 James J.B. Huang 68


[prog] String
„ String has many methods; its collection of
methods is a union of the following:
„ java.lang.String
„ JavaScript String object
„ StringUtils and StringEscapeUtils in
org.apache.commons.lang
„ JudoScript's own
„ Strings also represent files and URLs.
Copyright 2005 James J.B. Huang 69
[prog] Data Structures: the Source of
Programming Power
„ More built-in data structures
„ More methods on these data structures
„ Built-in data types and data structures:
„ Integer, Float, String and Date/time
„ Object, OrderedMap, SortedMap
„ Array, LinkedList, Set
„ TableData
„ TreeNode
„ Stack, Queue
„ Other built-in domain objects
Copyright 2005 James J.B. Huang 70
[prog] Array, LinkedList, Set
arr = [ 1, 'abc', Date(2001,11,16) ];
list = LinkedList[ 1, 'abc', Date(2001,11,16) ];
set = Set[ 1, 'abc', Date(2001,11,16) ];
for x in arr { println x; }

arr = [ 4, 2, 7, 5, 10, 9 ];
println 'Length: ', arr.length();
println 'Sorted: ', arr.sortAsNumber();
println 'CSV: ', arr.concat(',');
println '[2,3]: ', arr.subarray(2,3);
println 'Average: ', arr.average();

Copyright 2005 James J.B. Huang 71


[prog] Custom Sorting
a = [ '1.2','3','3.9','1.10','1.2.1','2.3','3' ];
for x in a.sort(&my_comparator) { println x; }
// Result: 1.10, 1.2, 1.2.1, 2.3, 3, 3, 3.9

function my_comparator(lhs, rhs) {


la = lhs.csv('.'); ra = rhs.csv('.');
lali = la.lastIndex(); rali = ra.lastIndex();
for i from 0 to min(lali,rali) {
if (la[i].int()<ra[i].int()) return -1;
if (la[i].int()>ra[i].int()) return 1;
}
if (lali==rali) return 0;
return lali>rali;
}

Copyright 2005 James J.B. Huang 72


[prog] Object and OrderedMap
obj = new Object(name='James', bday=Date(2001,11,16));
obj = { name='James', bday=Date(2001,11,16) };

omap = OrderedMap{ name='James', sex='M' };


omap = new OrderedMap(name='James', sex='M');

println 'name => ', obj.name;


println 'bday => ', obj.bday.fmtDate('yyyy-MM-dd');
for key in obj {
println key, ' => ', obj.(key);
}
for key in obj.keysSortByValues() {
println key, ' => ', obj.(key);
}
Copyright 2005 James J.B. Huang 73
[prog] TableData
a = new TableData('Name', 'Type', 'Birthday');
a.add('Java', 'System', Date(1996,5,23))
.add('JudoScript', 'Scripting', Date(2001,11,16));

println 'Language | Type | Birthday';


println '----------+-----------+---------';
printTable a for
column(0):<10!, '| ',
column('Type'):<10!, '| ',
column('Birthday').fmtDate('yyyy-MM');

for lang in a.getColumn('Name') {


println lang;
}
Copyright 2005 James J.B. Huang 74
[prog] Thread Programming
const #docroot = ${TMPROOT};

// multi-threaded HTTP server:


thread httpHandler(con) { con.serveFile(#docroot); }
ss = startServer(8088);
while {
start thread httpHandler(acceptHttp(ss));
}

// single-threaded HTTP server:


ss = startServer(8088);
while {
acceptHttp(ss).serveFile(#docroot);
}
Copyright 2005 James J.B. Huang 75
Topic: Hibernate Scripting
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 76


[hib] Hibernate Scripting
„ Hibernate scripting allows easy use of
persistent objects with the Hibernate ORM
framework.
„ Provides syntax similar to JDBC scripting
for querying and operations.

Copyright 2005 James J.B. Huang 77


[hib] Persist Objects
hib::setup (
hibernate.connection.url
= 'jdbc:mysql://localhost/test',
hibernate.connection.username = 'james',
hibernate.connection.password = 'james',
hibernate.hbm2ddl.auto = 'update',
judoscript.echo = true
)
TestSimpleTypes // class name(s)
;
x = new java::TestSimpleTypes(10.5, 'abc', Date());
/* Persist: */ hib::save(x);
/* Update: */ x.theFloat = 100.8; hib::update(x);
/* Delete: */ hib::delete x;
Copyright 2005 James J.B. Huang 78
[hib] Hibernate Query/Delete
hib::query qry:
select o.id, o.theFloat, o.theString
from TestSimpleTypes o
where o.id>:startIdx and o.id<:endIdx
; with startIdx:Long=9, endIdx:Long=15;
for o in qry { println o; }

hib::delete:
from TestSimpleTypes o
where o.id>:startIdx and o.id<:endIdx
; with startIdx:Long=11, endIdx:Long=13;

Copyright 2005 James J.B. Huang 79


Topic: WSDL Scripting
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 80


[wsdl] WSDL Scripting
„ WSDL scripting is extremely simple: obtain
the WSDL handle and use it like any object.
„ JudoScript marshals any object values,
including JudoScript Object,
java.util.Map and Java class, to WSDL
object types.

Copyright 2005 James J.B. Huang 81


[wsdl] Test with Echo Service
ws = wsdl::'http://testhost/axis/services/echo?wsdl';

println ws.echoStringArray( [ 'o', 'p', 'q' ] );


println ws.echoIntegerArray( [ 10, 20, 30 ] );

mapArray = [ { alfa=1 }, { beta='xyz' } ];


println ws.echoMapArray( mapArray );

Copyright 2005 James J.B. Huang 82


Topic: MS COM Scripting
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 83


[com] Scripting ActiveX/COM
„ ActiveX/COM scripting is extremely simple:
obtain the COM and use it like any object.

Copyright 2005 James J.B. Huang 84


[com] Use VBScript, XMLDOM
sc = new com::ScriptControl;
sc.Language = 'VBScript';
for i from 0 to 9 {
println sc.Eval('${i}+1001');
}

xmldoc = new com::Microsoft.XMLDOM;


xmldoc.async = false;
xmldoc.load('test.xml');
children = xmldoc.documentElement.childNodes;
for i from 0 to children.length-1 {
c = children['item',i];
println c, ' ', c.text;
}
Copyright 2005 James J.B. Huang 85
[com] Use Excel
xl = new com::Excel.Application;
xl.Visible = true;

workbooks = xl.Workbooks;
workbook = workbooks.Add;
sheet = workbook.ActiveSheet;
a1 = sheet['Range', 'A1'];
a2 = sheet['Range', 'A2'];
a1.Value = 123.456;
a2.Formula = '=A1*2';
println 'a1: ', a1.Value, ' a2: ', a2.Value;

workbook.Close();
xl.Quit();
Copyright 2005 James J.B. Huang 86
Topic: Internet Clients
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 87


[net] HTTP Client
h = httpGet('http://www.yahoo.com');

// set header before send:


h.('User-Agent') =
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';

// get headers and cookies (connect first):


for x in h.getAllHeaders() { println x, ': ', h.(x); }
for x in h.getCookies() { println x; }

Copyright 2005 James J.B. Huang 88


Topic: Send Mail
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 89


[mail] Send Mail Made E-Z!
mail::send
from: ‘a@x.com’
to: ‘c@y.com, d@y.com’
cc: ‘e@z.com’
subject: ‘Test test’
attach: ‘${ship}/judo.jar, ${ship}/src.jar’
body: [[*
This is a test!
*]];
htmlBody: [[*
This is a <u>test</u>!
*]];

Copyright 2005 James J.B. Huang 90


Topic: GUI Scripting
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 91


[gui] Java GUI Scripting
import javax.swing.*;

frame = new java::JFrame('Simplest GUI');


frame.setVisible(true);

gui::events {
<frame : Window : windowClosing>: exit 0;
}

Copyright 2005 James J.B. Huang 92


Topic: Ant Task Scripting
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 93


[ant] Why Script Ant Tasks
„ Ant tasks comprise a unique form of useful
library of practical utilities.
„ JudoScript allows you to cut-n-paste Ant
task code and script them immediately.

Copyright 2005 James J.B. Huang 94


[ant] Script Ant Tasks
a = 'ants';
anttask::<echo message="Hello, ${a}!"/>
anttask::<echo><![CDATA[ Hello, more ${a}! ]]></echo>

fname = '/usr/bin/judo';
anttask::<basename property="b.name" file="${fname}"/>
println 'Base name: ', ${b.name};

anttask::<taskdef name="judo"
classname="com.judoscript.AntJudoScriptTask" />
anttask::<judo>
println 'Judo-in-Ant-in-Judo, a.k.a. AntBurger!';
</judo>

Copyright 2005 James J.B. Huang 95


JudoScript Domain Support
[sql] SQL scripting [hib] Hibernate scripting
[sgml] SGML/XML scripting [wsdl] WSDL scripting
[fs] F.S. and archives [com] MS COM scripting
[io] I/O and logging [net] Internet clients
[exec] Run executables [mail] Send mail
[java] Potent Java scripting [gui] GUI scripting
[prog] Powerful algorithmic and [ant] Ant task scripting
O-O programming [misc] Other features

Copyright 2005 James J.B. Huang 96


II. JudoScript Strength

I. Vision and JudoScript Design


II. JudoScript Strength
III. Language Design Discussion

Copyright 2005 James J.B. Huang 97


III. Language Design Discussion

I. Vision and JudoScript Design


II. JudoScript Strength
III. Language Design Discussion

Copyright 2005 James J.B. Huang 98


Programming Language Use Cases

Essential Programming
Common Utility
Programming Languages
Use Cases
Use Cases
Extension JudoScript
Mechanism (A Useable Language)

“Cute”
Programming Scripting Real-World
Use Cases Languages Use Cases

Copyright 2005 James J.B. Huang 99


Issues with API Programming
„ Verbosity
„ Duplicated Efforts
„ Leakage-of-concerns
„ E.g. Use java.util.zip package.
„ E.g. Use javax.mail package.
„ The opposite of API programming is
declarative programming.

Copyright 2005 James J.B. Huang 100


Declarative vs API Programming
„ Declarative programming focuses on
specifying the solution itself
„ API programming focuses on the
implementation of a solution
„ Scripting tools are to solve real-world
problems – solution should be the focal
point!

Copyright 2005 James J.B. Huang 101


JudoScript Summary
„ Trinity of JudoScript
„ Algorithmic and O-O programming
„ Java scripting
„ Domain scripting
„ Practically Use Java Platform
„ Script Intuitively, Effectively, Efficiently
„ JudoScript is the first all-in-one tool!

Copyright 2005 James J.B. Huang 102


III. Language Design Discussion

I. Vision and JudoScript Design


II. JudoScript Strength
III. Language Design Discussion

Copyright 2005 James J.B. Huang 103


To Run JudoScript ̶
1. Download judo.jar.zip from:
http://www.judoscript.com/download.html
2. Unzip and add it to your CLASSPATH for Java.
3. To run a script:
% java judo test.judo -opt=1 param1 param2
4. To run code from the command-line:
% java judo -x "println versionInfo()"
% alias jx="java judo -x"
% jx ". (1234).fmtHex()"
% jx ". 1.075 ** 30"
% jx ". Date(2008,9,3).dayOfWeek"

Copyright 2005 James J.B. Huang 104


To Learn More about JudoScript ̶
1. This presentation is listed on:
http://www.judoscript.com/tut_pres.html
2. The examples library is the best source to get started
and it covers all areas!
http://www.judoscript.com/examples/
3. The on-going book and other articles:
http://www.judoscript.com/articles/
4. The Language Reference (somewhat out-of-date):
http://www.judoscript.com/ref/
5. The whole JudoScript site: http://www.judoscript.com

Copyright 2005 James J.B. Huang 105

You might also like