Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
Top Links You Must Click On


Writing Unix Filters in Java
Writing Unix Filters in Java

More recently, due in part to Sun's "Java Everywhere" campaign, we are beginning to see applications featuring server-side Java (servlets) and imbedded Java devices (phones, light switches, etc.), as well as large-scale standalone applications (Sun Java Server). What continues to be a seldom discussed subject is small-scale standalone Java applications.

While there have been several major standalone Java applications released, many are geared toward the Internet. Some are even more narrowly focused as Java development tools. What many of these applications have in common is that they tend to be graphical in nature and are invoked via a wrapper function. These wrapper functions are typically written in shell or batch script. They define the proper Java runtime environment and then invoke the application.

What is missing today is the ability for non-Internet developers to easily use Java in place of C or Perl to write standalone programs. This article will describe an automated method whereby the necessary Java runtime environment can be set up prior to invoking a Java application. With this environment, you can begin to use Java in place of other languages (Korn shell, bash, Perl, etc.) for your normal daily systems administration needs. These small utilities can then be deployed into your system bin directory for all to use.

For the purposes of this article, I assume that you have a good understanding of client/server technologies, object-oriented programing and C/C++ as well as a basic understanding of the Unix operating system and shell programming.

Clarification
It should be noted that several third-party Java compilers now support "native" code generation. Namely, the compile process generates an executable image that will run only on the target platform, much like a C compiler generates a binary executable file. To accomplish this, most compiler vendors are imbedding the Java Virtual Machine (JVM) in the binary object. While this solves the problem of a standalone application's runtime environment, these compilers are mostly limited to 95/NT platforms. This will be a suitable solution once these compilers are available on all platforms. Until then we must make do with supplying our own runtime environment.

The Goal
Our objective is to create a facility whereby we can write "Unix type" filters in Java. For this discussion, we will be focusing on the filter framework and not the filter applications themselves.

In general, a Unix filter is a process that reads standard input (stdin), or a file, and writes to standard output (stdout), or a file, all the while applying a filter algorithm to the input data. A filter can be something simple like transforming all upper case letters to lower or it can consist of complex mathematical formulations.

A good filter should support the following features:
1. Unix-style optional switches: a dash "-" followed by either a letter or word
2. switches that can have other optional arguments: "-filename foo.txt"
3. Redirection and pipes, optionally
4. systematic error checking on all switch settings.
5. Be cross-platform compatible
6. Once installed in the system bin directory, the ability to be invoked directly by entering the name of the filter at the command prompt.

To achieve these goals we must develop two distinct entities:
1. A standardized Java front-end for processing filter switch settings
2. A standardized script front-end for creating the necessary run-time environment for a given filter

Additionally, a method whereby the wrapper script is married to the application filter in an automated process would help to simplify the make process.

Java Filter Front-End
For our discussions, the front-end filter process will be designed to read switch settings, detect user input errors and display on-line help. More importantly, it will also invoke the core program logic. Listing 1, Java Filter Front-End, depicts just such a program. This program consists of the following sections:
1. Main function declaration - Necessary for all standalone Java programs.
2. Switch parsing section - Two switches are defined by default: verbose and help
3. On-line help - If the help option is specified, a detailed usage message will be displayed.
4. Error handler - If an illegal or malformed switch is set, the error handler will display a message and terminate.
5. Application code - Once all switches are successfully processed, normal/core execution can be resumed.

With this simple template file, we now have the structure necessary to support most of the desired functionality - namely, five of the six features of a standalone filter. By modifying this structure we can easily support additional switch settings, input and output arguments.

Unfortunately, this template program is not sufficient to solve the sixth requirement: "direct invocation of the target program from the command line." To achieve this last requirement, we need to resort to a wrapper script.

Invoking a Standalone Java Program
All Java programs must be invoked via the Java Virtual Machine. Java programs cannot be invoked directly - as is the case for C/C++ programs, batch files, or script files. There is no equivalent of a magic cookie (e.g., #!/usr/Java/bin) for a Java program. Trying to execute a Java program by typing the class name will not work, nor will making the class file executable.

To run your program, you must make sure that the Java Virtual Machine can find your class file. This can be done in several ways: setting the CLASSPATH variable, starting the JVM from the same directory as your .class file, etc.

Example 1:

> export CLASSPATH =
/usr/local/Javabin:$CLASSPATH
> Java /usr/local/Javabin/MyApp

Example 2:

> cd /usr/local/Javabin
Java MyApp

Either of the above methods will ensure that the Java Virtual Machine can find the target class file.

If your Java program relies on other class definitions then you must specify the path to the other class files too. Again assuming the current CLASSPATH definition does not contain the necessary path information, you must specify the proper path spec during invocation. For example:

> Java -classpath
/usr/local/Javabin:
~/Javabin:$CLASSPATH
MyApp

Since our goal is to make your Java application easy for others to use, we must wrap all of the aforementioned constraints into an easy to use package. The end user should not have to type anything more than "MyApp" to invoke your application. The remainder of this article will address just how this can be accomplished.

Wrapper Script
The wrapper script (Listing 2) depicts a shell script designed to invoke your Java applications for you. The purpose of the wrapper script is to simplify the process of invoking your Java Applications to the point where you only need enter the program name along with any application specific parameters.

Let's review exactly what this script does:

  • Line 1: Magic cookie: Ensures that the script's contents can be interpreted no matter what the current shell environment is set to.
  • Line 2: Isolates the target program name from the invocation path. This allows the script to be called relatively, absolutely or via the PATH environment variable. Example:

    ../../myBin/MyApp
    /home/kkranz/myBin/MyApp
    MyApp

  • Line 3: Separates the invocation path (e.g. ../../myBin/) from the full path to the script (/home/kkranz/myBin)
  • Line 4: Assumes that the .class file and the script file are named the same: MyApp.ksh, vs. MyApp.Java, vs. and MyApp.class
  • Line 6: Computes the absolute path to the script (and presumably to the .class file - assuming that the script and class files are in the same directory)
  • Line 8: Switches to the script's bin directory
  • Lines 10-13: Looks for a .class file named after the script file in the class directory. If there is no .class file the script aborts.
  • Line 15: Adds the script's bin directory to the CLASSPATH environment variable. An acceptable alternative would have been to pass this information via the -classpath option to the Java Virtual Machine. Either method is acceptable.
  • Line 17: Invokes the Java Virtual Machine with the base name of the script as the first argument and any remaining options as the remainder of the line.

    With the use of the wrapper script in Listing 3, you can make it very easy to invoke your Java applications, regardless of what the installation directory is. The only implementation criteria that must be met to use this script are:
    1. You must use the same name for the script file as you do for the .class file.
    2. The script file and the .class file must reside in the same bin directory, although you could easily modify the script to allow the script files to reside in one directory and the .class files to reside in a separate class bin directory.
    3. The script file must reside in a directory defined by the PATH variable.
    4. Other .class files that are accessed at run-time must be in a directory defined by the CLASSPATH environment variable or in a script directory.

    Generating the Wrapper Script
    So far, we have described a template Java application program and wrapper script that can be used to write standalone Java programs.The final step is to write a program that can generate a wrapper script for a given standalone Java program.

    The Java Compiler script (Jcc, listing 3) performs the following basic functions:
    1. Invokes the Java compiler to create the .class file from your source
    2. Invokes Javadoc, to create html based documentation files
    3. Creates a wrapper script tailored toward invoking your Java application
    4. Creates a manual page for your application

    Using the Java Compiler script is not mandatory. Its purpose is to simplify the process whereby your Java program and its associated files are generated. Listing 4, Example Makefile, demonstrates how the Jcc would be used in a Unix-style makefile.

    Conclusion
    If you are a systems administrator and are otherwise not involved in the internet, you do not have to feel left out of the Java learning curve. By using this wrapper script you can begin to use Java in places where you would have traditionally used Perl, C or a shell language. Given Java's rapid growth, it is very likely that it will become a standard feature on most future operating systems. By learning and using Java now, you will help prepare yourself for that time.

    About Kenneth J. Kranz
    Ken Kranz is the director of Internet Services for Interaxis Corporation, a developer of database-driven Web sites.This and the expanded source code used in this article can be found at www.ebbtide.com/UnixFilters.

  • In order to post a comment you need to be registered and logged in.

    Register | Sign-in

    Reader Feedback: Page 1 of 1

    Enterprise Open Source Magazine Latest Stories . . .
    Apache Deltacloud, the Red Hat-contributed ReSTful API that abstracts differences between clouds so services on any cloud can be managed – provided of course there’s a driver – has graduated from the Apache Foundation’s incubator and is now a full-fledged Top-Level Project (TLP). The...
    With Cloud Expo 2012 New York (10th Cloud Expo) just four months away, what better time to start introducing you in greater detail to the distinguished individuals in our incredible Speaker Faculty for the technical and strategy sessions at the conference... We have technical and st...
    AMD said late Tuesday that its chief sales officer Emilio Ghilardi had left the company and that CEO and president Rory Read is going to do his job while a replacement is sought. AMD didn’t say why Ghilardi left but it’s assumed Read wants his own people. Read is relatively new to th...
    During the lifespan of M3 (Monitis Monitor Manager) there has always been something lacking – timers. M3 execution procedure was outlined in this previous article. The execution mentioned in the latter was a one-time-execution, whereas server monitoring requires periodic invocati...
    Red Hat is putting its bought-in Gluster scale-out NAS storage technology, acquired in October, on the Amazon cloud. It’s styled Red Hat Virtual Storage Appliance for Amazon Web Services and other clouds are supposed to follow in short order.
    A new episode of the screencast series is now available at the OpenNebula YouTube Channel. This screencast demonstrates the new easily-customizable self-service portal for cloud consumers. Its aim is to offer a simplified access to shared infrastructure for non-IT end users. The scree...
    Subscribe to the World's Most Powerful Newsletters
    Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
    Click to Add our RSS Feeds to the Service of Your Choice:
    Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
    myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
    Publish Your Article! Please send it to editorial(at)sys-con.com!

    Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


    SYS-CON Featured Whitepapers
    ADS BY GOOGLE