Posts

Showing posts from 2010

Pattern: How to start a thread of execution in Fantom

In Fantom, how do you start a new thread of execution? The pattern below is very simple and nice. const class Main { Void main() { svc := Actor(ActorPool()) { doSomething }.send(null) } Obj? doSomething() { // Do something like binding to a port and listening for requests. // Or you can call another method that does that. return null } } The code above might seem a little odd at first. All that it does is to create an Actor with a code block that will execute the doSomething method. By sending a dummy message (".send(null)"), the Actor instance is started. The key here is that sending a dummy message to an Actor starts the Actor. This same trick may be applicable to other Actor based languages as well.

Funny error message in YouTube

Image
Today I got this funny error message in YouTube.

Lazy initializing default values

One of the tasks you will come across often is to look up a value in a map, while providing a default value for the looked up value. For e.g. Properties prop = ... Object value = prop.get("key", "defaultValue") The issue with this pattern is that, what if arriving at default value is a costly operation. Even worse, there may be no need to compute the default value at all, may be because the get operation will always find a value in the properties. During such times "lazy evaluation" comes to the rescue. This is not a new pattern, it has been around for long time. Just that some APIs are written with lazy evaluation in mind, and some not. In the example above, instead of taking the value itself, if the get method takes an argument that is callable or a lambda function, then it can use that function only under the situation that the value is not present. The example below is from Fantom language when you attempt to get a value from a map. class M...

Initial thoughts on Fantom

Recently I started playing with Fantom language . So far my reaction is "Wow!". Its a beautiful language with a lot of cool things. I also ran into a few gotchas, but none that falls in the category of "ugly!". Here are the things I really liked about the language (not necessarily in any order): Before any technical merits, the first thing I liked is the documentation. Most of the time, when I look for some documentation for a open source project, they notoriously suck. Fantom is the second project whose documentation I really liked and found my way around most of the time. (The first one is SLF4J.) The language is statically typed, with room for dynamically invoking methods on objects using a mechanism called "trap". One central theme I observed in the language is being able to reliably create an immutable objects ("const" classes). This simplifies a lot of analysis when it comes to concurrent programming. Also the language supports cre...

SecretKeyFactory is broken in JDK 1.6 update 22

If you upgrade JDK to 1.6 update 22 (build 04), the SecretKeyFactory is broken. As a result you will not be able to load any PKCS12 key stores. You will get NoSuchAlgorithmException thrown. I have reported this issue in the bug database. You can view the bug here . I guess it will take upto a day for this bug to be externally visible, if you don't have a SDN account. Here is the sample program to reproduce the issue: public static void main(String[] args) { SecretKeyFactory instance = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); System.out.println("Returned instance: " + instance.getAlgorithm()); } You will get the exception below: Exception in thread "main" java.security.NoSuchAlgorithmException: PBEWithSHA1AndRC2_40 SecretKeyFactory not available at javax.crypto.SecretKeyFactory.<init>(DashoA13*..) at javax.crypto.SecretKeyFactory.getInstance(DashoA13*..) at main.TestClient.main(TestClient.java:96) Work ...

Performance of BigInteger.toString(radix)

Problem: You are given a byte array, that represents a number in big endian format (the most significant byte first). You have to convert the byte array to its equivalent hex string. What is the most efficient way to do it? Solution: There are many ways to do it. But let us start with the easiest and correct one and optimize our solution. BigInteger class provides a constructor to convert the byte array to a BigInteger. We can convert that BigInteger to a hex string using the BigInteger.toString(radix) method. The solution is given below: public static final String toHexStringUsingBigInteger(byte[] input) { BigInteger bi = new BigInteger(input); return bi.toString(16); } We can also come up with a hand crafted solution that extract nibble by nibble and convert them into their equivalent hex character and finally forming a string. This solution is given below: public static final String toHexStringUsingCharArray(byte input[]) { int i = 0; if (...

Issue of autoboxing and reflection

Problem: Consider that you want to have a method called "Object invokeAndGet(Object targetObject, String methodName, Object... args)". This method should be able to invoke the given method on the target object and return the value returned by the invocation. If the method has overloaded forms, then depending on the argument types, the invokeAndGet method should invoke the correct form. Solution: Though this problem looks trivial and seems like it can be solved by using reflections APIs, it gets really tricky when you have to deal with primitive types. This is due to the fact that autoboxing converts the primitives into their corresponding wrapper types. For e.g. an integer value is autoboxed into Integer object, etc. To begin with let us assume that we have the following implementation of the method: public static Object invokeAndGet(Object obj, String methodName, Object... args) { try { Class<?>[] argsTypes = new Class[args.length]; ...

Creating a HashMap with entries

Problem: Create an instance of HashMap in Java with entries in it. I don't want to create a new HashMap instance and keep adding entries to it. I want to have a concise way of creating a HashMap with entries. Solution: Guava library comes with factory methods that can create a HashMap without using the verbose form of "Map myMap = new HashMap ()". You can simply say "Map myMap = newHashMap()", assuming you have done a static import of the Maps.newHashMap method. But that is not sufficient. It would be better to provide a utility method that looks like this: "Map myMap = newHashMapWithEntries(firstKey, firstValue, secondKey, secondValue)". That way it is easy to create static-final maps instead of writing a separate method to populate them or to populate them from constructor, as given below: public class MyClass {    private static final Map<String, URL> serviceUrls = createServiceUrlsMap();    private static Map<String, String> cre...

Bottle - A simple web framework in Python

I recently came across the Bottle . It is a web framework written in Python. Its very simple to learn and use. It is ideal for prototyping kind of work or you want to run a web application in no time.

Understanding Java Memory Model

I was browsing through the Linux kernel documentation and came across this excellent documentation on Memory Barriers . I was able to relate many of the concepts explained in this document with the issues that used to exist in the older buggy JVMs. I would strongly recommend to anyone to go through this kernel document to easily understand the 1.5+ Java Memory Model, especially the concept of happens-before ordering. The same author has written another excellent paper "Memory Barriers: a Hardware View for Software Hackers" , which covers the same topic in a bit more depth. Paul McKenney and David Howells - thanks a lot for your excellent document that helped me understand the key concepts behind memory barriers.

Is Java getting more and more complex

Recently I read an article in Artima , titled "Have Generics Killed Java?". This article is not the first one to complain about the complexities introduced into Java due to Generics. I used to a C++ programmer for around 6 years and been a big fan of the language. When I switched to using Java, during the pre-Generics era, I simply loved the simplicity and lucidness of Java. After reading the section on Generics in Effective Java, and having learnt the IFs and BUTs of the Generics, I realized how many things one has to remember to make effective use of Generics. I rememberd an answer given by Bjarne Stroustrup , the creator of C++, a few years before the introduction of Generics. The gist if his answer was that every language commercially successful and used in large scale follows exactly the same path C++ and (now) Java is following. That is to start simple and eventually getting more and more complex. After reading the FAQ for C++0X and some of the modules in Boost lib...

FEST libraries - a useful set of tools for testing

I came across an article in DZone.com that talked about the FEST libraries . I felt I should have known about the FEST libraries a earlier. They are pretty powerful in terms of expressing test cases in a human readable form. In FEST site itself I found a link to internal DSLs in Java which was quite an interesting reading.

Eclipse Helios JEE and Tomcat issue

I installed the latest Eclipse Helios JEE package. Every time when I try to start my Tomcat instance, I started getting 100% CPU and an non-responsive Eclipse. I figured out that this was an issue with the WTP that comes by default with the Eclipse package (which I think is 3.2.0) and this issue was fixed with WTP version 3.2.1. If you try to update this package by using "Help->Check For Updates" it won't update. So here is how you can update: Go to "Help->Install New Software". In the "Work with:" input box, give the URL "http://download.eclipse.org/webtools/repository/helios/". Wait for all the package information to be downloaded and select "Web Tools Platform (WTP) 3.2.1" option. If you are planning to use any other package, you can select them. But make sure you select the ones from 3.2.1 version distribution. Click on Next and follow the prompt to complete installation.  If you restart Eclipse, you should be fine. Y...

Cobertura and Spring auto proxying

If you are using Cobertrua to get coverage reports, you may run into the error message shown below (lines folded for clarity): Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myBean' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type '$Proxy28 implementing net.sourceforge.cobertura.coveragedata.HasBeenInstrumented, org.springframework.aop.SpringProxy, org.springframework.aop.framework.Advised' to required type 'com.mydomain.MyDao' for property 'myDao'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [$Proxy28 implementing net.sourceforge.cobertura.coveragedata.HasBeenInstrumented, org.springframework.aop.SpringProxy, org.springframework.aop.framework.Advised] to required type [com.mydomain.MyDao] for ...

Bean properties printer - a useful debugging tool

There are many instances when I wanted to just log the properties of a given object (most of the time its a bean). This will be useful in two ways: 1) learn about the concrete type of the object 2) serves as a good learning aid to understand what are all the properties that can be get/set in that object. Of course, if you have the documentation and the source code for the class in question, that would be the ultimate aid. Nevertheless, the following piece of code would be useful to print the properties of the given object/bean, using the getter methods that are available in the object.     public static void printProperties(String msg, Object o) {         String className = o.getClass().getName();         if(msg != null && msg.length() > 0)             logger.info("{} (type {})", msg, className);         Method[] methods ...

Logging three or more arguments in slf4j

I use slf4j for logging purposes. All the logging methods (Logger.info, Logger.debug, etc.) provide an efficient way of passing one or two argument objects. For e.g. logger.info("The response from server is [{}]", serverResp); logger.debug("Key [{}], Value [{}].", key, value);  But if you want to pass three or more arguments you have to create an object array yourself and pass. Like this: logger.info("Status [{}], message [{}], time taken [{} ms].", new Object[]{status, msg, timeTaken}); Doing a new everywhere in the code doesn't seem like an elegant way of doing it. I was thinking about a cool way of doing it, and this is what I came up with. Here is a utility method that makes use of varargs: public static Object[] toObjArr(Object... args) {     return args; } In the code we can use this utility function like this. import static com.mydomain.Utils.toObjArr; ...     logger.info("Status [{}], message [{}], time taken [{} ms].", toOb...

Creating a Collection with a single element

Question: What is the most efficient way of creating a collection (Set, List or Map) with a single element? Answer: The most efficient way of creating a collection with a single element would be to make use of the Collections.singletonXXX() methods. Collections.singleton - To create a set that has only one element. Collections.singletonList - To create a list that has only one element. Collections.singletonMap - To crate a map that has only one entry. The collections returned from these methods are immutable. Compare these methods with Collections.unmodifiableXXX() methods. The umodifiableXXX methods already accept a collection as an argument.

Java Native Access - An essential tool in Java tool box

I recently learned about Java Native Access (JNA) and was simply amazed at how easy it is to make native calls. I have used JNI earlier in my projects to access native code, but it is a bit painful experience. JNA makes it a bit easier to make those native calls. I haven't experimented much with passing structures and getting structures (or pointers to structures) as return values. As far as the arguments and return types are one of the primitive types, the interface is very easy to define and use. Give it a try, you will like it.

Intercepting method calls of @WebService annotated classes

I ran into this issue recently and I thought sharing this with everyone will help in saving some time. I am making use of Metro + Spring for my web service implementation. I have a requirement that I should intercept all the calls in the web service implementation (the class that has is annotated with @WebService) and log the time taken to execute each call. So I created the following AOP advice: @Aspect public class WebServiceMethodsAspect {     @Around("execution(* com.mydomain.service.*Impl.*(..)) && args(request)")            public Object interceptWebServiceCall(ProceedingJoinPoint pjp,             Object request) throws Throwable {         ....     } } Once created the aspect I enabled the annotation based aspects using the following tag in my applicationContext.xml file: <aop:aspectj-autoproxy/> < b...

Note on allocationSize parameter of @SequenceGenerator while using JPA

I ran into what I thought as an issue while I was using the sequence ID generation strategy in JPA. The JPA provider I am using is Hibernate. I think sharing my experience will save someone some time. To use a sequence (For e.g. Oracle sequence) to generate values and assign them to the ID field of your persistence object, you will following something like this: @Id @Column(name = "ITEM_ID") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="ItemIdSeqGenerator") @SequenceGenerator(name="ItemIdSeqGenerator", sequenceName="ITEM_ID_SEQ", allocationSize=1) private long itemId; This means the following things: The @Id annotation says that the field itemId is a primary key. The @Column annotation says that the corresponding column in the database is ITEM_ID. The @GeneratedValue says that the value that needs to be populated in the itemId should be generated, while that object is persisted. The strategy to generate the value is to...

Tomcat JDBC-pool

There is a new JDBC connection pool implementation that comes with Tomcat, called JDBC-pool. You can read more about this pool implementation here . I can already see that quite a few projects (including the Spring tc server) have started using or supporting this connection pool. I am currently hooked to DBCP, yet to try this pool. There is also an article that compares DBCP and JDBC-pool .

Python 3 I/O

I came across this useful page that helps you understand whats new in Python 3 I/O and what are all the significant performance enhancements you can achieve/expect.

Returning an empty collection instead of null

For one of my recent projects, I had to work with legacy code. There were methods that are returning collections, like lists or sets. These collections were created by reading data from the database. Whenever there is no data to form the collection, these methods return null. Now that is bad! One of the issues of returning null is that the caller always have to check for null. Most of the time the caller either searches for a particular value in the returned collection or iterate through the elements in the returned collection. The code will look like this: List rows = myDao.getRowsFor("key"); if(rows != null) {   for(Row row:rows) {     // Do something with the row   } } As you can see, it is easy to avoid the null pointer check if the getRowsFor() returned an empty list instead of a null pointer when there is no data in the database. The clutter caused out of the null pointer checks all over the code. You can read more about this simple principle in ...