Unable to load extension class ?

JSR 223

Here is an extract describing this topic :

Servlet specification (Servlet 2.4, JSR-154, is the latest version) defines the set of core abstractions that are used by Java developer writing Web Applications. These abstractions include those of Web Application context, session, request, response, etc. When Java developers write Web Applications, they write classes that interact with these objects in well defined security, resource and class loader contexts. The proposed specification will describe which of these Java objects will be exposed to pages written in other scripting languages. The specification will be grounded on at least one concrete scripting language example, PHP, but the concepts will remain independent of the scripting language and, if at all possible, the EG will also explore the bindings to at least another scripting language. The EG will also explore the case where the Java objects may not be associated with a specific Web application but may just be instantiated in a Java Virtual Machine.

The specification may include a Java API that can be used, possibly through JNI, by an scripting language engine to access the desired Java objects.

This specification will describe how it is possible to bundle scripting pages into a WAR file, either stand-alone, or as part of an EAR. The specification will describe the different implications for security, resource, and class loader contexts both in the case of stand-alone WARs and as part of an EAR. The EG will also consider whether it is appropriate to deliver scripting and Java code outside of a WAR.

The specification may describe how scripting pages can be denoted as such in a WAR in a manner that is easily identified using only the machinery in any standard Servlet container. For instance, it may be appropriate to define a standard Servlet per scripting language; this would allow a WAR to indicate in its web.xml descriptor which files are in a given scripting language. The EG may decide that a container that follows this JSR can use a different mechanism, like a default extension value, to determine that a page is an scripting language known to the container.


Picture 1Starting in groovy version 2.1.4 and later, we have this additional scripting language extension feature offered for the java and groovy community. This feature is only available for users with installed java JVM versions 1.6+ so if, like me, you’re still running jdk 1.5, we’re out of luck.


Jun 12, 2013 4:26:55 PM org.codehaus.groovy.runtime.m12n.SimpleExtensionModule getMetaMethods 
WARNING: Module [groovy-jsr223] - Unable to load extension class [class org.codehaus.groovy.jsr223.ScriptExtensions] due to [javax/script/ScriptEngine]. 
Maybe this module is not supported by your JVM version. 

Jun 12, 2013 4:26:55 PM org.codehaus.groovy.runtime.m12n.SimpleExtensionModule getMetaMethods WARNING: Module [groovy-jsr223] - Unable to load extension class [class org.codehaus.groovy.jsr223.ScriptStaticExtensions] due to [javax/script/ScriptEngineManager]. Maybe this module is not supported by your JVM version. 

Groovy Version: 2.1.4 JVM: 1.5.0_30 Vendor: Apple Inc. OS: Mac OS X

This script extension defines new Java 6 specific groovy methods, so look here for more details :http://groovy.codehaus.org/api/org/codehaus/groovy/jsr223/ScriptExtensions.html

P.S.

What i really meant to say is that your installed version of the java jdk is too old to be able to run the extra new logic that comes with later versions of groovy. Update your installed JDK to jdk 1.6 or later to be able to use these new extensions – thx.

See Groovy Classpath

I used this code fragment to print my groovy classpath from within a groovy script :


def printClassPath(classLoader) {
  println "$classLoader"
  classLoader.getURLs().each {url->
     println "- ${url.toString()}"
  }
  if (classLoader.parent) {
     printClassPath(classLoader.parent)
  }
}
printClassPath this.class.classLoader

and we can see our full classpath sequence to determine missing / wrong jars ! Like this:

groovy.lang.GroovyClassLoader$InnerLoader@76911d
groovy.lang.GroovyClassLoader@b155b7
org.codehaus.groovy.tools.RootLoader@c51355
- file:/Volumes/Media1/Software/menus/./
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/ant-1.8.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/ant-antlr-1.8.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/ant-junit-1.8.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/ant-launcher-1.8.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/commons-logging-1.1.1.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/gpars-1.0.0.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-ant-2.1.4.jar
- file:/Volumes/Media1/Software/g.4/lib/antlr-2.7.7.jar - file:/Volumes/Media1/Software/groovy-2.1.4/lib/asm-4.0.jar - file:/Volumes/Media1/Software/groovy-2.1.4/lib/asm-analysis-4.0.jar - file:/Volumes/Media1/Software/groovy-2.1.4/lib/asm-commons-4.0.jar - file:/Volumes/Media1/Software/groovy-2.1.4/lib/asm-tree-4.0.jar - file:/Volumes/Media1/Software/groovy-2.1.4/lib/asm-util-4.0.jar - file:/Volumes/Media1/Software/groovy-2.1.4/lib/bsf-2.4.0.jar - file:/Volumes/Media1/Software/groovy-2.1.4/lib/commons-cli-1.2.jar - file:/Volumes/Media1/Software/groovy-2.1roovy-2.1.4/lib/groovy-bsf-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-console-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-docgenerator-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-groovydoc-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-groovysh-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-jmx-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-json-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-jsr223-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-servlet-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-sql-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-swing-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-templates-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-test-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-testng-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-xml-2.1.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/hamcrest-core-1.3.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/ivy-2.2.0.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/jansi-1.6.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/jcommander-1.27.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/jline-1.0.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/jsp-api-2.0.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/jsr166y-1.7.0.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/junit-4.11.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/qdox-1.12.1.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/servlet-api-2.4.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/testng-6.8.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/xmlpull-1.1.3.1.jar
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/xstream-1.4.2.jar
sun.misc.Launcher$AppClassLoader@a9c85c
- file:/Volumes/Media1/Software/groovy-2.1.4/lib/groovy-2.1.4.jar
sun.misc.Launcher$ExtClassLoader@cc7ad6
- file:/System/Library/Java/Extensions/AppleScriptEngine.jar
- file:/System/Library/Java/Extensions/CoreAudio.jar
- file:/System/Library/Java/Extensions/dns_sd.jar
- file:/System/Library/Java/Extensions/j3daudio.jar
- file:/System/Library/Java/Extensions/j3dcore.jar
- file:/System/Library/Java/Extensions/j3dutils.jar
- file:/System/Library/Java/Extensions/jai_codec.jar
- file:/System/Library/Java/Extensions/jai_core.jar
- file:/System/Library/Java/Extensions/libAppleScriptEngine.jnilib
- file:/System/Library/Java/Extensions/libJ3D.jnilib
- file:/System/Library/Java/Extensions/libJ3DAudio.jnilib
- file:/System/Library/Java/Extensions/libJ3DUtils.jnilib
- file:/System/Library/Java/Extensions/libmlib_jai.jnilib
- file:/System/Library/Java/Extensions/libQTJNative.jnilib
- file:/System/Library/Java/Extensions/libShark.jnilib
- file:/System/Library/Java/Extensions/mlibwrapper_jai.jar
- file:/System/Library/Java/Extensions/MRJToolkit.jar
- file:/System/Library/Java/Extensions/QTJava.zip
- file:/System/Library/Java/Extensions/vecmath.jar
- file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext/apple_provider.jar
- file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext/dnsns.jar
- file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext/localedata.jar
- file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext/sunjce_provider.jar
- file:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext/sunpkcs11.jar

How To Convert Firefox Bookmark Dates Using Groovy/Java

Firefox offers us two ways to keep our bookmarks, 1: backup as a json formatted file or 2: export as an html file.

This tip is for the json backup crowd 🙂

When we backup our bookmarks from Firefox, they come out formatted as json. The dates found therein are stored in what’s known as epoch dates ( read this ) though include millesecond precision – meaning 1,000 trailing milliseconds. So, for example, the firefox bookmark lastModified date of  1366313580447014 is really just 1366313580447. So when we write code, we divide by 1,000 to remove that part. My groovy code sample seemed to work when it looked like this :

def convertDate(def epoch)
{
     long dv = epoch / 1000; // divide by 1,000 to avoid milliseconds 
     String dt = new java.text.SimpleDateFormat("dd/MMM/yyyy HH:mm:ss").format(new java.util.Date (dv)); 
     // to get epoch date: 
     // long epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() * 1000; 
     return dt; 
} // end of def

So for a test sample, i did a firefox backup to get bookmarks-2013-04-29.json. Then added some groovy sugar to parse the text with json slurper.

json.lastModified :1366313580447014
convert from epoch date:18/Apr/2013 21:33:00

from :
println “convert from epoch date:”+convertDate(json.lastModified)

Git, Groovy and Gradle References

Five nice things we can do with groovy – samples of groovy code

groovy-http -Examples of how to interact with the web and create embedded webservers using Groovy

Git CheatSheet – good overview of most typical git workflow

Gradle Cookbook – useful code fragments to include in our buil.gradle files

Gradle Git – A set of plugins to support Git in the Gradle build tool

Printing in Java – an overview of features in java to allow printing on local printer

Gradle Application Plugin – overview of additional tasks include in our gradle environment when we include apply plugin:’application’

Sample Groovy / Java File Chooser

Here is a quick bit f code to choose a single file or directory. It’s written in groovy but uses java’s JFileChooser. It has many more options than demonstrated here, Look at the oracle link here.

// groovy sample to choose one file using java's  JFileChooser
// would only allow choice of a single directory by setting another JFileChooser feature
// http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
// see more examples in above link to include a file filter
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
// start to choose files from pwd
def initialPath = System.getProperty("user.dir");
JFileChooser fc = new JFileChooser(initialPath);
// fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = fc.showOpenDialog( null );
switch ( result )
{
   case JFileChooser.APPROVE_OPTION:
      File file = fc.getSelectedFile();

      def path =  fc.getCurrentDirectory().getAbsolutePath();
      println "path="+path+"\nfile name="+file.toString();
      break;
   case JFileChooser.CANCEL_OPTION:
   case JFileChooser.ERROR_OPTION:
      break;
}

Sample Java / Groovy Code to Play MP3 Sound Clip

Groovy

The groovy programming language is a super version of the java language specification. If you are a java developer, you can either rework this code sample or google elsewhere for an exact java example.

Steps To Test

Here is a sample program originally written in java. Here i’ve used groovy as a convenience. This code requires an mp3 codec which is found in the JLayer project seen here: 1.0.1 so download that jar. The latest version appears to be JLayer 1.0.1 from Nov.2008. This is what i used in this test.

  1. Make a new directory
  2. copy above jar into that directory
  3. place a sound or music clip recorded in the mp3 format into that directory
  4. copy the following groovy source code into that directory
  5. be sure you have a working groovy install from here
  6. open terminal command session
  7. change into that directory
  8. compile source code: groovyc -classpath .:jl1.0.1.jar SampleMP3player.groovy
  9. download my two sample mp3 files at bottom of post and place in same directory. One of these is teardrops.mp3
  10. test code : groovy -classpath .:jl1.0.1.jar SampleMP3player.groovy teardrops.mp3 35

ok, that test plays the mp3 file named teardrops.mp for 35 seconds. The second parameter is optionally an integer number of seconds of duration to play the sound clip (default is 10 sec.s). If your clip is longer, the remainder will not be heard as the .close() method stops the playback after timer expiry. If the sound clip is less than that, task blocks until timer expires even if sound clip finishes playing earlier.

Groovy Source Code

Code Comments

Place the following lines at the top of your source code file named SampleMP3player.groovy

/*************************************************************************
 *  Compilation:  groovyc -classpath .:jl1.0.1.jar SampleMP3player.groovy         (OS X)
 *                groovyc -classpath .;jl1.0.1.jar SampleMP3player.groovy         (Windows)
 *  Execution:    groovy -classpath .:jl1.0.1.jar SampleMP3player filename.mp3  (OS X / Linux)
 *                groovy -classpath .;jl1.0.1.jar SampleMP3player filename.mp3  (Windows)
 *
 *  Plays an MP3 file using the JLayer MP3 library.
 *
 *  Reference:  http://www.javazoom.net/javalayer/sources.html for jlayer jar with mp3 converter
 *
 *  To execute, you will need jl1.0.1.jar from the website above in your working directory with compiled source
 *  along with some .mp3 files in the same dir.
 ************************************************************************
*/
// /Volumes/PENDRIVE/MP3Player $ groovyc -classpath .:jl1.0.1.jar SampleMP3player.groovy
// /Volumes/PENDRIVE/MP3Player $ groovy -classpath .:jl1.0.1.jar SampleMP3player.groovy track6.mp3
// *
// *  redapple:jim /Volumes/PENDRIVE/MP3Player $ groovy -classpath .:jl1.0.1.jar SampleMP3player.groovy teardrops.mp3 35

Code Body

Place the following lines in the same source code file as above and following those comments


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;

public class SampleMP3player
{
// name of sound to be played – should be an MP3 format
String filename;
Player player;
def timer = new Timer()
int seconds = 10;

// constructor needs name of an MP3 file
public SampleMP3player(fn) {
this.filename = fn;
if (!new File(this.filename).exists() || (!this.filename.toLowerCase().endsWith(“.mp3”)) )
{
println “fatal: need mp3 file name as parameter\nNot found -> sound clip:”+this.filename
help();
} // end of if

} // end of constructor

// constructor needs name of an MP3 file
public SampleMP3player(fn,secs) {
//this.filename = fn;
this(fn);
this.seconds = secs as Integer;
} // end of constructor

/* sample code to try running another process while sound clip plays
// declare a task that runs after 10 seconds
def task = timer.runAfter(10000)
{
println “Actually executed at ${new Date()} for file ${filename}.”

// so while this task has started, wait another 10+ seconds before closing player
// which stops the music & issue an exit to finish the thread & JVM
sleep(new Random().nextInt(10) * 1000);
this.close();
System.exit(0);
}
— */

public void close()
{
if (player != null) player.close();
} // end of close()

// stream an MP3 file to audio output
public void play()
{
try
{
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e)
{
println(“Problem playing file ” + filename);
println e
} // end of try/catch

// use new thread to play in background
new Thread(){
public void run()
{
try { player.play(); }
catch (Exception x) { println x; }
} // end of run()

}.start(); // yes, we gotta start playing the clip in a new thread

} // end of play()

def static help()
{
println “groovy -classpath .:jl1.0.1.jar SampleMP3player \nfatal: need mp3 file name as parameter”
println “=== end ===”;
System.exit(1);
}

// typical main method
public static void main(String[] args)
{
println “=== start ===”;
String soundfilename = null;

if (args.size() 1)
{
mp3 = new SampleMP3player(soundfilename, args[1]);
} // end of if
else
{
mp3 = new SampleMP3player(soundfilename);
} // end of else

mp3.play();

// small example to run a task after some seconds that will close & stop the currently playing sound clip
// for testing, uncomment the next line plus def task method above
// println “Current date is ${new Date()}. Task is executed at ${new Date(mp3.task.scheduledExecutionTime())}.”

// note that we need to do process or task that will take up time as the sound clip stops playing when the .close() method is invoked
sleep(mp3.seconds * 1000);

// when done, stop playing it
println “ready to close() after ${mp3.seconds} seconds”;
mp3.close();

// play from the beginning
//def playthis = “teardrops.mp3”
//mp3 = new SampleMP3player(playthis);
//mp3.play();
System.exit(0);

println “=== end ===”;

} // end of main

} // end of class

enjoy 🙂

Sound Samples

Note that i had to do a funny as wordpress does not allow me to insert .mp3 files into my post so i rename them with a .jpg image suffix. This ensures all the bits reach your directory intact. But you will need to rename the ‘image’ to be able to use these clips.

Click here to download track6-mp3.jpg into your target folder then please rename it as track6.mp3 or look here: https://github.com/jnorthr/track6/tree/master/war/resources

Click here to download the teardrops3.mp3 sound clip into your target folder then please rename it as teardrops.mp3

Directory Layout

My directory looked like this after the above testing was complete.

Folder Content for MP3 Test
Folder Content for MP3 Test

Gretty Light-Weight Web Services Framework

Looking for a quicker prototype framework to do some demos for my clients, i received this tutorial from IBM Developerworks. This framework is much smaller than grails and does not support a full MVC stack, but my goodness, it really does show the power of groovy as an alternative JVM language and the new features in groovy++.

Since any missing jars can be resolved with the built-in Grape feature, the groovy source code can declare the need for jars using the @Grab annotation. There is no need for any other downloads, jars or installs to make gretty work. Hurrah !

For a quick test, you will need an installed version of Groovy 1.8.0 or later plus an internet connection so grape can download missing jar files. Here is an HTML template with the view described as :

<html>
 <head>
  <title>Hello!</title>
 </head>
 <body>
<h1>index.gpptl code</h1>
  <p>${message}</p>
  <p>I/P Address is ${addr}</p>
  <p>Host name is ${hname}</p>
  <p>Canonical name is ${cname}</p>
 </body>
</html>

We can save this template as index.gpptl, then below is the code to create a server on port 8080. I saved this code in a file called grettytest.groovy in the same directory as the above index.gpptl file. Then from a terminal, type groovy grettytest.groovy and wait for the server to start.

RedApple:jim /Volumes/Data/dev/gretty $ groovy grettytest.groovy 
Aug 22, 2011 11:27:34 AM org.mbte.gretty.AbstractServer
INFO: Started server on localhost/127.0.0.1:8080
Aug 22, 2011 11:27:45 AM org.mbte.gretty.httpserver.template.GrettyTemplateEngine
INFO: Trying to compile /Volumes/Data/dev/gretty/index.gpptl

Go to a browser and try http://localhost:8080/fred and if all your components are properly installed, you should see a display similar to below.

Snapshot of Display using Gretty Server and index.gpptl Template
Snap of Display using Gretty Server and a Template
import org.mbte.gretty.httpserver.* 

@GrabResolver(name='gretty',
  root='http://groovypp.artifactoryonline.com/groovypp/libs-releases-local')
@Grab('org.mbte.groovypp:gretty:0.4.279') 

def addr = InetAddress.localHost.hostAddress
def hname = InetAddress.localHost.hostName
def cname =InetAddress.localHost.canonicalHostName

GrettyServer server = []
server.groovy =
[
    localAddress: new InetSocketAddress("localhost", 8080),
    defaultHandler:
    {
        response.redirect "/"
    },
    "/:name":
   {
        get
        {
   		response.html = template("index.gpptl", [message: "Hello ${request.parameters['name']}",addr:"${addr}",hname:"${hname}",cname:"${cname}"    ])
        } // end of get
    } // end of
] 

server.start()

The grape feature in groovy++ uses the @GrabResolver to pull down needed dependencies from a web URL address. The @Grab annotation triggers the download of org.mbte.groovypp.gretty version 0.4.279 jars and we also need to declare an import for the gretty http server as @Grab also updates the JVM classpath to include the new arrival. Tidy !

The file name of our html template is the first parameter to the ‘template()’ method. Notice in the code how a binding map is fed to the template that builds the response.html. The first map entry ${request.parameters[‘name’]} pulls the text value bound to the incoming  request property ‘name’ to feed the ‘message’ variable in the template. This one gets it’s value, ‘Fred’ in the above example,  from the request parameter ‘name’. Look closely at the address bar in the screenshot. You’ll see that /fred follows the 8080 address. So ‘fred’ fills the ‘name’ request parameter which is then used to populate the ‘message’ variable in the template thus giving us “Hello fred”. Try replacing fred with your name to see the results.

Two other aspects i particularly like are 1) there is no need to restart the server for each/any source code updates as gretty places a continual watch on all files under it’s directory, so all we need is to click the browser refresh button after a source code or configuration code change, and voila, we have live results – great for heavy prototyping and 2) the ability to declare browser bar address attributes like “/:name”.

UPDATE: Ok, changed my mind on the first of those aspects as my google chrome browser is too smart and changes made in source DO NOT update real-time. I had to ctrl-C to kill the gretty server, then restart it. But even so, it’s rather quick to do so no big overhead in the development cycle :}

Further examples of gretty as a server, jackson for JSON consumption and also groovy++ can be found here.