Technical Musings !!

Kamlesh's learning and rendezvous with the technical world

What is Monkey Patching?

leave a comment »

I came across this buzz word while I was reading something on unit testing. The concept is not new but the term is new for me. Monkey Patching is a term mostly used in context of Python and unit testing. This means modifying the code in a dynamic programming language at run time without affecting the source code.

Please refer the following wiki page for details about Monkey Patch.

Monkey Patch

Do share and comment about similar buzz words you know of in Software Development.

Enjoy Learning,

Kamlesh

Written by Kamlesh

July 15, 2014 at 10:25 AM

Add/Update a Class File in a Jar

with 3 comments

Updating a class file directly in a jar comes very handy when you are working on a remote server and you need to update some classes in your deployed jar file. With update feature of the jar command, we can directly update the selective classes in the jar rather than building and moving the jar file itself to the remote server.

Let us assume we have abc.jar and we need to update the file Foo.class in the jar. Foo.class is in the package com.tm.example.

In order to update the jar we need to create a directory structure reflecting the package structure of the class which we need to replace and place the class there. In this case we need to place the class, Foo.class, in the directory com/tm/example. Also, let us keep the directory com is on the same level as that of abc.jar.

Now we can execute the following command to update the class file into the jar file.

        jar uf abc.jar com/tm/example/Foo.class

The above command works for both Linux and Windows.

Please note if we do not provide the directory structure and try to add the class like

        jar uf abc.jar Foo.class

this will add the Foo.class in the jar on the root level.

In case we need to add/update multiple files in jar, we can do it by separating the file name with spaces like:

        jar uf abc.jar com/tm/example/Foo.class com/rm/example/another/Bar.class

For more details visit this java tutorial.

Enjoy Learning,
Kamlesh

Written by Kamlesh

December 26, 2013 at 3:47 PM

Posted in JAVA, LINUX

Tagged with , , ,

AspectJ: Applying Advice to Methods Based on an Annotation

with 3 comments

I am new to AspectJ (not new to AOP though) and have been recently doing some R&D on using AspectJ for intercepting methods annotated with an annotation.

What I Tried …
Use AspectJ to intercept all the public methods (belonging to classes of specified packages) based on an annotation applied.

What I Needed …
Aspect J Development Tool plugin for eclipse. [equipped my eclipse 3.7 with AJDT plugin]
Searched for AspectJ getting started tutorials available on the internet. [Visit this link  for a good AspectJ getting started tutorial]
Searched how to write a pointcut for intercepting a method based on annotation.

This is how I did it …

Created a simple annotation named MyAnnotation.

MyAnnotation.java

package com.technicalmusings.examples.aspectj.annotation;

public @interface MyAnnotation {}


Created three classes Hello1, Hello2 and Hello3 having public and private methods annotated with MyAnnotation. The intent was to apply a before advice to all the public methods (annotated with MyAnnotation) present in the package com.technicalmusings.examples and its sub-packages. Therefore these three classes have been kept in three different packages. Please refer to the class organization in the screenshot below:

AspectJProjectOrganization

Hello1 class has a method without annotation as well to ensure that the pointcuts are doing exactly what they are supposed to.

Hello1.java

package com.technicalmusings.examples.hello1;
import com.technicalmusings.examples.aspectj.annotation.MyAnnotation;

public class Hello1 {

    public static void main(String[] args) {
        methodOfHello1WithoutAnnotation();
        greetPubliclyFromHello1();
    }

    public static void methodOfHello1WithoutAnnotation() {
        System.out.println("Greetings from a method without annotation from Hello1 class!");
    }

    @MyAnnotation
    public static void greetPubliclyFromHello1() {
        System.out.println("Greetings from public method of Hello1 class!");
    }
}


Hello2.java

package com.technicalmusings.examples.aspectj.hello2;
import com.technicalmusings.examples.aspectj.annotation.MyAnnotation;

public class Hello2 {

    public static void main(String[] args) {
        greetPubliclyFromHello2();
        greetPrivatelyFromHello2();
    }

    @MyAnnotation
    public static void greetPubliclyFromHello2() {
        System.out.println("Greetings from public method of Hello2 class!");
    }

    @MyAnnotation
    private static void greetPrivatelyFromHello2() {
        System.out.println("Greetings from private method of Hello2 class!");
    }
}

Hello3.java

package com.technicalmusings.partofexamples;
import com.technicalmusings.examples.aspectj.annotation.MyAnnotation;

public class Hello3 {

    public static void main(String[] args) {
        greetPrivatelyFromHello3();
        greetPubliclyFromHello3();
    }

    @MyAnnotation
    public static void greetPubliclyFromHello3() {
        System.out.println("Greetings from public method of Hello3 class!");
    }

    @MyAnnotation
    private static void greetPrivatelyFromHello3() {
        System.out.println("Greetings from private method of Hello3 class!");
    }
}

Now the important part, the AspectJ stuff…

Created an aspect, HelloAspect, with one after advice and one before advice (just to differentiate between the two scenario)
a) The after advice is applied to all the methods annotated with MyAnnotation (irrespective of package)
b) The before advice is applied to all the mehods anotated with MyAnnotation belonging to classes of specified package or subpackages

HelloAspect.aj

package com.technicalmusings.examples;

public aspect HelloAspect {

    // Pointcut for all public methods
    pointcut publicPointcut(): execution(public * *(..));

    // Pointcut for all the methods with the specified annotation
    pointcut annotationPointcutAll()
        : execution(@com.technicalmusings.examples.aspectj.annotation.MyAnnotation * *(..));

    // Pointcut for all the methods with the specified annotation within specified package
    pointcut annotationPointcutPackage()
        : execution( @com.technicalmusings.examples.aspectj.annotation.MyAnnotation
         * com.technicalmusings.examples..*(..));

    after() : annotationPointcutAll() && publicPointcut() {
        System.out.println("annotationPointcutAll: Intercepted the after call of : " 
        + thisJoinPoint.getSignature());
    }

    before() : annotationPointcutPackage() && publicPointcut() {
        System.out.println("annotationPointcutPackage: Intercepted the before call of : "
        + thisJoinPoint.getSignature());
    }
}

By executing the classes Hello1, Hello2 and Hello3 individually, we can see how the advices are being applied. The after advice which does not have the package filter should include the method of Hello3 class whereas the other should not.

Below snapshot from ‘Cross References’ view of eclipse shows how the HelloAspect is advising the methods.

HelloAdvice

Enjoy Learning,
Kamlesh

Written by Kamlesh

May 10, 2013 at 10:34 PM

String Utility Classes in Java

leave a comment »

Manipulating strings is a part and parcel of a programmer’s day to day life. There are many string related operations which we use quite often. Some of the string operations are provided by Java (classes like String, StringBuilder etc.) and some we devise ourselves. For example, as a good practice the first thing we do while working with string is to check it for null and emptiness as shown below:

if (myString != null || !"".equals(myString)) {
// work with myString
}

For the above and some other frequently used cases of string manipulation we can use the string utility classes already provided by the third party libraries. The string utility class available in apache commons project, org.apache.commons.lang3.StringUtils, is one of the widely used string utility classes. This class has many utility methods which take care of commonly used string operations and most of these are null safe.

For example we can use the isBlank, isNotBlank methods from the StringUtils class to validate the string for empty and null as shown below:

if(StringUtils.isNotBlank(myString)) {
//work with myString
}

The java documentation of the StringUtils.isBlank method says:

public static boolean isBlank(CharSequence cs)
Checks if a CharSequence is whitespace, empty ("") or null.

StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false

Based on requirements we can also consider using isEmpty and isNotEmpty.

You can check the API documentation of org.apache.commons.lang3.StringUtils and have a look on other utility methods it provides.

If you are already using Spring framework in your application, you can consider using the StringUtils class available in Spring Framework for the utility methods it provides. This class has been mainly used inside Spring Framework but as it is available, we can use this. Some of the methods I liked from this class are:

// Convert an array or a collection to a comma delimited string (say, for creating a csv file) and vice versa
public static java.lang.String arrayToCommaDelimitedString(java.lang.Object[] arr)
public static java.lang.String[] commaDelimitedListToStringArray(java.lang.String str)

public static java.lang.String collectionToCommaDelimitedString(java.util.Collection<?> coll)
public static java.util.Set<java.lang.String> commaDelimitedListToSet(java.lang.String str)

//Trim an array of strings
public static java.lang.String[] trimArrayElements(java.lang.String[] array)

For more information on Spring Framework’s StringUtil class, check it’s API documentation.

Enjoy Learning,
Kamlesh

Written by Kamlesh

May 7, 2013 at 3:53 PM

JSP: Problem Using Spring Message with JSTL

with 5 comments

Couple of days back I was trying to externalize the labels and messages in a JSP file to a property file. As I was using Spring MVC, decided to use <spring:message> tag to achieve this. Everything else worked fine except when I used <spring:message> tag as a value attribute of <c:set>. Albeit it sounds very simple, I had to spend some time finding out the way. And hence considering this a candidate for my blog.

Problem:

Unable to use <spring:message> tag with the JSTL  <c:set> tag like below:

<c:set var=”someVar” value=”<spring:message code=’some.value’/>” />

Solution:
Nest the <spring:message> tag in the JSTL tag.

<c:set var=”someVar”>
<spring:message code=”some.value”/>
</c:set>

Enjoy Learning,
Kamlesh

Written by Kamlesh

November 26, 2011 at 6:44 AM

Posted in spring

Tagged with , , , ,

Inside Java: Concurrent modification when using collection and iterator

with 3 comments

ConcurrentModificationException may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible. This exception is encountered more often in case of collections when one thread is iterating over the collection and other tries to modify it.

This article explains how java detects concurrent modifications to a List with the help of an example. The comments provided along with the code are self explanatory so let us go through the example first:

ConcurrentModificationTest.java

package com.technicalmusings.examples.collection;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
* The class explains how concurrent modification is detected in List.
*/

public class ConcurrentModificationTest {

public static void main(String[] args) {

// Instantiating the list sets the modCount field of list to 0
// modCount is a protected integer variable defined in the AbstractList class.

List<Object> myList = new LinkedList<Object>();

myList.add(new Object()); // modCount incremented to 1
myList.add(new Object()); // modCount incremented to 2
myList.add(new Object()); // modCount incremented to 3

// Getting an iterator sets the value of expectedModCount field
// equal to that of the modCount field of list.

Iterator<Object> itr1 = myList.iterator(); //itr1: expectedModCount = 3
Iterator<Object> itr2 = myList.iterator(); //itr2: expectedModCount = 3

// The first Iterator traverses the list once
itr1.next();

// The second iterator traverses and removes the first element
itr2.next();
itr2.remove();
// In the previous step Itr2 modifies the list and sets the
// expectedModCount field to 4. The modCount field of the list
// has also been now incremented to 4

// The first iterator again tries to traverse the list
itr1.next();

// java.util.ConcurrentModificationException is thrown at this stage
// because itr1 finds its expectedModCount (which is still 3) to be not
// matching with the modCount field of the list
}
}

The ConcurrentModificationTest.java class shown above explains how java works behind the scenes to detect concurrent modification and throw the ConcurrentModificationException in case of a List. List has an integer field modCount, which is incremented each time a structural modification is done in the list. Structural modification includes methods like add, remove, clear etc. The Iterator on the other hand uses another integer field, expectedModCount, to take care of concurrent modifications in the list. Iterator expects both the variables modCount and expectedModCount to be the same. In case the list is modified by any other means the modCount and expectedModCount differs and the exception is thrown.

Written by Kamlesh

March 26, 2011 at 6:00 AM

Java Threads: Thread and Exception Handling

with 8 comments

Whenever an uncaught exception occurs in a thread’s run method we get a default exception dump which gets printed on System.err stream. We may not always want to live with this default behavior and might think about logging the exception message in a more sophisticated way or doing something else as per business requirement.

Such custom exception handling can be achieved using the UncaughtExceptionHandler interface of the Thread class. The ThreadGroup class also implements the Thread.UncaughtExceptionHandler interface. The interface has only one method defined, which is:

void uncaughtException(Thread t, Throwable e);

This handler interface is invoked when a thread abruptly terminates due to an uncaught exception. The below excerpt from Java documentation explains the UncaughtExceptionHandler interface:

When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler’s uncaughtException method, passing the thread and the exception as arguments. If a thread has not had its UncaughtExceptionHandler explicitly set, then its ThreadGroup object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special requirements for dealing with the exception, it can forward the invocation to the default uncaught exception handler.

Thread class has two methods viz. setDefaultUncaughtExceptionHandler() and setUncaughtExceptionHandler(). The setDefaultUncaughtExceptionHandler() which is a static method of Thread class can be used to provide a common exception handler for all the threads. On the other hand setUncaughtExceptionHandler() is a non static method of Thread class which is used to provide handler to a given thread.

The below example shows how to handle the uncaught exception thrown from a Thread:

MyThreadTest.java

package com.technicalmusings.examples.thread;

/**
* The below class creates a thread which is supposed to throw an exception.

* A handler is added to the thread before calling the start method of thread.
* When the thread executes the exception is handled by the handler
* and the custom exception message is displayed on the console.
*/

public class MyThreadTest {

public static void main(String[] args) {

Thread newThread = new Thread(new ThreadWithException());

// Add the handler to the thread object
newThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){

@Override
public void uncaughtException(Thread t, Throwable e) {

System.out.println("ERROR! An exception occurred in " + t.getName() + ". Cause: " + e.getMessage());
}
});

newThread.start();
}
}

/**
* This thread throws a custom exception in its run method.
*/

class ThreadWithException implements Runnable {

@Override
public void run() {
throw new RuntimeException("Application Specific Exception!!");
}
}

Output:

ERROR! An exception occurred in Thread-0. Cause: Application Specific Exception!!

Enjoy Learning,
Kamlesh

Written by Kamlesh

March 24, 2011 at 12:42 PM

Follow

Get every new post delivered to your Inbox.

Join 335 other followers