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

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 »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.