Tuesday, May 19, 2009

More Groovier collections

Ranges are a beautiful ways of mangaing feinite sequence with a defined start and end.


a=1..5
println a // prints [1,2,3,4,5]
println a.size() // prints 5
println a.from // prints 1
println a.to //prints 5

x='a'..'f'
println x // prints [a,b,c,d,e,f]


You can also use ranges in subscript way to get part of a list.

a=[1,2,3,4,5,6]
x = 2
println a[0..2] // printrs [1,2,3]


You can also loop over each element of a range simple as follows

a=[1,2,3,4,5,6]
a.each{
println it
}

this prints all elements on new line.

Ranges can work with any objects whose class implments the Commprable interface having next and previous methods.

Another interesting thing that happens with all collections in any programming langugae is looping over it.Groovy has various options to this in many elegant ways.

Classical for .
This is usual for loop found in C,C++,JAVA,etc.this makes you feel home

for(int i=0;i<5;i++)
println i // you know what it prints


Iterable for.
This for works with any class that implments iterable like ranges,lists,maps,etc.
For on ranges

for(i in 0..5)
println i


For on lists

for(i in [1,2,3,4,5])
println i


For on maps

m=[a:"ant",b:"bat",c:"cat"]
for(e in m)
println e.key + "=" + e.value


For on strings

for(i in "Groovy")
println i // prints ewach character on newline


Another flexible and intuitive nature added to collections in groovy is that all Empty collections are evaluated to false in all boolean checks.
Following all prints true .(trick question : try removing ! :)

println ![]
println !''
println ![:]


Feel free to share your Groovy tips and tricks in the comments section

Read more...

Sunday, April 19, 2009

Groovier collections

I have been groovying almost over a year now.There are many remarkable things that groovy do in a very simple and intuitive manner .If you haven't start using it, you are already late.Today , i am going to discuss how groovy takes using collection to another level.Currently, i use it for routine scripts and code generation.
Java Collections framework is one of the most used SDK API (esp. in enterprise applications).This Api allows you do handle ,manipulate and represent the Collection of any Java objects.This greatly reduces programming effort where as boosting programming performance and fostering reuse.
Groovy adds to this many useful operators and tweaks to make working with collection api more entertaining experience.
Following is the ways you create a List in groovy:


L=[0,1,2,3]
println L.class //prints class java.util.ArrayList

This showing that ArrayList is used by groovy behind the scenes to create a List representation.

To work with LinkedList do this

L = new LinkedList([0,1,2,3]);
println L.class


To access, any element from the List , you can use array-like notation familiar to most of Java developers.Other ways to retrieve the elements are get and getAt methods expecting the index (-ve index allowed).

println L[2] //prints 2
println L[-3] //prints 1
println L.get(0) //prints 0
println L.getAt(1) //prints 1

The most frequent operation done on a list is to add elements to it.This can be acheived using +=,<< or using add method.To merge 2 lists use, addAll or + operator.

L = [0,1,2,3]
L += 4
L << 5
L.add(6)
println L //prints [0,1,2,3,4,5,6]
L.addAll(["a","b"])
println L // prints [0,1,2,3,4,5,6,a,b]
K = L + [99,100]
println K // prints [0,1,2,3,4,5,6,a,b.99.100]


Removing an element is equally easy.Use -,-= or call minus.remove() method of list is too supported.

L = [0,1,2,3]
L -= [3]
println L //prints [0,1,2]
L = L.minus(2)
println L //prints [0,1]
L.remove(0)
println L //prints [1]


Reversing the content of the list can be done as

L = [0,1,2,3]
println L.reverse() //prints [3,2,1,0]


Using map is easier than ever, the content left to the : is the key and to the right is the value.

M= ['a':'A','b':'B','c':'C']
println M // prints [a:A,b:B,c:C]
println M.getClass() //prints java.util.LinkedHashMap.We cannot use .class as . is reserved to access the key-values
println new HashMap(['a':'A','b':'B','c':'C']) // prints [a:A,b:B,c:C]


Retreiving value can be done numerous ways.

M= ['a':'A','b':'B','c':'C']
println M.a // prints A
println M['a'] // prints A
println M.get('c') // prints C
println M.getAt('b') // prints B
println M.getAt('x') // prints null as no key is matched.


Adding new key-value pairs too has various alternative.

M= ['a':'A','b':'B','c':'C']
M['d'] = 'D'
println M // prints ['a':'A','b':'B','c':'C','d':'D']
M.put('e','E')
println M // prints ['a':'A','b':'B','c':'C','d':'D','e':'E']
M.putAt('f','F')
println M // prints ['a':'A','b':'B','c':'C','d':'D','e':'E','f':'F']

Remove a pair with remove method paasing the Key.

M= ['a':'A','b':'B','c':'C']
M.remove('b') = 'D'
println M // prints ['a':'A','c':'C']


i'll cover more groovy stuff in upcoming posts.
till then...happy Groovying ;)

P.S : Syntax high lighting help from here.

Read more...

Saturday, April 04, 2009

Freemind on Ubuntu

Today i installed JDK6u13 and wanted to try out Freemind , one of the best free mind mapping tools.As i am still very new to mind mapping but a seasoned Java developer , i thought that i will start rolling soon with this tool.But , it turned otherwise.

After unzipping the freemind (binaries for any operating system - max - all inclusive) version to /opt,i chmodED it as executable.Now ,i tried to start it with the shell script file provided and what i got was

Exception in thread "main" java.awt.AWTError: Cannot load AWT toolkit: gnu.java.awt.peer.gtk.GtkToolkit
at java.awt.Toolkit.getDefaultToolkit(libgcj.so.70)
at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(libgcj.so.70)
at java.awt.Window.(libgcj.so.70)
at java.awt.Frame.(libgcj.so.70)
at javax.swing.JFrame.(libgcj.so.70)
at freemind.main.FreeMind.(FreeMind.java:107)
at freemind.main.FreeMind.main(FreeMind.java:647)
Caused by: java.lang.UnsatisfiedLinkError: libgtkpeer: libgtkpeer.so: cannot open shared object file: No such file or directory
at java.lang.Runtime._load(libgcj.so.70)
at java.lang.Runtime.loadLibrary(libgcj.so.70)
at java.lang.System.loadLibrary(libgcj.so.70)
at gnu.java.awt.peer.gtk.GtkToolkit.(libgcj.so.70)
at java.lang.Class.initializeClass(libgcj.so.70)
at java.lang.Class.forName(libgcj.so.70)
at java.awt.Toolkit.getDefaultToolkit(libgcj.so.70)
...6 more


Even though , i installed JDK6u13 and had it as my default java executable after updating the .profile file, then to some how this script was picking up the java from gcj package.

so i started to dig and find out is this happening.Sooner using sudo update-java-alternatives -l i was able to find out that i only had gcj installed and registerd in ubuntu.

X@X-desktop:/opt/Freemind$ sudo update-java-alternatives -l
java-gcj 1041 /usr/lib/jvm/java-gcj


Now, i was in search of a resource which will show me how to get java from JDK6u13 to be my default.After a quick google , i found this.So next set i ran

X@X-desktop:/opt/Freemind$ sudo update-alternatives --install "/usr/bin/java" "java" "/opt/jdk1.6.0_13/bin/java" 1
X@X-desktop:/opt/Freemind$ sudo update-alternatives --set java /opt/jdk1.6.0_13/bin/java

And then started the shell script..VOILA..it started










Drop me a cooment if this helps you , or you have good mind mapping sites/online book urls.

Read more...

Sunday, February 01, 2009

Want to begin TDD?

i have joined the Test-driven development yahoo mailing group.Its a great place to see all levels of TDD practitioners out there and their innovative ideas.
One of the thread there mentioned a resource which may help you kickstart the TDD.


TDD Problems
This present programmer with problems that will help them learn and improve their TDD skills.The problem categorization is huge and divided into games,Web related,and many more.
This is worth a check for any TDD practitioners .This will help beginners improvise their skills whereas advanced user to guide their colleagues to follow TDD.

Read more...

Tuesday, October 21, 2008

Loading Jars Dynamically

Post after really long time..from now on ..i ''ll be frequently updating this with random but interesting java posts.
Earlier this week i had a requirement to dynamically load some classes in the current JVM's classpath from some external Jar files.
The way to load classes dynamically from any particular location is to use a java.net.URLClassLoader.
Lets see some code.

//Here u specify the URL for a jar on the file system
String filePath = "jar:file:///" + sysfilePath + "!/";
//Make a URL out of It.
URL url = new URL(filePath);
//Use the ClassLoder to Load that Jar
//You can pass in as many URL you want to the classloader
URLClassLoader clazzLoader = new URLClassLoader(new URL[]{url});


I am thinking to build a fluent interface on this classloader which will allow me to dynamically load more jars as the application goes along.

While researching and googling for this, i upon this JCL.Worth a try.

Do you have any recommendations or alternative approaches?Do comment below.

Read more...

Saturday, November 18, 2006

LIFE..........its just about having FUN..

I just StumbledUpon this thing in morning while surfing @ HOME.
It really shook me.
It showed simple 8 reasons of having fun in life which all of us unKnowingly (sometimes even Knowingly)just ignore or forget.
Just spend some minutes through this simple but really interesting flash movie.
Really it will make you lot more comfortable and make you know what are you really missing in life.
http://www.eightprinciples.com/*

Enjoy

*If you have sound, you can also hear the soothing music :).

Read more...

Sunday, September 10, 2006

WAI Tools I Used

Finally, i compeleted my WAI related things and here to share my experiences.
The tools that really helped me are again W3C validator(BTW W3C itself rollsout the spec) and ATRC Accessibility Checker which is developed by Adaptive Technology Resource Centre based upon the proposed Open Accessibility Checks (OAC).

I used W3CValidator to check WAI and XHTML markup validation.It is a great tool and you can provide either the url to validate or directly upload the content through file or inpput textarea.The result of validation shows level of violation(Error,warning,etc) with the line number of the content provided.

Here's an example,



Accessibility Checker tool was setup on a machine ,it gave results in a browsable manner dividing pages int ot tables,frames,images,etc.It also shows the part with violation in results.The installation is trivial.It requires JAVA and Apache Tomcat for working.

Bobby(from WatchFire) is a windows desktop tool which spiders the particular web application and runs checks on all html pages.But as we were not working on pure HTML it was not useful for us.Reports are again browsable with abilty to make projects ,have scheduled checks, nad many more features.

Read more...

Sunday, July 30, 2006

ANTic Problem

Last week working on a continuous buils setup for a project, i stumbled upon a issue with ANT(Another Neat Tool), Java build tool.
The buildfile was working from the current directory where the file was , but was failing if ant was invoked from outside the directory.
So when i said
ant
in the current folder the build would happen successfully, but if i triggered the build from any other location using
ant -f some_dir/build.xml
it would fail.


I digged into the build file and found that all the property declarations were using value attribute to refer relative paths.Here the problem lied.
I changed the value attribute to location and Voila....... it started working.So it seems that sometimes minor mishaps can cause a blunder(and posssible time waste) while automating any actvity.

Just to summarize,

Always use location attributes for properties , if you are refereing to paths in your buildfile

Read more...

Looking for WAI Tools

For past couple of weeks i am working on WAI-fying web applications. i have come across couple of good online tools the W3C validator and ATRC Accessibility Checker Java based Server Side tool.

Have any body used other Open Source WAI Tools?
Can u share those with me?
What are your experiences?

I'll be putting my experience here....so stay tuned for more WAI.

Read more...

Wednesday, July 19, 2006

Here i go...........

Atlast a blog, me and my thoughts which doesn't always makes it where its intended.
So Let me start.
Here, i'll be blogging about Java,Programming,hobbies,etc.
Seems like everyday things.
So till next time.....
Keep Sipping..Keep Coding :-)

Read more...

Sociofluid