TweetFollow Us on Twitter

RemoteScriptRunner: Remotely execute scripts from any web browser

Volume Number: 19 (2003)
Issue Number: 12
Column Tag: Programming

RemoteScriptRunner: Remotely execute scripts from any web browser

by Joe Zobkiw

Introduction

Lately I've been exploring Java and the many things that can be done with it. I will admit that for years I was turned off by Java due to my initial experiences with it in the Mac OS. When Java was first introduced on the Mac OS it was horribly slow. Most people first saw Java perform in the form of an applet or some other browser-based user interface - unfortunately this was not Java's strong suit. However, with Mac OS X, Jaguar and especially Panther, Apple has made great strides in making Java much more usable on the Mac...which caused me to give it a second look.

Java is not just for user interfaces. In fact, there are so many tributaries flowing off the Java river that it's liable to make your head spin just trying to figure out what Java is actually capable of! In fact, it's probably safe to say that Java is capable of just about any type of software development you are interested in - all you have to do is figure it out or find someone who already has. Java can be used to write clients and servers, access databases, communicate with mobile devices, run appliances, write platform-native code, etc. In this article we look at Java's server side - which arguably is a better choice than many other languages (including C) when writing a server.

RemoteScriptRunner is a proof-of-concept Java application that runs as a daemon process in the background. That is, you won't see any icons in the Dock while RSR is running - like most servers. Although Java can be platform independent, this one implements the ability to execute AppleScript format scripts, so in that regard it is platform specific to any platform that implements AppleScript. However, this mechanism can easily be changed to support other scripting architectures and is left as an exercise to the reader.

RSR is modeled after an article written by David Brown in August 1997 entitled "A Simple, Multithreaded Web Server" which can be found on the Sun Java developer web site at http://developer.java.sun.com/developer/technicalArticles/Networking/Webserver/. I recommend you look at this article for details on the server as I will not delve into the details of that here. In fact, this article takes more of a "here's what I learned" approach. The AppleScript portion of this code is modeled on a code example by Scott D.W. Rankin and is available at http://macdevcenter.com.

20,000 Feet

At 20,000 feet, RSR functions as follows. You double-click the compiled Java application, usually in the form of a JAR file. Although you won't see it in the Dock, suffice it to say that this starts the server running and waiting for client connections on port 8080, or any port you specify. You can check to see if the server is running by typing ps ax | grep java in Terminal. If the server is running you should see a line in the result that looks something like 460 ?? S 0:00.71 java -jar /Users/zobkiw/RSR/RemoteScriptRunner.jar. At this point the server is active yet essentially idle as it awaits a connection from a web browser client.

Next, a user launches their web browser and accesses the server as they would any other HTTP URL. In our case, since we are testing things locally, we use http://localhost:8080/ but localhost can be 127.0.0.1 or any other valid IP address or server/domain name. The server accepts the HTTP connection, sees that the request is in GET format and returns the HTML necessary to display a form to the user. This form contains an editable text area, a submit button and a button to quit the server. The editable text area is used to type your AppleScript.

Once an AppleScript is entered, you press the Submit button to POST the form and data to the server. This time when the browser connects to the server, the server accepts the connection and sees that the request is in POST format and parses the data in the form -- most importantly, the AppleScript. The server attempts to execute the script using the necessary AppleScript-related Java classes and returns the results as HTML to the client.


Figure 1 - RemoteScriptRunner in action

In Figure 1 we show the two "pages" created by the server. In the first page (behind) we have filled out the form to include an AppleScript that tells the Finder to get the name of every item in the desktop. After submitting this script, we see the results in the second page (front). Note that the results are simply a list of items that happened to be on my desktop at the time.

10,000 Feet

Zooming down to 10,000 feet, let's take a look at the development environment and source code. Java development tools can take you in many different directions - all have their advantages and disadvantages for any particular project. There is Project Builder for pre-10.3 users, Xcode for 10.3 users and beyond, Eclipse for anyone on just about any platform, and then BBEdit and the command line. Although I've written Java code using each of these options, for this project I chose BBEdit and the command line. When there isn't a whole lot of code to write I can do things just as easily and usually faster by using these stand-by tools.

So, in this project I created my RemoteScriptRunner.java file in BBEdit as well as the manifest file, RemoteScriptRunner.mf. Then I use Terminal to compile, run and build the JAR file. The command line to compile is javac -classpath /System/Library/Java:. RemoteScriptRunner.java. The command line to run is java -classpath /System/Library/Java:. RemoteScriptRunner. The command line to build the JAR file is jar cmf RemoteScriptRunner.mf RemoteScriptRunner.jar *.class. The manifest file is a text file that contains two lines, as follows:

   Main-Class: RemoteScriptRunner
   Class-Path: /System/Library/Java/ 

Because the easily accessible Brown article mentioned earlier does such a good job at explaining the multithreaded nature of the server, to which I made few changes, I won't go into the details of that here. This article will primarily discuss the handleClient method of the Worker class that is called after a connection is accepted. However, let's quickly discuss what leads up to the handleClient method being called.

First, the main program loads all program settings and creates a series of Worker objects as Threads. Because it's less "expensive" to create a few of these up-front, we do it at program initialization rather when a connection is actually established. These Worker objects are stored in a Vector and are available to handle connections as they are accepted. The server then establishes itself and loops forever, waiting for a connection. When a connection is established, the first Worker object not already busy is pulled from the Vector and passed the Socket that accepted the connection. At this point the Worker object, which was in a wait state, is notified to wake up and begin its work, ultimately calling its handleClient method.

In handleClient the first thing you want to do is create a PrintWriter on the socket's output stream for writing and a BufferedReader on the socket's input stream for reading. We also set the timeout so we don't hang the machine in the case where the socket is left open but there is nothing left to read.

   // Create a reader and writer
   PrintWriter pw = new PrintWriter(clientSocket.getOutputStream(), true);
   BufferedReader br = new BufferedReader(new 
      InputStreamReader(clientSocket.getInputStream()));
            
   // We will only block in read for this many milliseconds before we fail with 
   // java.io.InterruptedIOException, at which point we will abandon the connection
   clientSocket.setSoTimeout(RemoteScriptRunner.timeout);
   clientSocket.setTcpNoDelay(true);

Depending on what the purpose of your server is, you can very easily loop calling the readLine method of the BufferedReader repeatedly until no more data is available. This will get you (most) everything coming from the client.

   // Read the bulk of the data from the input by line
   String s;
   while (((s = br.readLine()) != null) && (s.length() != 0))
      System.out.println("> " + s);

We do just this with the addition that we also look for specific information coming from the client. In the HTTP protocol the server receives all sorts of information from the client when a connection is open. A part of this information includes the type of request. Although we can just as easily look for specific codes and values within the URL or embedded in the data, in this implementation we look for GET and POST requests specifically and base our response on that. We make use of the startsWith method of the String class for this purpose. If the string starts with "GET" then we respond by sending back the HTML containing the form. If the string starts with "POST" then we know that the form is being submitted and we extract the AppleScript from it and attempt to execute it, returning its result.

One thing to note about the readLine method used above is that in the case of a POST, readLine will not read the POSTed form data. The problem is that the form data does not end in a newline character, so readLine essentially ignores it. Given that, in the case of a POST, we have to finish reading the data character by character using the read method of the BufferedReader. As we read each character, we build a string containing all of the data.

   // Read the rest of the available data and create a string of it
   s = "";
   while (br.ready() && ((ch = br.read()) != -1))
      s += (char)ch;

Once you have the string containing the form data there are a few things to do to it before you use it. First we trim the string using the trim method of the String class. Next we decode the string using the decode method of the URLDecoder class, passing "UTF-8" as the decoding scheme. Then, using the StringTokenizer class we split the string by '&' to extract the name and value pairs. Once we have each pair we use the StringTokenizer class once again to split the string by '='. This gives us the value of any particular field from the form. The getFormVariableValue method shows the use of the StringTokenizer class. It assumes a string passed in such as script=beep 3&something=this&somethingelse=that.

   // Get a form variable value from a list of variable name and data pairs
   String getFormVariableValue(String variables, String name)
   {
      // Set up our first tokenizer and variables
      StringTokenizer st1 = new StringTokenizer(variables, "&");
      String s1 = "";
      String n1 = name.toLowerCase() + "=";
      
      // If the given name is not even in the variables then exit immediately
      if (variables.toLowerCase().indexOf(n1) == -1)
         return null;
      
      // Search for first token as a name and data pair (ie: variable=data)
      while (!s1.startsWith(n1) || s1.length()==0) {
         s1 = st1.nextToken();
         System.out.println("s1=" + s1);
      }
      // Now that we have the first token, we can split it into the name and data specifics
      StringTokenizer st2 = new StringTokenizer(s1, "=");
      String s2 = "";
      String n2 = name.toLowerCase();
      while (s2.startsWith(n2) || s2.length()==0) {
         s2 = st2.nextToken();
         System.out.println("s2=" + s2);
      }
      
      return s2;
   }

At this point, by extracting the value of the "script" form variable we finally have the raw AppleScript to execute. We first create a new NSAppleScript object by passing in the script. We then create an NSMutableDictionary object to hold any errors during execution. Sending the NSAppleScript object the execute message causes the script to execute and return results in an NSAppleEventDescriptor object. The results in that object can then be extracted and displayed.

   NSAppleScript myScript = new NSAppleScript(s);
                     
   // This dictionary holds any errors that are encountered during script execution
   NSMutableDictionary errors = new NSMutableDictionary();
               
   // Execute the script!
   NSAppleEventDescriptor results = myScript.execute(errors); 
   // If multiple items in the result we use this to display results
   int numberOfItems = (results == null) ? 0 : results.numberOfItems();
   for (int i = 1; i <= numberOfItems; i++) {
      NSAppleEventDescriptor subDescriptor = results.descriptorAtIndex(i);
      System.out.println(subDescriptor.stringValue());
   } 
                     
   // If only one item in the result we can use this
   if (numberOfItems == 0) {
      String resultString = (results == null) ? "" : results.stringValue();
      System.out.println(resultString);
   }

Conclusion

As mentioned, RSR is a proof-of-concept for a larger project of mine. There are many ways to improve this code and even more possible features to add. There are also other ways to remotely invoke scripts, but this was a fun project to put together that works reliably. In closing, I hope this convinces you to give Java a second chance -- you just might like it!


Joe Zobkiw is the author of Mac OS X Advanced Development Techniques and President of TripleSoft Inc., a software development and consulting company in Raleigh, NC. He can be reached at zobkiw@triplesoft.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »

Price Scanner via MacPrices.net

Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more
Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more

Jobs Board

Licensed Practical Nurse - Womens Imaging *A...
Licensed Practical Nurse - Womens Imaging Apple Hill - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Regular Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.