In this post I want to discuss how runtime class reloading can be done in java using user defined class loaders. The following is a simple example that demonstrates how classes can be reloaded at runtime in Java. This is done using a different user defined class loader than that originally loaded the class. The following two java classes should be on the classpath of the java command.
package com;
import java.io.*;
import java.net.*;
public class TestReload {
private TestClass reload() {
URL[] urls = null;
try {
// Convert the file object to a URL
File dir = new File("C:\\programs\\projects\\");
URL url = dir.toURL(); // file:/c:/almanac1.4/examples/
System.out.println(url);
Runtime.getRuntime().exec("javac C:\\programs\\projects\\com\\*.java");
urls = new URL[]{url};
} catch (Exception e) {
e.printStackTrace();
}
try {
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("com.TestClassImpl");
return (TestClass) cls.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] argsv) {
System.out.println("sys out");
TestReload testReload = new TestReload();
while (true) {
System.out.println(testReload.reload().getMessage());
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// Test class the implementation of this class will be out side of class path
package com;
public interface TestClass {
public String getMessage();
}
Now place the TestClass and TestClassImpl in a path other than the java class path and compile them. Now run the original TestReload and change the message, you will see the changes picked up at run-time :). Bear in mind that I chose not have the class to be reloaded specifically in class path to avoid confusion. This is perfectly acceptable and two different class loaders can load same class.
package com;
public class TestClassImpl implements TestClass {
public String getMessage() {
return "Change me";
}
}
Grails development is breeze with runtime class reloading for controllers, domain and service classes etc at run time. JavaRebel is a promising tool that enables this functionality to java users and is a great productivity gain. This tool uses class instrumentation and java agents to achieve run-time class loading that is more efficient and faster.
Resources:
http://mindprod.com/jgloss/reloading.html
http://www.exampledepot.com/egs/java.lang/ReloadClass.html
Posted by satish on August 25, 2009 at 1:03 pm under Grails, Java.
1 Comment.
I have recently switched from bash to zsh. zsh has nice command completion and it also suggests command if you mistype. Mac OS-X comes with zsh installed, to switch to zsh go to system preferences -> accounts, right click on the account select advanced options and select zsh for login shell. Also along the way I picked up a new command, its the bang command I would like to share, bare in mind this is not unique to zsh and is also available in bash. Have fun programming :).
!! - To run last executed command
!$ - Last argument of previous command
!* - All arguments
!!:1 - First argument
References
http://www.zsh.org/
http://vafer.org/blog/20070103101542
Posted by satish on August 3, 2009 at 9:45 pm under Ruby.
Tags: bash, zsh.
2 Comments.
Recently I had to switch to newer java version on my Mac. Turns out it is not straight forward so I put together some notes that would help others. Usually java command is located in /usr/bin/java on Mac. This is a symbolic link to java command in one of the java versions installed on your computer. To change your java version. use the following commands.
cd /usr/bin
sudo rm java
sudo ln -s /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Commands/java java
Now try java -version… you should see
java version "1.6.0_07"
Java(TM) SE Runtime Environment (build 1.6.0_07-b06-153)
Java HotSpot(TM) 64-Bit Server VM (build 1.6.0_07-b06-57, mixed mode)
Posted by satish on July 25, 2009 at 7:18 pm under Java, Mac OS X.
Comment on this post.
I have spent some time over the weekend on javarebel from Zeroturnaround guys. I have to say I am quite impressed and it is a must tool for all the java developers. It greatly reduces development time and I bet tools like these will soon become a de facto in development environments. The tool allows to load/replace classes at run-time, no need for server restarts if you are doing web-development :).
Posted by satish on July 12, 2009 at 10:12 pm under Java.
Comment on this post.
This is part-1 in a series of tutorials about meta-programming in Groovy. Groovy provides excellent hooks for extending behavior of classes and objects at run-time. First, what is meta-programming? Meta-programming means writing programs that write programs. What this means is that programs are open for either modification or extention at any time during the process of compilation or runtime. Meta-programming allows you to write efficient programs that change behavior dynamically based on needs or input from the environment. Groovy accomplishes this using MOP(Meta Object Protocol). Groovy provides categories, meta-classes, exapandos, mixins, annotations etc. to accomplish this. First in this part I will discuss categories.
1) Categories - Categories allow methods to be added dynamically on any object. Let’s see the following example. In this example I have a StringUtil class that has method capitalize which capitalizes each word in a string.
def hello = "hello world HELLO WORLD"
class StringUtil {
static String capitalize(String self) {
return self.split(" ").collect { it[0].toUpperCase() + it[1..-1].toLowerCase()}.join(" ")
}
}
use(StringUtil) {
println hello.capitalize()
}
// prints "Hello World Hello World"
Lets see what is happening here Use is a method on class Object. Use accepts a class and closure as arguments. All the objects with in the closure will have access to the methods on the category class, in this case StringUtil. Groovy accomplishes this by providing a fresh list of properties and methods of the category class on the stack. These are the different ways Use can be used. This is taken from groovy jdk API.
use(Class categoryClass, Closure closure)
Scoped use method
use(List categoryClassList, Closure closure)
Scoped use method with list of categories
use(Object[] array)
Allows you to use a list of categories, specifying the list as varargs use(CategoryClass1, CategoryClass2) { This method saves having to wrap the the category classes in a list
Since groovy 1.6 is official now, groovy now provides compile time meta-programming using AST(Abstract Syntax Tree). Using this Categories can be created using @Category annotations. to be contd..
Posted by satish on April 15, 2009 at 8:11 pm under Ruby.
1 Comment.
Here is a small sample code I wrote that shows object serialization in groovy. when I ran this directly in groovy shell it did not work off the bat. I had to move the class Name to separate file Name.groovy and make sure it is in the class-path to work. Here is the link to original discussion on groovy forum.
// put this in a file named Name.groovy and compile using groovyc
class Name implements Serializable {
def fname, lname
}
// Now run the code below to see the Object serialization and de-serialization.
def test1= new Name(fname: "fn1", lname : "ln1")
def test2 = new Name(fname: "fn2", lname: "ln2")
//serialization
new File("C:/config.txt").withObjectOutputStream { out ->
out << test1
out << test2
}
//de-serialization
new File("C:/config.txt").withObjectInputStream { instream ->
instream.eachObject {
println it
}
}
Posted by satish on January 31, 2009 at 1:25 pm under Groovy, dynamic languages.
Tags: Groovy, Serializaton
4 Comments.
All controller actions in grails magically have access to request, params, session and bunch of other utility methods such as redirect, render etc. I digged through the grails source to find how it is done. The functionality is added to controller meta-classes utilizing groovy’s meta-programming capabilities. It is written as a plugin where in all the controller meta-classes are attached the functionality we all see. Here is the portion of code that adds some functionality. Imagine writing an action/controller in conventional j2ee style, this small portion of elegant code gets rid of all the boiler plate repetitive code. This simple example shows the power of meta programming. Kudos to all the contributors for this excellent project.
/*
The method below is called for controller meta classes. and RCH is the RequestContenxtHolder from spring MVC
import org.springframework.web.context.request.RequestContextHolder as RCH
*/
def registerCommonWebProperties(MetaClass mc, GrailsApplication application) {
def paramsObject = {->
RCH.currentRequestAttributes().params
}
def flashObject = {->
RCH.currentRequestAttributes().flashScope
}
def sessionObject = {->
RCH.currentRequestAttributes().session
}
def requestObject = {->
RCH.currentRequestAttributes().currentRequest
}
def responseObject = {->
RCH.currentRequestAttributes().currentResponse
}
def servletContextObject = {->
RCH.currentRequestAttributes().servletContext
}
def grailsAttrsObject = {->
RCH.currentRequestAttributes().attributes
}
// the params object
mc.getParams = paramsObject
// the flash object
mc.getFlash = flashObject
// the session object
mc.getSession = sessionObject
// the request object
mc.getRequest = requestObject
// the servlet context
mc.getServletContext = servletContextObject
// the response object
mc.getResponse = responseObject
// The GrailsApplicationAttributes object
mc.getGrailsAttributes = grailsAttrsObject
// The GrailsApplication object
mc.getGrailsApplication = {-> RCH.currentRequestAttributes().attributes.grailsApplication }
mc.getActionName = {->
RCH.currentRequestAttributes().actionName
}
mc.getControllerName = {->
RCH.currentRequestAttributes().controllerName
}
}
}
Posted by satish on January 3, 2009 at 10:00 pm under Grails, Groovy, meta programming.
Tags: Grails, Groovy, Metaclass
2 Comments.
Posted by satish on December 14, 2008 at 11:18 am under Ruby, conf.
Comment on this post.
To make acegi grails plugin work for case insensitive user-names, I used the following code snippet to override/redefine the loadDomainUser method. I put this in bootstrap and it worked like a gem.
Note: there are other methods in GrailsDaoImpl that need to be redefined if you use them.
GrailsDaoImpl.metaClass.loadDomainUser = { username, session ->
def clazz = Class.forName(loginUserDomainClass, true, new GroovyClassLoader())
def crit = clazz.createCriteria()
def users = crit.list {
ilike(usernameFieldName, username)
}
if (users.empty) {
logger.error("User not found: ${username}")
throw new UsernameNotFoundException("User not found.", username)
}
return users[0]
}
Posted by satish on December 4, 2008 at 6:22 pm under Ruby.
Comment on this post.
jQuery datepicker adds a new attribute to the DOM element in IE. if you try to add a new DOM element dynamically copying from an existing element the datepicker will not work in IE as the newly added DOM element refers to the old jQuery attribute. One way to fix this is to delete the attribute and then instantiate the datepicker class on the element. See the following code for the fix.
//newDiv is the new added dom element with innerHTML
jQuery("#newDiv").find(".datePicker").each(function() {
//removing jquery added attribute as this is causing the dynamically
// added DOM elem referring old DOM element from it is copied.
if (jQuery.browser.msie) {
var jqaddedattr;
jQuery(this.attributes).each(function() {
if (this.name.search(/jQuery/) != -1) {
jqaddedattr = this;
}
});
if (jqaddedattr) {
jQuery(this).removeAttr(jqaddedattr.name);
}
}
jQuery(this).datepicker({yearRange: '-100:+10', changeFirstDay:false}).val("").trigger('change');
})
Posted by satish on November 11, 2008 at 4:35 pm under Ruby.
9 Comments.