Different folder colors in Ubuntu

If you need a tagging kind of system to track folders, you can change color of the folder. I love it.

A small extension in Nautilus can do this job. To install this extension, open terminal / terminator and execute following commands.

sudo add-apt-repository ppa:costales/folder-color

sudo apt-get update

sudo apt-get install folder-color

Once installed, restart machine or Nautilus.

nautilus -q

Once done, right click on any folder. You’ll see Folder Color option where you can change folder color to any of your choice and reset it too.

Change Folder Color

Enjoy!

Internal implementation of Set / HashSet

We all know that Set implementations store unique elements. Now we will try and understand what makes sure that Set has unique elements.

Observe the class below and see how elements are stored in a set.

Set.add() method returns boolean. It returns true if an element is stored successfully otherwise false.
Line number 23 in above code will print true because String “a” has been stored in set. But line number 24 prints false because “a” element / string was already present in set.

Now look at the HashSet implementation in Java API’s.

Whenever we create HashSet object, internally a new HashMap is created. This hashmap stores element E as key and PRESENT dummy object as value.

Now we should understand what HashMap.add(key, value) method does.

When we make an attempt to put a key-value pair in hashmap, it checks if same key is present or not. If it finds same key, it overrides the new value with the key and add() method returns old value associated with that key. If same key is not present in map, new entry is made in map and add() method returns null.

So when an attempt is made to add element in set, internally map.put(e, PRESENT)==null; determines whether to return true or false.

Finally to conclude, HashSet uses HashMap internally to store unique elements.

My notes on Collections framework

Java Collections Framework :

1] ArrayList

  • Usage : List<Integer> list = new ArrayList<Integer>();
  • You can specify initial size of arraylist. But by default it’s 10.
  • In ArrayList, elements are stored in array internally. [0][1][2][3][4][5][6] …
  • If initially you have created array list of size 10. And you try to add 11th item in the list, it will internally create new array of twice the size and copy all the old elements in new array.
  • Removing elements from the end of an ArrayList is quick because it just decrements the size of array internally. If removing elements from the beginning or the middle of the list, it copies subsequest elements one step back. And this adjustment of indexes causes the removal operation slow.
  • Adding elements to the beginning of array list will be slow.
  • If you want to add elements and remove from the end of the list, use array list.

2] LinkedList :

  • Usage : List<Integer> list = new LinkedList<Integer>();
  • LinkedList contains elements where each element has reference to previous and next element.
    [0]->[1]->[2]->[3] …
    <- <- <-
  • Getting elements from linked list or traversing linked list is slow because every element has to get reference to next item and so on till you reach the desired index.
  • This collection is heavyweight and consumes more memory than ArrayList.
  • If there is need to add / remove elements from list from the beginning or middle, consider using other lists LinkedList.
  • Adding new element in the linkedlist creates a new node and points it with the next node and previous node is pointed to new node.
  • Removing element from linked list removes the previous and next references of node / element.

3] HashMap :

  • Usage : Map<String, Integer> map = new HashMap<String, Integer>();
  • Maps store pair of values. One member is called ‘Key’ and other one is called ‘Value’. Map is basically a lookup table.
  • You can use anything as key of map. But while using your custom object as map key, that object should have hashCode and equals methods implemented.
  • Though we provide wrapper or non-premitive type while declaring map, for e.g. Integer. But while putting elements in map, premitives are avoid because java automatically auto box them to non-premitive.
  • If you try to get the value that doesn’t exist in your map, it returns null.
  • If you try to add duplicate key into map, it overrides the previous entry.
  • Iterating a map :
  • for(Map.Entry entry : map.entrySet()) {
    String key = entry.getKey();
    int value = entry.getValue();
    }

  • Another way is :
  • for(String key : map.keySet()) { // map.keySet() method returns the collections of keys in the form of Set (Collection).
    int value = map.get(key);
    }

  • HashMap is not sorted in any way. It does maintain order.

4] LinkedHashMap :

  • HashMap does not maintain order, so if you want elements to be in order as they are put in you can use LinkedHashMap.
  • LinkedHashMap manages doubly linked list connecting the entries. This allows the elements to be in order as they are put in.

5] TreeMap :

  • TreeMap sorts the keys in natural order. Natural order for integers is numerical order (1, 2, 3, ….) and for Strings it is alphabetical order (a,b,c,d, …). You can define natural order for your custom objects also.

6] HashSet :

  • Usage : Set<String> set = new HashSet<String>();
  • Set is a collection which stores only unique elements.
  • Sets manages arrays internally. HashSet is lightweight.
  • Adding duplicate elements in set has no effect. Adding duplicate items does nothing. (HashMap overrides old entry with the new one.)
  • HashSet does not retain order. It can and will spotaneously rearrange themselves according to the no particular logic.
  • Iterating all kinds of sets :
  • for(String item : set) {
    Sysout(item);
    }

  • We can check if given item is there in set or not quickly. Sets are optimized to do this. Use set.contains() method. Returns either true or false.

7] LinkedHashSet :

  • LinkedHashSet remembers the order of elements put in.
  • This manages doubly linked list internally, where each element has reference to previous and next element. Which makes this collection to maintain order of elements.

8] TreeSet :

  • If you want added elements to be sorted in their natural order, use TreeSet.
  • For Strings natural order is alphabetical order whereas for integers it is numeric.

9] Using custom objects in sets and maps :

  • Not implementing hashCode and equals methods in class which you are going to use as key for map, will not allow all the objects regardless of their equality. So to make it clear which objects are equal, we need to implement these methods. The same applies for sets as well.

Cache-Control headers in Spring MVC 3.0

Often we come across situations where we need to set cache control headers in http response. The one scenario which is very common is, pressing back button after logging out of application. It takes us to previous page, the page which should have been shown to logged in users. It’s actually a cached copy of page. If you see firebug or chrome tools, pressing back button after logging out does not create a new request. Ideally user should be redirected to login page. How to avoid previous page from being shown after logout?

We can add cache parameters in jsp files. Those are :

This works, but not all browsers support this.

We can use the org.springframework.web.servlet.mvc.WebContentInterceptor. This interceptor extends the WebContentGenerator class, so it has the setter methods to enable the header parameters.

This will not cache anything and everytime will request for resources. Now, if user presses back button after logout, new request will be generated and user not being logged in, will be redirected to login page again.

Spring annotations explained

We are going to discuss about spring mvc annotations. And how to use spring annotations. It’s from Spring 2.5 that allowed us to configure dependency injection using spring annotations. Instead of wiring bean’s in XML file, we do bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.
Wiring of beans using annotations is not on by default, we need to enable it in configuration file. Your spring configuration file will be something like :

Now I am going to explain some of the most used spring annotations.

  • @Component : It’s a generic stereotype for any Spring-managed component. @Repository@Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.
  • @Controller : Controller annotation is used to denote that the class is controller. It contains method which serve the http requests, request mappings are done at method level or class level.
  • @Service : Annotate all your service classes with @Service. All your business logic will be in Service classes. Controller and DAO layers will not have any business logic in there.
  • @Repository : Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.
  • @Autowire : Spring beans are injected or acquired using autowire annotation.
  • @Qualifier("bean name") : Qualifier annotation is used along with autowire. It is used as an discriminator.
  • @Value("${properties-name}") : @Value annotation is used to get the value of key mentioned/mapped in properties file.

There are some simple reasons to explain why should we use’em :

  • The main advantage of using @Repository or @Service over @Component is that it’s easy to write an AOP pointcut that targets, for instance, all classes annotated with @Repository.
  • You don’t have to write bean definitions in context xml file. Instead annotate classes and use those by autowiring.
  • Specialized annotations help to clearly demarcate application layers (in a standard 3 tiers application).

Now, Practically performance impact of using context xml beans & annotations is the same. Component scanning is a bit more expensive (when you scan for @Service, @Component). The annotations are ‘parsed’ with reflection, the xml – with an xml parser.

Here are some examples of how we use annotations :

At Controller level :

At service level we autowire dao beans and invoke dao methods.

And at the DAO layer, we fetch data from database using underlying ORM and return it to service class.

See how we are using annotations in application. Visit my github repo for this code.

Spring Maven application step by step

This post will explain how to create a project in spring mvc step by step using eclipse. You can use any eclipse version having maven and spring plugins installed. I am using Spring tool suite here. It requires only 4 steps to create a spring maven project in eclipse.

1] First of all open eclipse. Open New file wizard. Search Spring in the text box on wizard. Select Spring template project in below wizard.

New file/project wizard.

New file/project wizard.

2] Clicking next will open project template selection wizard. There are many template projects available. Select Spring MVC Project for now. That’s where we are going to start our spring journey from.

spring project template

spring project template

3] Select Spring MVC Project. Clicking next will open Project settings wizard. It will ask for project name, location and 3 level package.

project settings

new spring project settings

4] After providing all the information needed, click finish button. That’s it. You have a spring mvc project created.

spring+maven project structure

spring+maven project structure

Look at the project structure in Eclipse navigator on left side. There is a file named pom.xml. POM stands for Project Object Model. This file contains all the maven dependencies which you are going to need & description of your build process. If you want to search for any dependency, search maven repository.

You can always build this project into war file using eclipse by right click on project folder -> Runa As -> mvn clean -> mvn install. You will find the war file in target directory. If you prefer command line tools to build projects, open terminal / command prompt. Go to the project directory where pom file is located. and run commands like below.

root@ubuntu:~/home/transbank$ mvn clean
root@ubuntu:~/home/transbank$ mvn package

OR

root@ubuntu:~/home/transbank$ mvn install

The other way to create Spring MVC project is via command line.
I assume maven environment variables are set up. Using command line tools to create spring mvc project will work on any linux, unix, windows and mac systems.
Go to the directory where you want to create your new project. And use following command to create project.

mvn archetype:generate -DgroupId={projects-package-name} -DartifactId={your-project-name} -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

This will create a project directory. To make it possible to open project in eclipse, use following command.

mvn eclipse:eclipse -Dwtpversion=2.0

Resources directory under main contains mostly properties file and xml files which are used to store things we use for configurations and things which can change later on. You can put your css, js and font files in resources directory under webapp. Everything else is pretty self explanatory.

You can always clone this project from my github repo. Happy coding!