Monday, March 19, 2007

How to build completely dynamic example with Spring 2, Scriptlandia, Beanshell, Groovy and JRuby

Recently, I found this project: GroovyWorks;.
It tries to use together such things as Java, Groovy, Spring 2 and Struts 2. Because Struts actions are written as Groovy scripts, it is not required to restart web application for each and every change. It is possible because of dynamic nature of Groovy language.

But still, it's not completely dynamic. Small portion of the system is written in Java and for each change in Java you have to recompile and redeploy your web application. Is it possible to make it completely dynamic?

In the following lines I will explain how to build such completely dynamic code. It is standalone application, so Struts 2 is not required. But we still want to have IoC container. Spring 2 fits for our needs, especially with new struts-scripting library, that supports 3 popular languages: Groovy, JRuby and Beanshell.

1. In order to work with scripts inside Spring 2 we have to create Java classes first. Let's create animal farm that consists of animals:


// Animal.java

public interface Animal {

public void makeSound();

}

// AnimalFarm.java

import java.util.List;

public class AnimalFarm {
private List animals;

public AnimalFarm() {
System.out.println("New Animal farm has been created.");
}

public void setAnimals(List animals) {
this.animals = animals;
}

public void wakeUp() {
for(int i=0; i < animals.size(); i++) {
Animal animal = (Animal)animals.get(i);

animal.makeSound();
}
}

}


2. Now, we can implements different animals in different languages:


// Cat.groovy

class Cat implements Animal {

void makeSound() {
println "Meow!"
}

}

# Dog.rb

require "java"

include_class("Animal")

class Dog < Animal
def makeSound
puts "Bark!!!"
end
end

Dog.new

// Cow.bsh

void makeSound() {
System.out.println("Moo...");
}


3. We'll keep all required libraries in the form of maven2 dependencies file.
Because current version of spring (2.0.3) is not compatible with jruby version 0.9.8
(see bug SPR-3255),
we have to keep reference to temporary repository:
http://scriptlandia-repository.googlecode.com/svn/trunk/patches.

4. All required beans are defined inside spring file:


<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<!-- dynamo-test.xml -->

<beans>
<!-- Enables spring-scripting. -->
<bean class="org.springframework.scripting.support.ScriptFactoryPostProcessor"/>

<!-- Creates cat. -->
<bean id="cat" class="org.springframework.scripting.groovy.GroovyScriptFactory">
<constructor-arg value="file:Cat.groovy" />
</bean>

<!-- Creates dog. -->
<bean id="dog" class="org.springframework.scripting.jruby.JRubyScriptFactory">
<constructor-arg value="file:Dog.ruby" />
<constructor-arg value="Animal" />
</bean>

<!-- Creates cow. -->
<bean id="cow" class="org.springframework.scripting.bsh.BshScriptFactory">
<constructor-arg value="file:Cow.bsh" />
<constructor-arg value="Animal" />
</bean>

<!-- Creates animal farm. -->
<bean id="farm" class="AnimalFarm">
<property name="animals">
<list>
<ref bean="cat"/>
<ref bean="dog"/>
<ref bean="cow"/>
</list>
</property>
</bean>
</beans>


5. The trickiest part here is how to avoid compilation of java code, making code
completely dynamic. To achieve it, we use janino library (http://www.janino.net/)
with JavaSourceClassLoader. We load class from source file, retrieve it as array of bytes
and then add this array as a class to our class loader.

To load required classes/libraries to CLASSPATH we use Scriptlandia API (http://scriptlandia.sf.net).
The complete example is represented below:


// dynamo-test.bsh

org.sf.scriptlandia.ScriptlandiaHelper.addMavenDependencies("pom.xml");

import org.sf.scriptlandia.launcher.ScriptlandiaLauncher;
import org.codehaus.janino.*;

import org.sf.scriptlandia.util.*;
import org.codehaus.classworlds.ClassRealm;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;


public class Dynamo {
private ClassRealm classRealm;
private ApplicationContext factory;

public Dynamo(String basedir, String[] classNames, String beansFile) {
ScriptlandiaLauncher launcher = ScriptlandiaLauncher.getInstance();

classRealm = launcher.getMainRealm();

register(basedir, classNames);

factory = new FileSystemXmlApplicationContext(new String[] { basedir + "/" + beansFile });
}

private void register(String basedir, String[] classNames) {
ScriptlandiaLauncher launcher = ScriptlandiaLauncher.getInstance();

ClassLoader sourceClassloader = new JavaSourceClassLoader(
launcher.getClass().getClassLoader(), // parentClassLoader
new File[] { new File(basedir) }, // optionalSourcePath
(String) null, // optionalCharacterEncoding
DebuggingInformation.NONE // debuggingInformation
);

for(int i=0; i < classNames.length; i++) {
loadClass(classNames[i], sourceClassloader);
}
}

/**
* Loads class specified by the name.
*/
private void loadClass(String name, ClassLoader classLoader) {
String[] args = new String[] { name };

Map bytecodes = ReflectionUtil.invokePrivateMethod(
classLoader,
new Object[] { name },
JavaSourceClassLoader.class,
"generateBytecodes",
new Class[] { String.class });

classRealm.addConstituent(name, bytecodes.get(name));
}

public Object getBean(String beanName) {
return factory.getBean(beanName);
}

public static void main(String[] args) throws Exception {
// Java classes that needs to be registered.
String[] classNames = new String[] {"Animal", "AnimalFarm" };
String basedir = System.getProperty("user.dir");

Dynamo dynamo = new Dynamo(basedir, classNames, "dynamo-test.xml");

AnimalFarm animalFarm = dynamo.getBean("farm");

animalFarm.wakeUp();
}

}

38 comments:

Anonymous said...

Thanks for the nice post!

Anonymous said...

Do you like playing the game where you need to use maple mesos, when you do not have
mesos, you must borrow
cheap mesos from friends, or you buy
maplestory mesos. If you get
maple story mesos, you can continue this game.
Do you like playing in the game where you need to use runescape gold, when you do not buy runescape, you must borrowrs gold from friends, or you get runescape money. If you get cheap rs gold, you can continue this game.

Anonymous said...

can you attach working project file to this post or file hosting site url where working project is stored.

Anonymous said...

Hi !.
might , probably curious to know how one can make real money .
There is no need to invest much at first. You may begin earning with as small sum of money as 20-100 dollars.

AimTrust is what you thought of all the time
The company incorporates an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

It is based in Panama with affiliates everywhere: In USA, Canada, Cyprus.
Do you want to become really rich in short time?
That`s your choice That`s what you desire!

I feel good, I began to get income with the help of this company,
and I invite you to do the same. If it gets down to select a correct companion utilizes your savings in a right way - that`s the AimTrust!.
I take now up to 2G every day, and my first investment was 500 dollars only!
It`s easy to start , just click this link http://uqykyhehux.1accesshost.com/irywywe.html
and lucky you`re! Let`s take this option together to feel the smell of real money

Anonymous said...

[url=http://bariossetos.net/][img]http://hopresovees.net/img-add/euro2.jpg[/img][/url]
[b]buying softwares, [url=http://hopresovees.net/]discount software office 2007[/url]
[url=http://vonmertoes.net/][/url] want to buy software accounting software for sale
free kaspersky [url=http://bariossetos.net/]game software stores[/url] trial adobe photoshop cs3
[url=http://hopresovees.net/]i buy computer software[/url] cheap cs3 software
[url=http://bariossetos.net/]free adobe photoshop cs3 styles[/url] glass shop software
pdf to autocad [url=http://hopresovees.net/]adobe photoshop cs4 tutorials[/b]

Anonymous said...

Good day !.
might , perhaps curious to know how one can make real money .
There is no need to invest much at first. You may commense earning with as small sum of money as 20-100 dollars.

AimTrust is what you need
AimTrust represents an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

Its head office is in Panama with offices everywhere: In USA, Canada, Cyprus.
Do you want to become an affluent person?
That`s your chance That`s what you wish in the long run!

I feel good, I began to get real money with the help of this company,
and I invite you to do the same. It`s all about how to select a proper partner utilizes your funds in a right way - that`s AimTrust!.
I earn US$2,000 per day, and my first deposit was 1 grand only!
It`s easy to join , just click this link http://ajinilam.arcadepages.com/kivexa.html
and go! Let`s take our chance together to feel the smell of real money

Anonymous said...

Hi !.
might , perhaps very interested to know how one can reach 2000 per day of income .
There is no initial capital needed You may commense to receive yields with as small sum of money as 20-100 dollars.

AimTrust is what you haven`t ever dreamt of such a chance to become rich
AimTrust represents an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

It is based in Panama with affiliates everywhere: In USA, Canada, Cyprus.
Do you want to become really rich in short time?
That`s your chance That`s what you desire!

I feel good, I started to take up real money with the help of this company,
and I invite you to do the same. It`s all about how to choose a correct companion who uses your money in a right way - that`s AimTrust!.
I make 2G daily, and what I started with was a funny sum of 500 bucks!
It`s easy to start , just click this link http://ehawipew.kogaryu.com/jupyru.html
and go! Let`s take our chance together to get rid of nastiness of the life

Anonymous said...

Hi!
You may probably be very curious to know how one can manage to receive high yields on investments.
There is no initial capital needed.
You may commense to get income with a money that usually goes
for daily food, that's 20-100 dollars.
I have been participating in one company's work for several years,
and I'm ready to let you know my secrets at my blog.

Please visit blog and send me private message to get the info.

P.S. I earn 1000-2000 per day now.

http://theblogmoney.com

Anonymous said...

Hi!
You may probably be very curious to know how one can make real money on investments.
There is no need to invest much at first.
You may commense earning with a money that usually goes
for daily food, that's 20-100 dollars.
I have been participating in one project for several years,
and I'm ready to share my secrets at my blog.

Please visit blog and send me private message to get the info.

P.S. I earn 1000-2000 per daily now.

[url=http://theinvestblog.com] Online investment blog[/url]

Anonymous said...

I am the kind of guy who passions to taste revolutionary stuff. Right now I am building my personal pv panels. I'm managing it all alone without the help of my men. I'm using the net as the only way to acheive this. I encountered a truly brilliant site which explains how to make photovoltaic panels and so on. The internet site explains all the steps required to building pv panels.

I am not sure about how precise the data given there iz. If some experts over here who have experience with these things can have a look and give your feedback in the site it will be great and I'd extremely appreciate it, cause I truly lav solar panel construction.

Tnx for reading this. You guys rock.

Anonymous said...

The author of scriptlandia.blogspot.com has written an excellent article. You have made your point and there is not much to argue about. It is like the following universal truth that you can not argue with: There's more that 5 ways to skin a cat, but less than 3 reasons to want to. Thanks for the info.

Anonymous said...

Nice story you got here. It would be great to read more about this matter. Thank you for giving that data.

Anonymous said...

Good dispatch and this mail helped me alot in my college assignement. Say thank you you on your information.

Anonymous said...

Amiable brief and this enter helped me alot in my college assignement. Thanks you as your information.

Anonymous said...

Good post and this enter helped me alot in my college assignement. Gratefulness you as your information.

Anonymous said...

scriptlandia.blogspot.com is the best. Thank your for this article. I enjoyed it very much.
AAA Toronto Payday Loans 1172 Bay St #101, Toronto, ON M5S 2B4 (416) 477-2817

propecia said...

this kind of topic is good for people to learn more about it, and that people should be every day less ignorant, and medicine for this is the reading of issues like this

Anonymous said...

I consider, that you are not right. I am assured. I suggest it to discuss. Write to me in PM, we will communicate.

Anonymous said...

This phrase is simply matchless ;)

Invertir en oro said...

hello, i think that this post is the best that i have read.

4d ultrasounds said...

Anyway thanks a lot one more time for the great and informative publication.

organic supplements said...

Almost people like to write what he said, But I like to listen what they said, Your post is very good. Thanks!

Classified Ads Rajasthan said...

i have read your blog and find that your articles are amazing, i have added this into my bookmark. Thanks a lot.

Unknown said...

My love is like the grasses Hidden in the deep mountains.
Though its abundance increase, There is hiehwfdh none that knows.
Wholesale New Era Hats
Cheap 59fifty Hats
Cheap New Era Hats
New Era Snapback Hats
New Era Fitted Hats

hosted virtual call center said...

This is highly informatics, I've joined your feed and look forward to seeking more of your magnificent post. Also, I have shared your site in my social networks!Thanks for writing the pattern.

Anonymous said...

four bases of dating http://loveepicentre.com/faq.php deutschland dating singles

Anonymous said...

engineering ebook free download http://audiobookscollection.co.uk/Network-Administration/c2157/ first flight chris clarmont ebook [url=http://audiobookscollection.co.uk/es/Derecho-Penal/c1144/]29.00 ebook biz on ebay[/url] free ebook downlaod

Anonymous said...

iphone ebook source http://audiobookscollection.co.uk/Rockin-the-Rockpile-The-Buffalo-Bills-of-the-American-Football-League/p155732/ percy jackson ebook torrent download [url=http://audiobookscollection.co.uk/de/Essentials-of-Managing-Corporate-Cash/p104265/]how to make best friends ebook[/url] free ebook australia

Anonymous said...

the awakening ebook http://audiobooksplanet.co.uk/Comprehensive-Review-of-Headache-Medicine/p169473/ robert bruce energy work ebook [url=http://audiobooksplanet.co.uk/fr/H-W-Spiess/m46942/]medusa cussler ebook download[/url] ebooks check in check in ebook

Anonymous said...

best software of 2008 http://buyoem.co.uk/fr/product-14026/Crossword-Forge-5-1-Mac what is the definition of software [url=http://buyoem.co.uk/product-35117/YoGen-Recorder-3-5]girling health care software[/url] open source wiki server software
[url=http://buyoem.co.uk/fr/product-24957/Adobe-Master-Collection-CS4-Mac]Adobe Master Collection CS4 [Mac] - Cheap Legal OEM Software, Software Sale, Download OEM[/url] what is altiris software used for
[url=http://buyoem.co.uk/product-11710/Apple-iWork-06-Mac][img]http://buyoem.co.uk/image/7.gif[/img][/url]

Anonymous said...

tecnicas de mantenimiento de software http://buyoem.co.uk/fr/product-37121/MaxDB-Data-Wizard-7-8 similar software to record toolbar [url=http://buyoem.co.uk/fr/product-34200/Electric-Rain-Swift-3D-PS-1-0-x64]order takeing software[/url] durable medical supply billing software
[url=http://buyoem.co.uk/product-37319/Ultra-Mobile-3GP-Video-Converter-3-0]Ultra Mobile 3GP Video Converter 3.0 - Software Store[/url] best photo filters software
[url=http://buyoem.co.uk/it/product-36750/Argus-Monitor-2-0][img]http://buyoem.co.uk/image/2.gif[/img][/url]

Anonymous said...

order computer software http://buyoem.co.uk/it/product-14870/SpaceObServer-3-0 ostia 2003 software [url=http://buyoem.co.uk/product-33580/Primasoft-Contact-Organizer-Pro-2-4]what is cam software[/url] bill gates first software sale
[url=http://buyoem.co.uk/product-37370/Absolute-Audio-Converter-4-1-Portable]Absolute Audio Converter 4.1 Portable - Software Store[/url] symantec ghost imaging software download
[url=http://buyoem.co.uk/de/product-36919/WaterProof-PHPEdit-4-1][img]http://buyoem.co.uk/image/2.gif[/img][/url]

Anonymous said...

windows vista mp3 to audio software http://buysoftwareonline.co.uk/es/product-37123/PDF-Extract-TIFF-2-0 word marketing software [url=http://buysoftwareonline.co.uk/fr/product-35726/ColorWasher-2-0-for-Adobe-Photoshop]ad aware software 6 0[/url] memory card recovery software free
[url=http://buysoftwareonline.co.uk/category-200-203/Graphics-and-Publishing?page=4]Graphics & Publishing - Download OEM, Software Sale, OEM Software[/url] gps topo software for blackberry
[url=http://buysoftwareonline.co.uk/de/category-14/Anderes?page=2][img]http://buyoem.co.uk/image/1.gif[/img][/url]

Anonymous said...

[url=http://onlinemedistore.com/products/terramycin.htm][img]http://onlinemedistore.com/4.jpg[/img][/url]
joint submission pharmacy guild of australia pharmacy regulation http://onlinemedistore.com/products/noroxin.htm pharmacy in kc [url=http://onlinemedistore.com/products/albendazole.htm]pelam pharmacy in massachusetts[/url]
university of colorado pharmacy program http://onlinemedistore.com/products/depakote.htm costco pharmacy prices [url=http://onlinemedistore.com/products/remeron.htm]remeron[/url]
highland regent pharmacy http://onlinemedistore.com/products/myambutol.htm pharmacy journal rss feed [url=http://onlinemedistore.com/products/floxin.htm]pharmacy tech nationwide[/url]
argus pharmacy benefits http://onlinemedistore.com/products/paxil.htm cattle pharmacy australia [url=http://onlinemedistore.com/products/levaquin.htm]levaquin[/url]

Anonymous said...

[url=http://onlinemedistore.com/products/activ8--energy-booster-.htm][img]http://onlinemedistore.com/5.jpg[/img][/url]
va pharmacy long beach http://onlinemedistore.com/products/omnicef.htm quality market pharmacy [url=http://onlinemedistore.com/products/viagrx.htm]pharmacy news colorado[/url]
pharmacy techn ok jobs http://onlinemedistore.com/products/mentat.htm university pharmacy australian national university [url=http://onlinemedistore.com/products/yasmin.htm]yasmin[/url]
pharmacy or education http://onlinemedistore.com/products/prazosin.htm avoid the middle man pharmacy [url=http://onlinemedistore.com/products/prevacid.htm]online pharmacy school program[/url]
pharmacy benefit managers http://onlinemedistore.com/products/entocort.htm greenspoint pharmacy [url=http://onlinemedistore.com/products/retin-a-0-05-.htm]retin a 0 05 [/url]

Anonymous said...

[url=http://englandpharmacy.co.uk/products/flovent.htm][img]http://onlinemedistore.com/8.jpg[/img][/url]
rutgers pharmacy school http://englandpharmacy.co.uk/products/effexor-xr.htm affiliate marketing pharmacy marketing program [url=http://englandpharmacy.co.uk/products/pletal.htm]montana pharmacy school[/url]
juarez pharmacy http://englandpharmacy.co.uk/products/voltaren.htm tower online pharmacy [url=http://englandpharmacy.co.uk/products/ventolin.htm]ventolin[/url]
cornerstone pharmacy http://englandpharmacy.co.uk/products/flovent.htm advantages being a pharmacy lawyer [url=http://englandpharmacy.co.uk/products/evista.htm]milinnium pharmacy[/url]
anthem online pharmacy indiana http://englandpharmacy.co.uk/products/erectalis.htm pharmacy benefit manager anovian [url=http://englandpharmacy.co.uk/products/cephalexin.htm]cephalexin[/url]

Anonymous said...

[url=http://englandpharmacy.co.uk/terms.htm][img]http://onlinemedistore.com/6.jpg[/img][/url]
university pharmacy salt lake http://englandpharmacy.co.uk/products/ceftin.htm online pharmacy tramadol pharmacy prilosec [url=http://englandpharmacy.co.uk/products/entocort.htm]aurora pharmacy 53005[/url]
ks laws pharmacy tech http://englandpharmacy.co.uk/products/aciphex.htm monticello pharmacy daffron [url=http://englandpharmacy.co.uk/products/zovirax.htm]zovirax[/url]
ultram pharmacy http://englandpharmacy.co.uk/products/serevent.htm canada job pharmacy technician [url=http://englandpharmacy.co.uk/products/zelnorm.htm]green pharmacy[/url]
arthurs pharmacy university http://englandpharmacy.co.uk/products/cytoxan.htm hydrocodone online pharmacy [url=http://englandpharmacy.co.uk/products/kamagra.htm]kamagra[/url]

Anonymous said...

regional dating http://loveepicentre.com/taketour/ rome italy dating
girls dating [url=http://loveepicentre.com/testimonials/]dating for freshman in highschool[/url] black women dating on line
dating free game hentai [url=http://loveepicentre.com/testimonials/]asian women site dating love chat[/url] new free dating website [url=http://loveepicentre.com/user/Rahulsinha22/]Rahulsinha22[/url] dating personels