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

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