Spring ApplicationContextAware Example

Spring provides ApplicationContextAware interface to get the ApplicationContext anywhere in our code. In order to get this feature we need to implement ApplicationContextAware interface in our beans and override setApplicationContext method.

Here is one example to get the context from CustomerGroup bean.

Customer.java

public class Customer {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Customer [name=" + name + "]";
    }


}

CustomerGroup.java

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class CustmerGroup implements ApplicationContextAware {
   
    ApplicationContext context;
    public ApplicationContext getContext() {
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException {
        this.context = context;
    }

}

Application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>
    <bean id="customer" class="com.pretech.test.Customer">
        <property name="name" value="Vinod Kumaran" />
    </bean>
    <bean id="customerGroupBean" class="com.pretech.test.CustmerGroup" />
</beans>

Test class
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class AppContextMain {
 
    public static void main(String[] args) {
 
 
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "application-context.xml");
 
        CustmerGroup customerGroupBean = (CustmerGroup) context
                .getBean("customerGroupBean");
 
        //Getting context from customerGroup bean and getting customer from that context
        System.out.println(customerGroupBean.getContext().getBean(Customer.class));
    }
 
}

Output

Customer [name=Vinod Kumaran

Spring BeanNameAware Example

BeanNameAware Interface to be implemented by beans that want to be aware of their bean name in a bean factory. If a bean in spring implements BeanNameAware then that bean has to implement a method that is setBeanName. And when that bean is loaded in spring container, the name is set to this method.
Here is an example to implement this interface and printing the name when it is loaded.

 

Student.java (Which implements BeanNameAware)

import org.springframework.beans.factory.BeanNameAware;

public class Student implements BeanNameAware {
    @Override
    public void setBeanName(String name) {
        System.out.println("Setting bean name " + name);

    }

}

application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="student" class="com.pretech.test.Student" />
</beans>
Test class
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanNameAwareTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "application-context.xml");
    }
}
Output
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@48a930: defining beans [student]; root of factory hierarchy
Setting bean name student

Apache Camel Mongodb component Example

Apache camel provides many components to interact with external systems, here is one simple example to connect mongodb using from apache camel route.

Create a maven project and add below dependencies

<dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jetty</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-mongodb</artifactId>
            <version>2.12.1</version>
        </dependency>
    </dependencies>

 

Create a Camel route

package com.vinod.test;

import org.apache.camel.builder.RouteBuilder;

public class CamelMongoRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("jetty:http://localhost:8181/mongoSelect")
                .to("mongodb:myDb?database=customerdb&collection=customer&operation=findAll");
        from("jetty:http://localhost:8181/mongoInsert")
                .to("mongodb:myDb?database=customerdb&collection=customer&operation=insert");
    }
}

Create application context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring"
    xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <camel:camelContext id="camel-client">
        <camel:routeBuilder ref="vinodroute" />
    </camel:camelContext>
    <bean id="myDb" class="com.mongodb.Mongo">
        <constructor-arg index="0" value="localhost" />
    </bean>
    <bean id="vinodroute" class="com.vinod.test.CamelMongoRoute" />
</beans>

Create a Main program

This main program will start the routes

package com.vinod.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CamelMongoMain {
    @SuppressWarnings("resource")
    public static void main(String[] args) {
                      new ClassPathXmlApplicationContext("application-context.xml");
    }

}
 

Run it

1. Start Mongodb
2. Run the main program
3. Use rest client to give inputs

To insert data into mongodb

Request body= {name:"Vinod K K"}
Response from mongodb = [{ "_id" : { "$oid" : "5419cefb0364771a127e352c"} , "name" : "Vinod K K"}]

Data in mongodb
> use customerdb
switched to db customerdb
> show collections
customer
system.indexes
> db.customer.find()
{ "_id" : ObjectId("5419cefb0364771a127e352c"), "name" : "Vinod K K" }
>


Done !!!!

Download example

Spring 4 AsyncRestTemplate Example

Spring's central class for asynchronous client-side HTTP access. Exposes similar methods as RestTemplate, but returns ListenableFuture wrappers as opposed to concrete results. See more about AsyncRestTemplate
1. Create a maven project with below dependencies 
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-core</artifactid>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-web</artifactid>
<version>4.0.6.RELEASE</version>
</dependency>
2. Create a main class to test AsyncRestTemplate
import java.util.concurrent.ExecutionException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRestTemplate;

public class AsyncRestTemplateExample {

public static void main(String[] args) {

String url = "http://pretechsol.com";
AsyncRestTemplate asyncRestTemplate = null;
HttpMethod method = null;
try {

// Create AsyncRestTemplate object
asyncRestTemplate = new AsyncRestTemplate();

// Define http method
method = HttpMethod.GET;

// Define response type
Class responseType = String.class;

// Define headers

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);

HttpEntity<String> requestEntity = new HttpEntity<String>("params",
headers);
ListenableFuture<ResponseEntity<String>> future = asyncRestTemplate
.exchange(url, method, requestEntity, responseType);

ResponseEntity<String> entity = future.get();
System.out.println(entity.getBody());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}

}

Camel Timer Example

Camel Timer component is used to generate or process message exchanges when a time fires. Here is one example to print ‘Hello world ‘ in each five seconds

Example

package com.vinod.test;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
public class TimerTest {
    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new TimerRoute());
        main.run(args);
    }
}

class TimerRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("timer://foo?period=5000").process(new Processor() {
            public void process(Exchange exchange) throws Exception {
                System.out.println("Hello world  :"
                        + System.currentTimeMillis());
            }
        });
    }
}

Output

Hello world  :1453013393616

Hello world  :1453013398609

Hello world  :1453013403614

Hello world  :1453013408617

Hello world  :1453013413621

Hello world  :1453013418624

 
Done!! download source codes from
 

Ref: http://camel.apache.org/timer.html

How to sort list of objects with multiple attributes?

We can sort list of objects using Collections.sort(Collection c) or Collections.sort(Collection c,Comparator) based on compareTo,compare implementations. Some scenarios we need to sort objects based on multiple attributes. Here is one simple example to sort student objects based on the department, name and address using apache common api.

Create a Maven project and add below dependency.

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>

Create a pojo class (Student.java)

package com.test.vinod;

public class Student {
private String name;
private String address;
private String dept;

public Student(String dept, String name, String address) {
super();
this.dept = dept;
this.name = name;
this.address = address;
}

//getters and setters

@Override
public String toString() {
return dept + " " + name + " "
+ address;
}

}

StudentComparator.java

package com.test.vinod;

import java.util.Comparator;

import org.apache.commons.lang3.builder.CompareToBuilder;

public class StudentComparator implements Comparator<Student> {

public int compare(Student o1, Student o2) {
return new CompareToBuilder().append(o1.getDept(), o2.getDept())
.append(o1.getName(), o2.getName())
.append(o1.getAddress(), o2.getAddress()).toComparison();
}

}

Main class (StudentSort.java)

package com.test.vinod;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StudentSort {

public static void main(String[] args) {
Student s1 = new Student("Commerce", "Vinod", "Bangalore");
Student s2 = new Student("Electronics", "Ram", "Chennai");
Student s3 = new Student("Electronics", "Vinod", "Bangalore");
Student s4 = new Student("Commerce", "Nirmal", "Bombay");
Student s5 = new Student("Electronics", "Ashok", "Delhi");
Student s6 = new Student("Electronics", "Prem", "Agra");
Student s7 = new Student("Commerce", "Anoop", "Bangalore");
Student s8 = new Student("Electronics", "Santhosh", "Cochin");
Student s9 = new Student("Commerce", "Vinod", "Agra");

List<Student> studentList = new ArrayList<Student>();
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
studentList.add(s4);
studentList.add(s5);
studentList.add(s6);
studentList.add(s7);
studentList.add(s8);
studentList.add(s9);

System.out.println("Before sorting:");
for (Student st : studentList) {
System.out.println(st);
}
Collections.sort(studentList, new StudentComparator());

System.out.println("\n\nAfter sorting:");
for (Student st : studentList) {
System.out.println(st);
}

}

}

Output

Before sorting:
Commerce Vinod Bangalore
Electronics Ram Chennai
Electronics Vinod Bangalore
Commerce Nirmal Bombay
Electronics Ashok Delhi
Electronics Prem Agra
Commerce Anoop Bangalore
Electronics Santhosh Cochin
Commerce Vinod Agra

After sorting:
Commerce Anoop Bangalore
Commerce Nirmal Bombay
Commerce Vinod Agra
Commerce Vinod Bangalore
Electronics Ashok Delhi
Electronics Prem Agra
Electronics Ram Chennai
Electronics Santhosh Cochin
Electronics Vinod Bangalore

Java 7 Features with Examples

There are lot of new useful java 7 features which are introduced in Jdk7 which looks very promising as it tries to make software developer’s job more easy and save his/her time as well. Now lets see which are those features or changes which are in this new release
 
1.Diamond Operator

2.Using Strings in Switch Statements

3.Automatic resource management

4.Numeric literals with underscores

5.Improved exception handling

6.File change Notifications

7.Fork and Join

8.Supporting dynamism

9.JLayerPane

10.Binary Literals
 
 
1. Diamond Operator

Diamond operator is one of the cool feature of Java 7 feature set. When we use generics and declare a map, then we need to specify the types on both the sides as shown below which was redundant, but in Java 7 we don't need to declare the types at right hand side.
 
Before Java 7 :
List<String> al=new ArrayList<String>();
 
In 7, it's written like this:

List<String> al=new ArrayList<>();
 
You don't have to type the whole list of types for the instantiation. Instead you use the <> symbol, which is called diamond operator.
 
package com.vinod.test;

import java.util.ArrayList;
import java.util.List;

public class JavaSevenGenerics {
    public static void main(String[] args) {
        List<String> al = new ArrayList<>();
        al.add("one");
        al.add("two");
        System.out.println(al);
    }
}

2. Using strings in switch statements

Switch statements work either with primitive types or enumerated types. Java 7 introduced another type that we can use in Switch statements: the String type. This is very good feature as lot of times we have Strings as key to match and we often work out if-else and equals for the check. But now we can directly use Strings in switch statement, so that we can use Switch functionality to fullest.
 
package com.vinod.test;

public class JavaSevenSwitch {
    public static void main(String[] args) {
        String s = "java";
        // switch allows string from java7
        switch (s) {
        case "java":
            System.out.println("This is java");
            break;
        case ".net":
            System.out.println("This is ,net");
            break;
        }
    }
}


3. Automatic resource management

Resources such as Connections, Files, Input/OutputStreams, etc. should be closed manually by the developer by writing bog-standard code. Usually we use a try-finally block to close the respective resources.However, Java 7 has introduced another cool feature to manage the resources automatically. It is simple in operation, too. All we have to do is declare the resources in the try as follows
 
Before Java 7
 
package com.vinod.test;

import java.io.*;

public class FileTest {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        DataOutputStream dos = null;
        try {
            fos = new FileOutputStream("file.txt");
            dos = new DataOutputStream(fos);
            dos.writeUTF("test");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
                dos.close();
            } catch (IOException e) {
            }
        }
    }
}
 
 
In Java 7
 
package com.vinod.test;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Java7FileTest {
    public static void main(String[] args) {
        try (FileOutputStream fos = new FileOutputStream("file.txt");
                DataOutputStream dos = new DataOutputStream(fos)) {
            dos.writeUTF("test");
        } catch (IOException e) {
        }
    }
}


4. Numeric literals with underscores

This is another excellent usability java 7 feature, this feature allows user to add any number of underscores which can appear anywhere between the digits in numeric literal. As shown below we are separating group of digits in numeric literals which is improving the readability of the number.

But there are some rules for adding underscores between digits
.
1.Underscore must be in between digits not at the beginning or at the end.

2.If the numeric literal in floating point type then underscore must not be adjacent to a decimal point.

3. Underscore must not prior to F and L suffix and in the occurrence of string of digit where it is expected
 
package com.vinod.test;

public class JavaSevenExample {
    public static void main(String[] args) {
        int i;
        // Java 7 allows underscore in integer
        i = 3455_11_11;
        System.out.println(i);
    }
}
 

5. Improved exception handling

Sometimes we need to handle lot of exceptions so for this we need to have multi catch statements for every exception we handle, but in java 7 its not the case anymore, You can add multiple exceptions using the pipe. Let's say you have a method that throws three exceptions. In the current state, you would deal them individually as shown in below:
 
package com.vinod.test;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Java7File1Test {
    public static void main(String[] args) {
        try (FileOutputStream fos = new FileOutputStream("file.txt");
                DataOutputStream dos = new DataOutputStream(fos)) {
            dos.writeUTF("test");
            SimpleDateFormat ff = new SimpleDateFormat("MM-dd-yyyy");
            ff.parse("2012-12-12");
        } catch (IOException | ParseException e) {
        }
    }
}


6. File change Notifications

The long awaited and very much useful feature of notifications when file change has also introduced in Java 7. When any file or directory changes the changes or the events are notified using the API WatchService.
 
package com.vinod.test;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class DirectoryWatcher {

    public static void main(String[] args) {
        // Obtain a path reference to your watchable directory:
        Path tmpPath = Paths.get("D:/Pretech Files");
        WatchService watchService;
        try {
            watchService = FileSystems.getDefault().newWatchService();
            // Register the directory with the WatchService for all types of
            // events
            tmpPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
            // Initiate the infinite loop and start taking the events:
            for (;;) {
                WatchKey key = watchService.take();
                // Run through the events on the key:
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind kind = event.kind();
                    switch (kind.name()) {
                    case "ENTRY_CREATE":
                        System.out.println("Directory created: " + event.context());
                        break;
                    case "ENTRY_MODIFY":
                        System.out.println("Directory Modified: " + event.context());
                        break;

                    }
                }
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 

7. Fork and Join

Now a days parallel computing has become necessary for heavy or complex operations. Java 7 has introduced a Fork and Join framework which distributes the work across multiple cores and join them after completion which is the final result. These tasks or work is divided into small tasks until these task dont need any divide and all these tasks carried out separately. These task use a pool and task are divided according to that. The core classes which will be useful for fork and join are the ForkJoinPool and ForkJoinTask.
 
 
package com.vinod.test;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

/**
 *
 * This class helps to understand the feature of ForkJoinPool and ForkJoinTasks
 *
 * 1) ForkJoinTask is an abstract class ,RecursiveAction and RecursiveTasks are
 * the subclasses of ForkJoinTask class
 *
 * 2) In case of return type required we need to use RecursiveTask
 *
 * 3) In this example we used RecursiveAction and override its call() method to
 * implement fork and join
 *
 * 4) This is an example to print 1 to the given number
 *
 * 5) The given number is less then 100 it will not split the task (fork)
 *
 * 6) If the given number is 100 or greater than 100 it will split it in to two
 * task (1 to 50 and 51 to 100) 7) Finally join each task
 *
 * @authorvinod
 */


public class ForkAndJoinExample {
    public static void main(String[] args) {
        ForkJoinPool fjpool = new ForkJoinPool(2);
        RecursiveAction task = new PrintJob(100);
        fjpool.invoke(task);
    }
}

class PrintJob extends RecursiveAction {
    private static final long serialVersionUID = 1L;
    private int lines = 0;

    public PrintJob(int lines) {
        this.lines = lines;
    }

    @Override
    protected void compute() {
        if (lines < 100) {
            print(1, lines, "single task");
        } else {
            PrintJob p1 = new PrintJob(lines);
            p1.print(1, lines / 2, "task 1");
            PrintJob p2 = new PrintJob(lines);
            p2.print(lines / 2, lines, "task 2");
            p1.fork();
            p2.fork();
            p1.join();
            p2.join();
        }
    }

    private void print(int start, int end, String taskname) {
        for (int i = start; i <= end; i++) {
            System.out.println("print job triggerd from " + taskname + " " + i);
        }
    }
}


8. Supporting dynamism

In this feature extension to the JVM to support the dynamically typed language to increase the performance. For this invoke dynamic is being introduced which used to incorporate non java requirements. In short this feature is to make running of dynamically typed languages efficient.

9. JLayerPane

Java has introduced another great feature for swing UI developer which is a JLayeredPane. With use of JLayeredPane we can draw on the top of the component and handle the events without actually modifying the underlying component. This is a great feature because it can be used in many effects such as transition effects, blur effects or spotlight effects etc.


10. Binary Literals

binary literals are also introduced in this release too, so developers don't have to convert them to hexadecimals any more.
 
package com.vinod.test;

public class BinaryLiterals {
    public static void main(String[] args) {
        System.out.println("Before java 7" + Integer.parseInt("101010", 2));
        int binary = 0b101010;
        System.out.println("In java 7" + binary);
    }
}
  


Download Example
https://github.com/kkvinodkumaran/java7.git


References

1. http://code.joejag.com/2009/new-language-features-in-java-7/
2. http://www.eclipse.org/jdt/ui/r3_8/Java7news/whats-new-java-7.html
3. http://inebium.com/post/java-7-new-release-performance-code

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts