Archive

Archive for the ‘Software Development’ Category

SimpleScript – Simple Examples

July 22nd, 2010 nawaman No comments

In the previous post, I’ve show you how to install SimpleScript. Now, let begin script some Java SS.

Table of Contents

1: Hello World!!!
2: Java Expressions and Statements
3: Java Libraries
4: Command-Line Arguments
5: Let’s make a useful program

1: Hello World!!!

Introducing a programming language or environment cannot be completed without this program – the Hello World!!!
se-01-Hello-World.ss

// @Java:
System.out.println("Hello World!!!");

Executed with:

ss --run se-01-Hello-World.ss

Result:

Hello World!!!

This example is very self-explanatory especially for those Java programmers. So let’s go on …. :-p

2: Java Expressions and Statements

This example aims to demonstrate that Java expressions and statements can be used in SimpleScript.
se-02-Java-Expressions-and-Statements.ss

// @Java:

for (int i = 0; i < 10; i++)
    System.out.printf("%02d: %s\n", i, ((i % 2) == 0) ? "even" : "odd");

System.out.println("DONE");

Executed with:

ss --run se-02-Java-Expressions-and-Statements.ss

Result:

00: even
01: odd
02: even
03: odd
04: even
05: odd
06: even
07: odd
08: even
09: odd
DONE

As you can see, for statements can be used in the script just like in a regular Java code. Also, Java expression such as the ‘++‘ or ‘?:‘ can be used. This is true to every Java expressions and statements as SimpleScript passes on the compilation of the code to Java compiler. Thus, everything that is valid to Java compiler also valid to SimpleScript.

3: Java Libraries

Not only Java expressions and statements, Java code in SimpleScript can fully access to all Java classes within the class path. This example demonstrates that.
se-03-Java-Libraries.ss

// @Java:
import java.io.*;
import java.util.*;

// Get the files
final File   aWorkingDir = (new File("")).getAbsoluteFile();
final File[] aFiles      = aWorkingDir.listFiles();

// Create the sorted file list
final List aItems      = new ArrayList();
for (int i = 0; i < aFiles.length; i++) {
    final File   aFile = aFiles[i];
    final String aKind = aFile.isDirectory() ? "D" : "F";
    final String aName = aFile.getName();
    final String aItem = String.format("  %s: %s", aKind, aName);
    aItems.add(aItem);
}
Collections.sort(aItems);

System.out.println(aWorkingDir);
for (final String aItem : aItems)
    System.out.println(aItem);

System.out.println("DONE");

Executed it in a directory on my computer:

ss --run se-03-Java-Libraries.ss

Result:

/home/nawaman/CodeTemp/SimpleScript
  D: SimpleExamples
  D: uses
  F: SimpleScript-bin.jar
  F: SimpleScript-examples.zip
  F: convert-mph-to-kph-JOptionPane
  F: se-01-Hello-World.ss
  F: se-01-Hello-World.ss~
  F: ss
  F: test-small-with-shebang.ss
  F: test.js
  F: test.js~
  F: test.ss
  F: test.ss~
  F: testjs.ss
  F: testjs.ss~
DONE

In this example, the code access to File in java.io package to get a list of files, List, ArrayList and Collections in java.util package to sort the files items. The code even use generic. This again demonstrates that Java code written for SimpleScript are compatible almost 100% with regular Java code. The exceptions for the incompatibilities will be discussed in later.

4: Command-Line Arguments

This example shows how can script code access to the command-line arguments given to the script.
se-04-cli-arguments.ss

// @Java:

System.out.println("$Args:");
for (int i = 0; i < $Args.length; i++)
    System.out.printf("% 2d): %s\n", i, $Args[i]);

System.out.println("DONE");

Executed with:

ss --run se-04-cli-arguments.ss a b c d

Result:

$Args:
 0): a
 1): b
 2): c
 3): d
DONE

Accessing to the command-line arguments can be done via variable $Args — an array of strings. Then first index (0) represents the first argument. This is exactly the same as the argument parameter given to main function. Since they are exactly the same, you can use CLI library such as the apache’s common CLI library to handle it.

5: Let’s make a useful program

Armed with the knowledges that Java code of SS can access to all Java library and how to access the command-line arguments, we can now write some useful program.

I use Linux full time and enjoy writing script (bash) to automate certain tasks for me. Once in a while I want to format text in a certain way so I use printf command which serve me very well. However, bash printf is not as powerful as String.format in Java (e.g, the lack of indexed replacement) and I would like to use it sometime.

Now, let’s make a script to allows me to use String.format via command line.

Here are the code:
se-05-format.ss

// @Java:

// Not enough arguments
if ($Args.length == 0) {
    System.err.println("
 [args ...]");
    System.exit(-1);
    return;
}

final String   aFormat = $Args[0];
final Object[] aArgs   = new Object[$Args.length - 1];
for (int i = 0; i < aArgs.length; i++) {
    final String aArg    = $Args[i + 1];
    final int    aLength = aArg.length();
    final Object aValue;

    if ((aLength > 2)
     && (aArg.startsWith("#"))) {
        // Convertion to number (text that starts with '#' and are at least 3 chars long)
        final char   aKind   = aArg.charAt(aLength - 1);
        final String aNumber = aArg.substring(1, aLength - 1);
        if      (aKind == 'i') aValue = Integer.parseInt   (aNumber); // i for Integer
        else if (aKind == 'd') aValue = Double .parseDouble(aNumber); // d for Double
        else {
            System.err.println("Unsupport numbering kind: " + aArg);
            System.exit(-1);
            return;
        }
    } else {
        // As string
        aValue = aArg;
    }
    aArgs[i] = aValue;
}
// Prints the formated
System.out.printf(aFormat, (Object[])aArgs);

Let’s try running it:

ss --run se-05-format.ss '--- %2$s %1$s ---' 'one' 'two'

You’ll get:

--- two one ---

Notice that ‘one’ is shown after ‘two’ because the indexed replacement.

Try the numbering:

ss --run se-05-format.ss '--- %2$s %3$03d %1$s ---' 'one' 'two' '#5i'

You’ll get:

--- two 005 one ---

As you can see, I can now can use Java string format. Indexed replacement, leading zero and all other features can now be available to my bash program. You can apply this to others functionalities like swing, regular expression, thread and whatever you want.

Let just stop for now. Next time, I will show you advance how Java SS code is mapped to the actual code so that you can use other advance features of SS.

All codes can be found at http://projects.nawaman.net/files/SimpleScript/SimpleExamples/.

Enjoy codeing …
Bye bye now.


Copyright 2010: Nawapunth Manusitthipol
Categories: Programming Tricks, SimpleScript Tags: