Ignore transitive dependency in Maven


Maven helps to manage the dependency of JARS . Most of the time it may happen that same JAR file with different versions is being loaded because some other jar files have it as dependency and thus causing the conflicts .

Typical example is have log4j or slf4j jar with different version in spring-xx.jar and junit-xxx.jar . So when you load you classes an conflict may arise and because of incompatible version of same jar file . For e.g.

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<version>3.2.1.RELEASE</version>
</dependency>

The above jar uses log4j 1.2.17 (you can check the dependency using mvn dependency:tree).

Consider this log4j jar file is conflicting with some other higher version of log4j which is used by other jar. To resolve this issue we would have to remove the conflicting log4j jar from org.springframework.
it can be done as follows :

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<version>3.2.1.RELEASE</version>
         <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
</dependency>

Cheers..

Advertisements

Convert JSON to Map or Map to Json in Java


One of the common uses cases while working with json is to convert it to a java object or convert java object to json. There is an open source library available in java which helps in processing json objects.

Add the Jackson dependency in pom.xml file

<repositories>
	<repository>
		<id>codehaus</id>
		<url>http://repository.codehaus.org/org/codehaus</url>
	</repository>
  </repositories>

  <dependencies>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.9.12</version>
	</dependency>
  </dependencies>

The Java class :

public static void main(String args[]) {
        ObjectMapper mapper = new ObjectMapper();
        Map m = new HashMap();
        Map personMap = new HashMap<>();
        Map personDetail = new HashMap();
        personDetail.put("firstname", "Bob");
        personDetail.put("lastname", "jackson");
        personDetail.put("age", "12");
        personDetail.put("city", "Berlin");

        personMap.put("person", personDetail);
        //convert Map to json string
        try {
            System.out.println(mapper.writeValueAsString(personMap));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // convert json to Map
        String json = "{\"person\":{\"age\":\"12\",\"lastname\":\"jackson\""
                + ",\"firstname\":\"Bob\",\"city\":\"Berlin\"}}"
        try {
            Map map = mapper.readValue(json, Map.class);
            System.out.println("Map is " + map);
        } catch (Exception e) {
            e.printStackTrace();
        }
 }

Output is

Output: {“person”:{“age”:”12″,”lastname”:”jackson”,”firstname”:”Bob”,”city”:”Berlin”}}

Map is {person={age=12, lastname=jackson, firstname=Bob, city=Berlin}}

ObjectMapper mapper = new ObjectMapper();

Creating an object of ObjectMapper is a expensive operation and as best practice it should be created as a singleton object in a class.

Rails tip #1 – Set a custom layout for a web page


Its may require that you dont want to use application.html layout for some pages . For e.g display different header on page2 which than page 1 and the header is rendered in application.html.erb.

One way is to create a new layout for e,g headerless.html.erb inside a views->layout folder and in the particular controller which serves the request set the new layout .


 class SomeController < ApplicationController

    layout :headless , :only=>[:your_action1,:your_action2]

end

With the layout keyword you can use options such as :only, :except.

Skip maven test while building a project .


Though I would encourage people to skip tests while building a project but sometimes its helpful to go down this path.
Skip Unit Test
To skip the entire unit test, uses argument “-Dmaven.test.skip=true“.

 mvn install -Dmaven.test.skip=true
 mvn package -Dmaven.test.skip=true

Or define skipTests in maven-surefire-plugin.

pom.xml
   <plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-surefire-plugin</artifactId>
	<version>2.12.4</version>
	<configuration>
		<skipTests>true</skipTests>
	</configuration>
    </plugin>

Now, build the project again, the entire unit tests will be ignored.

Create a binary tree from an array of integers .


Write a function that given an array representation of a binary tree will convert it into a typical tree format.
The following is a visual representation of expected input and output:

Input: [7, 3, 9, 2, 4, 8, 10,11,12,13,14]
Output:
7
/ \
3 9
/\ /\
2 4 8 10

One way to build a tree is that we know that array is like a breadth first traversal . So the series it appears is the same order we need to create tree. Also other property of tree is for a node at index “index” , left child is [2*index+1] and right child is [2*index+2].

public Node createTree(Integer[] array){
        
        if(array == null || array.size == 0)
         return null;
     	Node n = array[0];
     	Queue queue =new Queue();
     	queue.add(n);
        int count = 1;
     	while(count < array.length || !queue.isEmpty()){
     		n.left = new Node(array[count++]);
     		queue.add(n);
                if(count < array.length){
                  n.right = new Node(array[count++])
     		  queue.add(n.right)
               }    	
     	}
     return n;
     }

Create custom hashmap in Java


One of the common interview question, is to build own CustomHashMap. Following code sample demonstrate generic map with put(), get() and remove() operations.

/**
 * The CustomHashMap uses an array of KeyValuePair.
 * KeyValuePair class  where K is the key and V value and  next is the element appended to it. The KeyValuePair acts 
 * as a list
 * 
 *  MapList is used to store elements. the getHash() method is used to find the index of the array. 
 * 
 * @param <K>
 * @param <V>
 */
public class CustomHashMap<K, V> {

	KeyValuePair<K, V> mapList[] = new KeyValuePair[100];

	public V get(K key) {
		int index = getHash(key);
		KeyValuePair<K,V> list = mapList[index];
		return getMatchValue(list, key);
	}

	public void put(K key, V value) {
		int index = getHash(key);
		storeValue(index, key, value);
	}
	
	public void remove(K key) {
		int index = getHash(key);
		KeyValuePair<K,V> list = mapList[index];
		if (list == null)
			return;
		// if only one element is present in the list ,set the index to null
		if(list.getKey().equals(key)){
			if (list.next == null){
				mapList[index] = null;
				return;
			}
		}
		KeyValuePair<K,V> prev = null;
		do{
			if(list.key.equals(key)){
				if (prev == null){
					list = list.getNext();
				}else{
					prev.next = list.getNext();
				}
				break;
			}
			list = list.next;
		}while(list != null);
		
		mapList[index] = list;
	}

	/*
	 * find the match value and return , if not found either throw exception or return null.
	 */
	private V getMatchValue(KeyValuePair<K, V> list, K key) {
		while (list != null) {
			if (list.getKey().equals(key))
				return list.getValue();
			list = list.next;
		}
		return null;
	}

	private void storeValue(int index, K key, V value) {
		KeyValuePair<K, V> list = mapList[index];
		
		// if list is empty , enter as first element
		if (list == null) {
			mapList[index] = new KeyValuePair<K, V>(key, value);
		} else {
			boolean done = false;
			// traverse through list , if a key is found ,replace the value or add it at the end of the list
			while(list.next != null) {
				if (list.getKey().equals(key)) {
					list.setValue(value);
					done = true;
					break;
				} 
				list = list.next;
			}
			// add at the end of the list
			if (!done)
				list.next = new KeyValuePair<K, V>(key, value);
		}

	}
	
	private int getHash(K key) {
		int hash = key.hashCode();
		return hash % 100;
	}
	
	public static void main(String args[]) {
		CustomHashMap<Integer, Integer> map = new CustomHashMap<Integer, Integer>();
		map.put(1, 1);
		map.put(2, 2);
		map.put(201,201);
		System.out.println("get value is " + map.get(1));
		System.out.println("get value is " + map.get(201));
		System.out.println("get value is " + map.get(2));
		map.remove(1);
		System.out.println("After deletion " + map.get(1));
		System.out.println("get value is " + map.get(201));
	}

}

class KeyValuePair<K, V> {
	K key;
	V value;
	KeyValuePair<K, V> next = null;

	public KeyValuePair<K, V> getNext() {
		return next;
	}

	public void setNext(KeyValuePair<K, V> next) {
		this.next = next;
	}

	public KeyValuePair(K key, V value) {
		super();
		this.key = key;
		this.value = value;
	}

	public K getKey() {
		return key;
	}

	public void setKey(K key) {
		this.key = key;
	}

	public V getValue() {
		return value;
	}

	public void setValue(V value) {
		this.value = value;
	}

}