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

Jump into one of Volkswagen's most...
We spoke about PUBG Mobile yesterday and their Esports development, so it is a little early to revisit them, but we have to because this is just too amusing. Someone needs to tell Krafton that PUBG Mobile is a massive title because out of all the... | Read more »
PUBG Mobile will be releasing more ways...
The emergence of Esports is perhaps one of the best things to happen in gaming. It shows our little hobby can be a serious thing, gets more people intrigued, and allows players to use their skills to earn money. And on that last point, PUBG Mobile... | Read more »
Genshin Impact 5.1 launches October 9th...
If you played version 5.0 of Genshin Impact, you would probably be a bit bummed by the lack of a Pyro version of the Traveller. Well, annoyingly HoYo has stopped short of officially announcing them in 5.1 outside a possible sighting in livestream... | Read more »
A Phoenix from the Ashes – The TouchArca...
Hello! We are still in a transitional phase of moving the podcast entirely to our Patreon, but in the meantime the only way we can get the show’s feed pushed out to where it needs to go is to post it to the website. However, the wheels are in motion... | Read more »
Race with the power of the gods as KartR...
I have mentioned it before, somewhere in the aether, but I love mythology. Primarily Norse, but I will take whatever you have. Recently KartRider Rush+ took on the Arthurian legends, a great piece of British mythology, and now they have moved on... | Read more »
Tackle some terrifying bosses in a new g...
Blue Archive has recently released its latest update, packed with quite an arsenal of content. Named Rowdy and Cheery, you will take part in an all-new game mode, recruit two new students, and follow the team's adventures in Hyakkiyako. [Read... | Read more »
Embrace a peaceful life in Middle-Earth...
The Lord of the Rings series shows us what happens to enterprising Hobbits such as Frodo, Bilbo, Sam, Merry and Pippin if they don’t stay in their lane and decide to leave the Shire. It looks bloody dangerous, which is why September 23rd is an... | Read more »
Athena Crisis launches on all platforms...
Athena Crisis is a game I have been following during its development, and not just because of its brilliant marketing genius of letting you play a level on the webpage. Well for me, and I assume many of you, the wait is over as Athena Crisis has... | Read more »
Victrix Pro BFG Tekken 8 Rage Art Editio...
For our last full controller review on TouchArcade, I’ve been using the Victrix Pro BFG Tekken 8 Rage Art Edition for PC and PlayStation across my Steam Deck, PS5, and PS4 Pro for over a month now. | Read more »
Matchday Champions celebrates early acce...
Since colossally shooting themselves in the foot with a bazooka and fumbling their deal with EA Sports, FIFA is no doubt scrambling for other games to plaster its name on to cover the financial blackhole they made themselves. Enter Matchday, with... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra available today at Apple fo...
Apple has several Certified Refurbished Apple Watch Ultra models available in their online store for $589, or $210 off original MSRP. Each Watch includes Apple’s standard one-year warranty, a new... Read more
Amazon is offering coupons worth up to $109 o...
Amazon is offering clippable coupons worth up to $109 off MSRP on certain Silver and Blue M3-powered 24″ iMacs, each including free shipping. With the coupons, these iMacs are $150-$200 off Apple’s... Read more
Amazon is offering coupons to take up to $50...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for up to $110 off MSRP, each including free delivery. Prices are valid after free coupons available on each mini’s product page, detailed... Read more
Use your Education discount to take up to $10...
Need a new Apple iPad? If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $100 off the... Read more
Apple has 15-inch M2 MacBook Airs available f...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
Mac Studio with M2 Max CPU on sale for $1749,...
B&H Photo has the standard-configuration Mac Studio model with Apple’s M2 Max CPU in stock today and on sale for $250 off MSRP, now $1749 (12-Core CPU and 32GB RAM/512GB SSD). B&H offers... Read more
Save up to $260 on a 15-inch M3 MacBook Pro w...
Apple has Certified Refurbished 15″ M3 MacBook Airs in stock today starting at only $1099 and ranging up to $260 off MSRP. These are the cheapest M3-powered 15″ MacBook Airs for sale today at Apple.... Read more
Apple has 16-inch M3 Pro MacBook Pro in stock...
Apple has a full line of 16″ M3 Pro MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $440 off MSRP. Each model features a new outer case, shipping is free, and an... Read more
Apple M2 Mac minis on sale for $120-$200 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $110-$200 off MSRP this weekend, each including free delivery: – Mac mini M2/256GB SSD: $469, save $130 – Mac mini M2/512GB SSD: $689.... Read more
Clearance 9th-generation iPads are in stock t...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on clearance sale for starting at only $199 on their online store for a limited time. Sale prices for online orders only, in-store prices may vary... Read more

Jobs Board

Senior Mobile Engineer-Android/ *Apple* - Ge...
…Trust/Other Required:** NACI (T1) **Job Family:** Systems Engineering **Skills:** Apple Devices,Device Management,Mobile Device Management (MDM) **Experience:** 10 + Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Full Time (80 hrs/pay period) Evenings General Summary Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.