|
Kundan Ray Akela Oodles

Kundan Ray Akela (Manager-Sr. Technical Architect)

Experience:11+ yrs

Kundan holds years of industry experience as a Fullstack Developer in various technologies and is focused in defining the architecture of the system to ensure reliability and resilience. He possess good knowledge & understanding of latest technologies and hands-on experience in Core Java, Spring-Boot, hibernate, React, Angular , Apache Kafka messaging queue , AI Development like Computer Vision/Generative AI/Prediction System, Internet of Things based technologies and relational database like MySql, PostgreSQL etc. He is proficient in API Implementations, Webservices, Development Testings and deployments, code enhancements and have been contributing to company values through his deliverable in various client projects namely VirginMedia, Konfer, TIHM, Herdsy, HP1T and many more. He has a creative mind and has good analytical skills and likes reading and exploring new technologies.

Kundan Ray Akela Oodles
Kundan Ray Akela
(Sr. Technical Architect)

Kundan holds years of industry experience as a Fullstack Developer in various technologies and is focused in defining the architecture of the system to ensure reliability and resilience. He possess good knowledge & understanding of latest technologies and hands-on experience in Core Java, Spring-Boot, hibernate, React, Angular , Apache Kafka messaging queue , AI Development like Computer Vision/Generative AI/Prediction System, Internet of Things based technologies and relational database like MySql, PostgreSQL etc. He is proficient in API Implementations, Webservices, Development Testings and deployments, code enhancements and have been contributing to company values through his deliverable in various client projects namely VirginMedia, Konfer, TIHM, Herdsy, HP1T and many more. He has a creative mind and has good analytical skills and likes reading and exploring new technologies.

Skills
Skills

DotPython

100%

DotJava

80%

DotGenerative AI

80%

DotLangChain

80%
Top Blog Posts
A Brief Introduction to Kafka

In this blog, I am going to present an introduction to Kafka which is very popular nowadays.

Apache Kafka is a distributed streaming platform which has capabilities to

  • Message Queueing by the help of Publish and Subscribe paradigm
  • Store records in form of streams in a fault-tolerant way
  • Processing records in form of streams

 

Kafka is mainly popular and used in areas such as:

  • Very reliable capture data from application or system in real time, and
  • Building application which has the capability to use and feature real-time data

 

Let's understand how Kafka is able to do the great job which is nowadays getting popularity:

  • It runs as a cluster on one or more servers and can be span across multiple datacenters.
  • Every Kafka clusters stores stream of records in categories, called topics.
  • Each record consists Key, Value, and Timestamp.

Image source: https://kafka.apache.org/intro

 

Let's understand the main abstract thing which stores streams of records - Topic

We can understand the topic as a feed name to which records are published. Kafka topics is a multi-subscribe in nature which means a topic can have zero, one or multiple consumers that have subscribed for the data written into it in form of a stream.

In each topic there is a concept of maintaining partition log which looks like below:

Image source: https://kafka.apache.org/intro

 

In the diagram, there are three partitioned of a topic (0,1 and 2). Each partition is ordered and immutable that consists of stream of records that are written in a structured commit log, a special feature implemented in Kafka. Each record has a sequential id number which is called offset and on the basis of this id, Kafka uniquely identifies each record in a partition.

Let's next explore about the Producers:

In simple word, we can say that producer produces data on a particular topic.The producer can choose which records can be stored on which partition of a topic. This is internally handled in a round robin manner simply to balance the load.

Let's see about Consumers:

In simple words, consumers consume data from a particular topic. Every consumer is a part of consumer group. We can separate the consumer groups across multiple servers.

Image source: https://kafka.apache.org/intro

There are two servers and two consumer groups A and B. There is total of 4 partitions P0, P1, P2, P3, and each partition is subscribed by both Consumer groups.

Hope, this helps in understanding the basic concepts of Kafka. I will publish more information about it in the next subsequent blogs.

 

Thanks,

Kundan Ray

Websocket Messaging In Springboot
In this blog I am going to share the information on how we can implement Websocket messaging in spring boot. Let's started with some overview about Websocket and it's protocol.Websocket is above the TCP layer which is thin and lightweight.It is very suitable to use "subprotocols" to embed messages. We will use STOMP messaging protocol in this blog.
 
 
We will build a server that will accept a message carrying a user’s name. In response, it will push a wishing into a queue that the client is subscribed to.
First of all let's include the maven dependencies:

	
            org.springframework.boot
            spring-boot-starter-websocket
        
        
            org.webjars
            webjars-locator
        
        
            org.webjars
            sockjs-client
            1.0.2
        
        
            org.webjars
            stomp-websocket
            2.3.3
        
        
            org.webjars
            bootstrap
            3.3.7
        
        
            org.webjars
            jquery
            3.1.0
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

Let's define a model first of all:
public class Message {
    private String name;
    public Message() {
    }
    public Message(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
To model the Wishing representation, we'll add another plain old Java object with a content property and corresponding getContent() method:
public class Wishing {
    private String content;
    public Wishing() {
    }
    public Wishing(String content) {
        this.content = content;
    }
    public String getContent() {
        return content;
    }
}
Let's create a controller to handle the message:
@Controller
public class WishingController {
    @MessageMapping("/hey")
    @SendTo("/topic/wishing")
    public Wishing wishing(HelloMessage message) throws Exception {
        Thread.sleep(1000); // simulated delay
        return new Wishing("Hey, " + message.getName() + "!");
    }
}
Let's enable Web socket and STOMP protocol:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-websocket").withSockJS();
    }
}
We are done at server side configuration.
 
Thanks,
All about CORS in Springboot
In this blog I am going to create a restful endpoint with springboot that incudes the header for Cross-Origin Resource Sharing.CORS is a mechanism to allow only some of the specified IP to access the resource and block the other IPs.
 
Let's define our model class first:
public class User {
	private final Long userId;
	private final String fullName;
	public User() {
		this.userId = -1L;
		this.fullName = "";
	}
	public User(Long userId,String fullName) {
		this.userId = userId;
		this.fullName = fullName;
	}
	public Long getUserId() {
		return userId;
	}
	public String getFullName() {
		return fullName;
	}
}
Now let's create the Controller which handles request on a endpoint:
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.kundan.model.User;
@RestController
public class UserController {
    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();
    @GetMapping("/user")
    public User getUser(@RequestParam(required=false, defaultValue="User") String name) {
        System.out.println("==== in getUser() ====");
        return new User(counter.incrementAndGet(), String.format(template, name));
    }
}

Now let's enable the CORS:

@CrossOrigin(origins = "http://localhost:9200")
@GetMapping("/user")
public User getUser(@RequestParam(required=false, defaultValue="User") String name) {
      System.out.println("==== in getUser() ====");
      return new User(counter.incrementAndGet(), String.format(template, name));
}
This @CrossOrigin annotation enables cross-origin requests only for this specific method. By default, its allows all origins, all headers, the HTTP methods specified in the @RequestMapping annotation and a maxAge of 30 minutes is used. We can customize this behavior by specifying the value of one of the annotation attributes: origins, methods, allowedHeaders, exposedHeaders, allowCredentials or maxAge. In this example, we only allow http://localhost:9200 to send cross-origin requests.
Note:We can also user @CrossOrigin on Controller level.
Now test the endpoint (http://localhost:8080/user?name=kundan) from different origin other than 9200 from localhost and you will get CORS error.
In next blog I will probably illustrate to configure CORS in a center point of the app which will be applicabel throughout all the enpoints.
 
Thanks,
RestTemplate usage and implementation in Springboot

In this blog I am going to share the information about how to use RestTemplate in your spring project. So, let's start with basic information about RestTemplate.

It is the central Spring class for client-side HTTP access.It is very similar to the other Spring template example JdbcTemplate, JmsTemplate, and the various other templates found in the Spring Framework and other portfolio projects.RestTemplate is thread-safe once constructed, and  we can use callbacks to customize its operations.

RestTemplate Methods:
Http DELETE - delete(String, String...),Http GET -getForObject(String, Class, String...),Http HEAD-headForHeaders(String, String...),Http OPTIONS optionsForAllow(String, String...),Http POST - postForLocation(String, Object, String...),Http PUT-put(String, Object, String...)

For example, getForObject() will perform a GET, convert the HTTP response into an object type of our choice, and returns that object. postForLocation will do a POST, converting the given object into a HTTP request, and returns the response HTTP Location header where the newly created object can be found. As you can see, these methods try to enforce REST best practices.

We can pass URI as first argument in these methods and choose one of these methods to perform tasks based on our requirement. For example for performing HTTP GET request we can use getForObject() method that will perform GET and convert response into the object type of our choice and will return that object.

For expamle:

String response = restTemplate.getForObject("http://localhost/hotel/{hostelId}/bookings/{booking}", String.class, "12", "22");

will perform GET on  http://localhost/hostel/12/bookings/22. We can also pass parameters in Map.

Map parameters = new HashMap();
vars.put("hostelId", "12");
vars.put("booking", "22");
String response = restTemplate.getForObject("http://localhost/hotel/{hostelId}/bookings/{booking}", String.class, parameters);

Full example:

@SpringBootApplication
public class Application {

	private static final Logger log = LoggerFactory.getLogger(Application.class);

	public static void main(String args[]) {
		SpringApplication.run(Application.class);
	}

	@Bean
	public RestTemplate restTemplate(RestTemplateBuilder builder) {
		return builder.build();
	}

	@Bean
	public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
		return args -> {
			User user = restTemplate.getForObject(
					"http://localhost/api/user/{userId}", User.class,1);
			log.info(user.toString());
		};
	}
}

 

Your User.java will look like this:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {

    private String firstName;
     private String lastName;

    public User() {
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public Value getLastName() {
        return lastName;
    }

    public void setValue(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "User{" +
                "firstName='" + firstName + '\'' +
                ", lastName=" + lastName +
                '}';
    }
}

Thanks

Kundan Ray

Connect to SSL enabled RabbitMQ server Springboot

Connect to SSL enabled RabbitMQ server Springboot

In this blog I am going to share the information about how to configure and implement RabbitMQ in springboot application. So first of all some basic information about what RabbitMQ does.

 

RabbitMQ is basically use to implement queueing based messages between applications.It is opensource,robust,easy to use and runs on all major operating systems.It implements AMQP.

 

Let's start the configuration.First of all define the dependency in pom.xml.


	
            org.springframework.boot
            spring-boot-starter-amqp
        

Next step should be to define properties of RabbitMQ server to connect it in application.properties file.

#Rabbitmq configuration
spring.rabbitmq.host=hostURL
spring.rabbitmq.port = hostPort
spring.rabbitmq.username = username
spring.rabbitmq.password = password
spring.rabbitmq.virtual-host=virtualHost
spring.rabbitmq.ssl.enabled=true
spring.rabbitmq.ssl.algorithm=TLSv1.2
spring.rabbitmq.ssl.key-store=/rabbitmq-security/dev/inno-certs-p12/keycert.p12
spring.rabbitmq.ssl.key-store-password=tihm2k16
spring.rabbitmq.ssl.trust-store=/rabbitmq-security/dev/rabbitstore
spring.rabbitmq.ssl.trust-store-password=truststorepass

Let's go through main property parameters.
#spring.rabbitmq.ssl.algorithm - You should be make sure to use the same version of TLS at client side which server is using. Version incompatible will cause issues. #spring.rabbitmq.ssl.key-store - This will be the path of you private and public key certificate.
#spring.rabbitmq.ssl.key-store-password - This will be password which is used to generate the key certificate.
#spring.rabbitmq.ssl.trust-store - Path where your truststore resides.
#spring.rabbitmq.ssl.trust-store-password - Password which is used to generate the truststore.

You can test publishing and receiving messages.

Follow the previous blog to get code.RabbitMQ-Client-implementation-in-springboot.

 

Thanks
Kundan Ray

 

 

RabbitMQ Client implementation in springboot

In this blog I am going to share the information about how to configure and implement RabbitMQ in springboot application. So first of all some basic information about what RabbitMQ does.

RabbitMQ is basically use to implement queueing based messages between applications.It is opensource,robust,easy to use and runs on all major operating systems.It implements AMQP.

Let's start the configuration.First of all define the dependency in pom.xml.

	
            org.springframework.boot
            spring-boot-starter-amqp
       

Next step should be to define properties of RabbitMQ server to connect it in application.properties file.

#Rabbitmq configuration
spring.rabbitmq.host=hostUrl
spring.rabbitmq.port = hostPort
spring.rabbitmq.username =username
spring.rabbitmq.password =password
spring.rabbitmq.virtual-host=virtualHost

Next step will be to configure RabbitMQ client.

public class RobbitMqConfig  {
	public final static String publishQName ="publishQueue";
	public final static String consumeQName ="consumeQueue";
	@Bean
	public Jackson2JsonMessageConverter jsonMessageConverter(){
		Jackson2JsonMessageConverter con= new Jackson2JsonMessageConverter();
		return con;
	}
	@Bean
	RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
		RabbitTemplate templete=new RabbitTemplate();
		templete.setExchange("exchange");//Set exchange
		templete.setQueue(publishQName);//Declare queue
		templete.setMessageConverter(jsonMessageConverter());
		templete.setConnectionFactory(connectionFactory);
		return templete;
	}
	@Bean
	SimpleMessageListenerContainer container(ConnectionFactory connectionFactory) {
		SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		container.setQueueNames(consumeQName);
		container.setMessageConverter(jsonMessageConverter());
		container.setMessageListener(consumer());
		return container;
	}
	@Bean MessageListener consumer(){
		return new Consumer();
	}
}

All are set now and we can send and recieve messages.

Publish message:

public class RabbitmqTest {
	@Autowired
	private RabbitTemplate rabbitTemplate;
	@Test
	public void test() throws Exception {
		rabbitTemplate.convertAndSend(RobbitMqConfig.publishQName, "RabbitMQ Spring JSON Example");
		System.out.println("Is listener returned ::: "+rabbitTemplate.isReturnListener());
	}
}

Listening messages:

@Service
public class Consumer implements MessageListener {
	private final Logger log = LoggerFactory.getLogger(Consumer.class);	
	@Override
	public void onMessage(Message message) {
		String parseMessage=new String(message.getBody());
		log.info("consumer message {}",parseMessage);
	}
}

 

You may also want to check blog for implementing RabbitMQ in Java from http://www.oodlestechnologies.com/blogs/Implement-RabbitMQ-for-JMS.

Hope it will help:).Looking forward for any query and comments. Will share the information about how to connect to SSL enabled RabbitMQ server in next blog.

Thanks
Kundan Ray

Http POST request

In this blog , I am going to share the information about making Http Post request using Apache HttClient.

Here is the dependencies for HttpClient and JSON.Place it into your pom.xml.


	com.googlecode.json-simple
	json-simple
	1.1


	org.apache.httpcomponents
	httpclient
	4.3.1

Now , let's move to Java code.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CaptionDataUtil {
	
	private static final Logger log = 
			LoggerFactory.getLogger(CaptionDataUtil.class);

	public static void main(String[] args) throws UnsupportedEncodingException, IOException{
		HttpPost request = createPostReq("http://my.labs.com/api/v1/authenticate");
		JSONObject jsonData = new JSONObject();
		jsonData.put("username", "dddd");
		jsonData.put("password", "xxxxx");
		jsonData.put("stayLoggedIn", false);
		executeHttpPostRequest(jsonData.toString(),request);
	}
	
	private static HttpPost createPostReq(String restUrl) {
		HttpPost request = new HttpPost(restUrl);
		return request;
	}

	
	private static String executeHttpPostRequest(String jsonData,  HttpPost httpPost)  throws UnsupportedEncodingException, IOException {
		HttpResponse response=null;
		String line = "";
		StringBuffer result = new StringBuffer();
		httpPost.setEntity(new StringEntity(jsonData));
		HttpClient client = HttpClientBuilder.create().build();
		response = client.execute(httpPost);
		log.debug("Post parameters : " + jsonData );
		log.debug("Response Code : " +response.getStatusLine().getStatusCode());
		BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		while ((line = reader.readLine()) != null){ result.append(line); }
		log.debug(result.toString());
		return result.toString();
	}
}

You would get status code 200 , if request successfull.

 

THANKS

Launch4j for making exe from jar

In this blog , I am going to share the information about how can we make .exe(executable) file for windows from a jar.
My requirement was to make a desktop application which is executable by double clicking or by drop file on the icon of the executable.
Here are the steps I am describing to make exe from jar.
Step:-1
We can use launch4j on windows , mac and linux. Download from here http://sourceforge.net/projects/launch4j/files/launch4j-3/3.8/.
Step:-2
Run launch4j.jar from the command line type java -jar launch4j.jar
Step:-3
You will get a user interface. From the basic tab set the output file that will be your_file_name.exe.
Step:-4
Then you need to provide the full path of jar which you want to use.Add the jar.
Step:-5
You can also provide the manifest if you are defined externally(outside the jar). If manifest file is inside the jar then you can skip this step.
Step:-5
Select the icon which should be an .ico file.
Step:-6
You can also provide the command line arguments.
Step:-7
Now go to jre tab.Set the min jre version. You can also set the max jre version but it is optional.
Step:-8
Click on build-wrapper icon.That will ask you to provide the .xml file.

Here is the .xml file.



  false
  gui
  /home/kundan/oodles-work/CaptionLabsUDP/target/CaptionLabsUDP-1.0.0-SNAPSHOT-jar-with-dependencies.jar
  /home/kundan/Desktop/captionlab.exe
  
  
  .
  normal
  http://java.com/download
  
  false
  false
  
  /home/kundan/Desktop/Smile Face.ico
  
    
    false
    false
    1.7.0
    
    preferJre
    64/32
  

You need to only specify the file name.The file is auto generated on the basis of settings we have done.

Making exe from jar from command line in windows with own setting.xml file.
open command prompt->go to folder where launch4j.exe is stored.

>launch4j.exe your_setting.xml

Now you are able to launch the application in windows by double clicking on the generated file.

 

THANKS

Use external css in JavaFX for styling



In this blog I am going to share the information about how to load use css on form to make the style of the component as look and feel.

First of all you need to have Java 1.7 or later in your class path.
Go to File->New Project->JavaFX project . Choose JavaFX application and click on finish.

Create external file named style.css and download an image named background.jpg in your project root directory.

Here is the code that will create a window and use style.css file for styling.

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 *
 * @author kundan
 */
public class JavaFxTest extends Application {
    
    @Override
    public void start(Stage primaryStage) {       
        primaryStage.setTitle("JavaFX Welcome");
        GridPane grid = new GridPane();
        grid.setAlignment(Pos.CENTER);
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25, 25, 25, 25));
        Text scenetitle = new Text("Welcome");
        scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
        scenetitle.setId("welcome-text");
        grid.add(scenetitle, 0, 0, 2, 1);

        Label userName = new Label("User Name:");
        userName.setMinSize(80, 50);
        grid.add(userName, 0, 1);

        TextField userTextField = new TextField();
        grid.add(userTextField, 1, 1);

        Label pw = new Label("Password:");
        pw.setMinSize(80, 50);
        grid.add(pw, 0, 2);

        PasswordField pwBox = new PasswordField();
        grid.add(pwBox, 1, 2);
        Button btn = new Button("Sign in");
        HBox hbBtn = new HBox(10);
        hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
        hbBtn.getChildren().add(btn);
        grid.add(hbBtn, 1, 4);
        final Text actiontarget = new Text();
        grid.add(actiontarget, 1, 6);
        btn.setOnAction(new EventHandler() {
 
    @Override
    public void handle(ActionEvent e) {
        actiontarget.setFill(Color.FIREBRICK);
        actiontarget.setText("Sign in button pressed");
    }
    });
        Scene scene = new Scene(grid, 300, 275);
        scene.getStylesheets().add
 (JavaFxTest.class.getResource("Login.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}

Here is the code of style.css file.

.root {
     -fx-background-image: url("background.jpg");
}
.label {
    -fx-font-size: 12px;
    -fx-font-weight: bold;
    -fx-text-fill: #333333;
    -fx-effect: dropshadow( gaussian , rgba(255,255,255,0.5) , 0,0,0,1 );
}
#welcome-text {
   -fx-font-size: 32px;
   -fx-font-family: "Arial Black";
   -fx-fill: #818181;
   -fx-effect: innershadow( three-pass-box , rgba(0,0,0,0.7) , 6, 0.0 , 0 , 2 );
}
#actiontarget {
  -fx-fill: FIREBRICK;
  -fx-font-weight: bold;
  -fx-effect: dropshadow( gaussian , rgba(255,255,255,0.5) , 0,0,0,1 );  
}

Run it. You would get a windows with the style we defined in style.css.

 

THANKS

JavaFX first application

In this blog I am going to share about JavaFX hello world example in Netbeans or Eclipse.

JavaFX is a platform for creating and delivering desktop applications, as well as rich internet applications (RIAs) that can run across a wide variety of devices. JavaFX is intended to replace Swing as the standard GUI library for Java SE.

First you need to have Java 1.7 or later in your path.
In Netbeans go to File->New Project->Choose Project . Choose JavaFX project, click finish after typing the project name and setting version of Java.

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
 
public class FirstApp extends Application {
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler() {
 
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }
}

Run the application by right-clicking on the FirstApp.

 

THANKS

Spring MessageSource to get text from properties file

ApplicationContext object has many functionlaity, I am going to describe one functionality of application context bean factory object.

This is used in messaging and internationalization.If we need to display a message in different places in an application , you don't want to have these messages text inside you code.So, Spring provides supports for that. Where you can define your messages in the properties file and use dynamically.

Let's define the bean for MessageSource in your servlet.xml file where all your bean defined.


	
		
			messages
		
	

The bean we have defined is named messageSource and the class which will use to read the text from properties file. Now we need to tell this class where is properties file.

Now here is the code to get text from properties file.

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * An app that print text from properties file
 *
 */
public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
    	 
        System.out.println(context.getMessage("greeting", null, "Default greetings",null));
    }
}

The method getMessage has different signature in terms of number of argument. I have used getMessage method which takes four arguments.
First argument: First parameter messageKey
Second argument: Second aggument Sting objects that message needs
Third argument: Third params the default message the metod will return if not found value for the key greeting
Fourth argument: Fourth locale

Above is the simple example for testing purpose.Most of the cases we need to use messageSource method in bean(Class define in xml file through bean).

The way to use it injecting messageSource as we have defined in xml.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;

/**
 * Injected messageSOurce and print text from properties file
 *
 */
public class MyClass 
{
	private MessageSource messageSource;
	
	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}
	
	public void printHello() {
		System.out.println("Hello ! " + messageSource.getMessage("username", null, "Username not found", null));
	}
}

Here is our bean declaration for MyClass.


		

Hope,this would help you.

Thanks
Kundan Ray

Sending email through amazon mail service in Grails

Sending email through amazon mail service in Grails

In this blog , I am going to share information about how to configure and send email through Amazon simple email sevice.

A short details about Amzon SES.
We need to send email like business messages of transactional messages in almost every application and we cannot ignore the complexity and cost.Managing our sending email properly we must need to deal with some challeges like infrastructure(server management,network configuration, and IP address reputation).

Amazon SES properly handle these challenges.We can use SMTP or API call to get Amzon high quality email services.

Steps to configure email:

1.Obviously , we need to signup on Amazon (https://portal.aws.amazon.com) 

2.We need to verify that you own the domain or address from which you’ll be sending email.

3.You can increase the limit of sending email.

4.We can use either SMTP or the Amazon SES API to queue an email message for delivery.

5.Amazon SES provides useful statistics about our sending activities.

6.All we need to do Amazon SES console.

Sending in grails:

Build Config

compile 'com.amazonaws:aws-java-sdk:1.9.37'

In config

grails.plugin.awssdk.accessKey='YOUR_AWS_ACCESS_KEY'
grails.plugin.awssdk.secretKey='YOUR_AWS_SECRET_KEY'
gralis.plugin.awssdk.ses.sender='YOUR_SENDER_ADDRESS'

Here is a simple service that sends email.

package com.makzy.service
import com.amazonaws.services.simpleemail.model.Body
import com.amazonaws.services.simpleemail.model.Content
import com.amazonaws.services.simpleemail.model.Destination
import com.amazonaws.services.simpleemail.model.Message
import com.amazonaws.services.simpleemail.model.SendEmailRequest
import com.makzy.domain.User

class MailService {
    def grailsApplication

    /** The transactional. */
    static transactional = false

    /** The amazon web service. */
    def amazonWebService

    /** The groovy page renderer. */
    def groovyPageRenderer

    /**
     * Sets the async mail.
     *
     * @param model - domain object
     * @param template - template used for mail
     * @param from - from address
     * @param destination - array of addresses mail is sent to
     * @param subject - mail subject
     * @return the java.lang. object
     */
    public def sendMail(subject, template, model, destination) {

        def from = grailsApplication.config.gralis.plugin.awssdk.ses.sender
        def output = groovyPageRenderer.render view: '/emailtemplates/' + template, model: [data: model]
        Body body = new Body().withHtml(new Content(output.toString()))
        Message message = new Message(new Content(subject), body)
        def result = amazonWebService.ses.sendEmail(new SendEmailRequest(from.toString(), new Destination([destination]), message))
	println result
	return result
    }
}

Here emailtemplate is a html page containing content of the mail.

Multiple exceptions catching in one catch block Java

We all know that Java 8 has been introduced with its great new features, but I wanted to share a feature of Java 7 that I have used very frequently in my coding. This feature is, handling multiple exceptions in one catch block.Yes, we can handle multiple exceptions in one catch block that will reduce the code duplication, and facilitate easier and more concise exception handling. Here is how you can convert your exception handling code prior from Java SE7 to Java SE7. 

public class ExceptionHandling
{
	public static void main( String[] args )
	{
   		try {
   			URL newUrl = new URL("http://www.yoursimpledate.server/");
   			BufferedReader reader = new 
				BufferedReader(newInputStreamReader(newUrl.openStream()));
   			String line = reader.readLine();
   			SimpleDateFormat formater = new SimpleDateFormat("MM/DD/YY");
   			Date date = formater.parse(line);
   		}
		// handle passing in the wrong type of URL.
   		catch(ParseException exception) {
			System.out.println(“Passing wrong type of Url::::”+exception);
		}
		// handle I/O problems.
		catch(IOException exception) {
			System.out.println(“IO exception:::::”+exception);
		}
		// handle date parse problems.
		catch(ParseException exception) {
   			System.out.println(“Date parse exception:::”+exception)	;	
		}
	}
}

The solution, if you wanted to have the same logic for two of the three cases above, say, the ParseException and the IOException, you can copy and paste the same code. But this is more for  inexperienced or lazy programmer that might think it would be okay to do the following:

public class ExceptionHandlingNovice
{
	public static void main( String[] args )
	{
   		try {
   			URL newUrl = new URL("http://www.yoursimpledate.server/");
   			BufferedReader reader = new 
				BufferedReader(new InputStreamReader(newUrl.openStream()));
   			String line = reader.readLine();
   			SimpleDateFormat formater = new SimpleDateFormat("MM/DD/YY");
   			Date date = formater.parse(line);
   		}
	// I am an inexperienced or lazy programmer here.
   		catch(Exception exception) {
			System.out.println(“Exception occured :::”+exception);
   		}
   	}
}

The biggest problem with the above code is that it could introduce unintended side effects. Any code in the try block could throw an exception that would be swallowed up with a blanket (Exception) catch clause. If an exception that is not a ParseException orIOException is thrown (for example, a SecurityException), the code would still catch it, but the upstream user would not be aware of what really happened. Swallowing up an exception like that makes problems difficult to debug.


In order to facilitate the programmer’s work, Java SE 7 now includes a multi-catch statement. This allows the programmer to combine a catch clause into a single block of code without the need to use a dangerous catch-all clause or copy entire blocks of code. 

public class ExceptionHandlingNew
{
	public static void main( String[] args )
	{
		try {
   			URL newUrl = new URL("http://www.yoursimpledate.server/");
   			BufferedReader reader = new BufferedReader(
   				new InputStreamReader(url.openStream()));
   			String line = reader.readLine();
   			SimpleDateFormat formater = new SimpleDateFormat("MM/DD/YY");
   			Date date = formater.parse(line);
   		}
	        // handle our problems here.
   		catch(ParseException | IOException exception) {
			System.out.pritnln(“Exception occured ”+exception);
   		}
   	}
}

I hope you will use multi-catch feature of Java SE7 for handling multiple exceptions.

Making HTTP DELETE method request


In this blog, I am going to share the information about making DELETE request in Java.First of all let’s go through the definition.


The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method may be overridden by human intervention (or other means) on the origin server.

The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server should not indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.


A successful response should be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.
If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries should be treated as stale. Responses to this method are not cacheable.


Let’s move through the implementation:


I have used the apache http client jar for making Http request of any method type.
Maven dependency is given below:

	org.apache.httpcomponents
	httpclient
	4.3.1

Create a method that will make a HttpDelete request:

private HttpDelete createDeleteReq(String restUrl,String accessToken)
{
	HttpDelete httpDelete=new HttpDelete(restUrl);
	httpDelete.addHeader(“Authorization”,”OAuth”+" "+accessToken));
	httpDelete.addHeader(“Host”,”your_host_name”);
	httpDelete.addHeader(“User-Agent”,"your_client_name");
	return httpDelete;
}

Create another method that will execute the request:

private String executeDeleteReq(HttpDelete httpDeleteRequest)
{
	HttpClient client = HttpClientBuilder.create().build();
	HttpResponse response=null;
	try {
		response = client.execute(httpDeleteRequest);
	} catch (ClientProtocolException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	log.debug("Response Code : " + response.getStatusLine().getStatusCode()+"Response status:::"+response.getStatusLine());
	BufferedReader rd=null;
	try {
		rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
	} catch (IllegalStateException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	StringBuffer result = new StringBuffer();
	String line = "";
	try {
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
	JSONParser parser=new JSONParser();
	JSONObject jsonResponse=new JSONObject();
	try {
		jsonResponse=(JSONObject)parser.parse(result.toString());
	} catch (ParseException e) {
		e.printStackTrace();
	}
	return jsonResponse.toString();
}

Now call these methods for getting response:

public void testDeleteMethod()
{
	HttpDelete httpDelete =createDeleteReq(restUrl,accessToken);
	String jsonResponse=executeDeleteReq(httpDelete);
	log.debug(“Response for calling Put request:::::::”+jsonResponse);
}

Note :Parameter may vary and depends on the header parameter.I am using OAuth client-server ,that’s why accessToken and other parameter set in the header.

 

 

 

Thanks,
Kundan Ray

Making HTTP PUT method request

In this blog I am going to share the information about making HTTP PUT request in Java. First of all let’s go through the definition.


The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity should be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI. If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response.

If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes should be sent to indicate successful completion of the request. If the resource could not be created or modified with the Request-URI, an appropriate error response should be given that reflects the nature of the problem.

The recipient of the entity must not ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and must return a 501 (Not Implemented) response in such cases. 

Let’s move through the implementation:
I have used the apache http client jar for making Http request of any method type.
Maven dependency is given below:

	org.apache.httpcomponents
	httpclient
	4.3.1

Create a method that will make a HttpPut request:

private HttpPut createPutReq(String restUrl,String accessToken,String jsonData)
{
	HttpPut httpPut=new HttpPut(restUrl);
	httpPut.addHeader(OAuthFieldName.AUTHORIZATION.toString(),(OAuthFieldName.OAUTH.toString()+" "+ accessToken));
	httpPut.addHeader(OAuthFieldName.HOST.toString(),"your_host”);
	httpPut.addHeader(OAuthFieldName.USER_AGENT.toString(),”your_client”);
	try {
		httpPut.setEntity(new StringEntity(jsonData));
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	return httpPut;
}

Create another method that will execute the request:

private String executePutLightSpeedReq(HttpPut httpPut)
{
	HttpResponse response=null;
	String line = "";
	StringBuffer result = new StringBuffer();
	HttpClient client = HttpClientBuilder.create().build();
	try {
		response = client.execute(httpPut);
	} catch (ClientProtocolException e) {
			e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	log.debug("Response Code : " +response.getStatusLine().getStatusCode());
	BufferedReader reader=null;
	try {
		reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
	} catch (IllegalStateException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	try {
		while ((line = reader.readLine()) != null){ result.append(line); }
	} catch (IOException e) {
		e.printStackTrace();
	}
	org.json.JSONObject jsonResponse=XML.toJSONObject(result.toString());
	log.debug("jsonResponse ::::"+jsonResponse.toString());
	return jsonResponse.toString();
}

Now call these methods for getting response:

public void testPutMethod()
{
	HttpPut httpPut  =createPutReq(restUrl,accessToken,jsonData);
	String jsonResponse=executePutLightSpeedReq(put);
	log.debug(“Response for calling Put request:::::::”+jsonResponse);
}

Note :Parameter may vary and depends on the header parameter.I am using OAuth client-server ,that’s why accessToken and other parameter set in the header.

 

Thanks,
Kundan Ray

OAuth 2.0 implementation in Spring Framework

In this blog , I am going to share OAuth 2.0 implementation in Spring. Unlike from my last blog this will automatically handle response code come to the redirect uri. I also want to show you the flow during OAuth 2.0 implementation.

Your application sends a token request to the Google Authorization Server, receives an authorization code, 
exchanges the code for a token, and uses the token to call a Google API endpoint.

Image source -google.com

In the above  image it is clear the process of Open authentication.First your application make a request to get the token to the server.In the response server authenticate the user by asking userid and password.After successful login of the user , server return the Authorization code on the redirect url. Now using this authorization code in request we get the access token in response.We can now call the api methods of the server using this access token. 
Now move through the code for implementing it. I am using Apache Oltu library.
Maven dependency of Oltu library have to write in pom.xml is:

	org.apache.oltu.oauth2
		org.apache.oltu.oauth2.client
		1.0.0

Create controller let name it to OAuthController.java

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class OAuthController 
{
	public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse response) throws OAuthSystemException, IOException{
		OAuthClientRequest request=null;
		request = OAuthClientRequest
					.authorizationLocation(“your server’s auth location ”)
					.setResponseType(“code”)
					.setState("1")
					.setClientId("your client id")
					.setRedirectURI("http://localhost:8080/Scheduler/auth/kounta/callback.html")
					.buildQueryMessage();
		System.out.println("Url for redirecting::::"+request.getLocationUri());
		return new ModelAndView("redirect:"+request.getLocationUri());
	}
}

Create callback controller let call it AuthCallbackController.java

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
import org.apache.oltu.oauth2.client.response.OAuthAuthzResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class AuthCallbackController 
{
		public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) 
			throws IOException, OAuthSystemException, OAuthProblemException {
		OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
		String stateResponse = oar.getState();
		if (stateResponse.equals("")) {
			return new ModelAndView("posIndex","message", "Unsuccessful");
		}
		OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
		OAuthAccessTokenResponse oAuthResponse = getAccessToken(oar, oAuthClient);
		System.out.println("Hey I am getting access token::::"+oAuthResponse.getAccessToken());
		return new ModelAndView("posIndex","message", "successful");
	}

	private OAuthAccessTokenResponse getAccessToken(OAuthAuthzResponse oar, OAuthClient oAuthClient)
			throws OAuthSystemException, OAuthProblemException {
		String code = oar.getCode();
		OAuthClientRequest request = OAuthClientRequest
				.tokenLocation("your server’s token location")
				.setGrantType(GrantType.AUTHORIZATION_CODE)
				.setClientId("your client id")
				.setClientSecret("your client secret")
				.setCode(code)
				.setRedirectURI("http://localhost:8080/Scheduler/auth/kounta/callback.html")
				.buildBodyMessage();
		OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(request);
		return oAuthResponse; 
	}
}

Define bean of above classes in your servlet mapping xml file.



		
oAuthController
			authCallbackController



Run your application and hit http://localhost:8080/sa/authorize.hhtml and this will ask you for authentication (userid and password) .After successful authentication ,it will redirect you to your rediect url which is http://localhost:8080/auth/kounta/callback.html. The controller mapped for this url is AuthCallbackController. This controller will receive code in response and using this code we will get the access token.


Thanks,
Kundan Ray

OAuth 2.0 implementation in Java

OAuth is an authentication and authorization  system stands for Open Standard for Authorization. It provides the application secure access to server resources.The main thing about the OAuth is that we do not need to share the server credentials.It is specifically desined to work with HTTP.

OAuth provides an access token with the approval of the resource owner.After getting the access token from the resource owner we can call the API methods or more simply we can say that we can access the resources hosted by the resource server.
It is highly recommended for use one of the library that support all the OAuth setup stuff. There are many libraries that provide the OAuth setup.


For java there are the following libraries that supports the OAuth implementation.

  • Apache Oltu
  • Spring Social
  • Spring Security for OAuth
  • Restlet Framework (draft 30)
  • scribe-java  

I am using Apache Oltu library for OAuth 2.0 implementation. The maven dependency of Apache Oltu is:

 

	org.apache.oltu.oauth2
		org.apache.oltu.oauth2.client
		1.0.0

 

OAuth implementation consist of two steps for getting token from server.In the first step we receive code in the response .After that we again make a request with code and get access token from the server.

 

So let’s move to the coding for getting code or temporary token and after using this code or temporary token we will get the access token.

 

public void OauthMethod(String authLocation,String clientId,String clientSecret,String redirectUri,String tokenLocation)
{
	String accessToken="";
	OAuthClientRequest outhReq=null;
	try {
		outhReq = OAuthClientRequest
			.authorizationLocation(authLocation)
			.setResponseType("code")
			.setState("1")
			.setClientId(clientId)
			.setRedirectURI(redirectUri)
			.buildQueryMessage();
	} catch (OAuthSystemException e) {
		e.printStackTrace();
	}
	//in web application you make redirection to uri:
	log.debug("Visit: " + request.getLocationUri() + "\nand grant permission");
	log.debug("Now enter the OAuth code you have received in redirect uri ");
	OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	String tempCode="";
	try {
		tempCode = br.readLine().trim();
	} catch (IOException e) {
		e.printStackTrace();
	}
	try {
		outhReq = OAuthClientRequest
			.tokenLocation(tokenLocation)
			.setGrantType(GrantType.AUTHORIZATION_CODE)
			.setClientId(clientId)
			.setClientSecret(clientSecret)
			.setCode(code)
			.setRedirectURI(redirectUri)
			.buildBodyMessage();
	} catch (OAuthSystemException e) {
		e.printStackTrace();
	}
	OAuthAccessTokenResponse oAuthResponse=null;
	try {
		oAuthResponse = oAuthClient.accessToken(outhReq);
	} catch (OAuthSystemException e) {
		e.printStackTrace();
	} catch (OAuthProblemException e) {
		e.printStackTrace();
	}
	token=oAuthResponse.getAccessToken();
	log.debug("Access Token:"+accessToken);
	log.debug("Expires in: "+oAuthResponse.getExpiresIn()+",Refresh token:"+oAuthResponse.getRefreshToken());
}

 

It will create a url like https://secure.vendhq.com/connect?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&client_id=owhVnBVLtFJGkdDbR3HeGwqbBLv54cl8 and after hitting this url we will get code in the url like http://localhost:8080/auth?code=cd4Frtd9jbddsdffddssg

Please enter the code as an input for the application. The application use the code for making request for getting access token.

This process will be common to all of the websites that are using OAuth 2.0 like facebook, twitter, linkedin, Lightspeed, Kounta and Vend and you have to register the client on their site.


Now we will able to access their API with the access token , some OAuth provider token expires in a particular duration and need to be refreshing using refresh token. This is a sample application for getting access token .I will cover more real approach in the next blog for getting access token in Spring framework.If you have any problem in getting access token through this ,please feel free to comment your queries.

 

Thanks,
Kundan Ray

Implementing Many to Many in Grails
 
Understanding and implementing relationship among the tables is very important thing.This is a very important step where , we maintain the relationship among tables or more properly among domain.There are basically four types of relationship (A)One-to-One (B)One-to-Many (C)Many-to-One , and (D)Many-to-Many. I am not going to describe all of the relationship in this blog. I am going to describe and implement Many-to-Many relationship. As the name  suggest “Many-to-Many” means many object can be dependent on many other particular object.
 
Let see examples, like relationship between Students and Subjects is Many-to-Many relationship. Think, Many Students can have Many Subjects paper.Let see second example ,the relationship between the Products and Supplier.In this example Many Products can have many Supplier. Let’s move forward for our first step which is domain design.I am assuming that you already have basic practical knowledge of Grails,so I am not going to describe you much  about how  you would create domain class,controller class.
 
Create a Grails project and then create two domain class (i)Student (ii) Subject
 
Student.java look like this:
class Student 
{
	String studentName
	int age
	static hasMany = [subjects:Subject]
    static constraints = {
    }
}
And the second domain class look like this:
class Subject 
{
	String subjectName
	static hasMany = [students:Student]
	static belongsTo = Student
    static constraints = {
    }
}
In the above domain we have done the hasMany mapping through this a Many-to-Many relationship is established between Student and Subject. So , how this mapping is going to maintain behind the scene.This mapping will automatically create a database table to maintain the relationship between Student and Subject student_subjects.There will be two fields or we can say that foreign key exist subject_id and student_id. Belongs to mapping tells that the Subject is belongs to Student that means , if we are deleting the Student then the Subject_id assigned to this Student in the Student_Subjects table will be deleted automatically. Note that we cannot delete the Subject unless deleting the row from the Student_Subjects table because of if we delete the subject we are going to violate the referencial integrity constraints.
 
 
Let’s create a controller to perform some operations:
class StudentControlController 
{
	def saveData()
    {
		Student student=new Student(studentName:'Ajeet’',age:23).save()
		Subject eng=new Subject(subjectName:'English').save()
		Subject civ=new Subject(subjectName:'Civics').save()
		Subject geo=new Subject(subjectName:'Geography').save()
		student.addToSubjects(eng)
		student.addToSubjects(civ)
		student.addToSubjects(geo)
		if(!student.save())
			println 'error while saving'
		else
			println 'Data saved'
	}
}
 
This way we are adding three subjects with one student.The student_subjects table will look like this.
student_id | subject_id 
------------+------------
          1 |          1
          1 |          2
          1 |          3
 
We can also add the many students with one subject like above. And now we can retrieve the data easily.Let’s we have to retrieve Subjects associated with the Student which has id 1.
def retreiveData()
{
	Student student = Student.get(1)
	println 'Subjects associated with the Student::::’'+student.subjects
}
 
I think this will help you in implementing Many-to-Many relationship.
 
 
 
Thanks
Custom Login with Spring Security

I have used the Spring Security plugin in my grails project where i felt need for customize the login of Spring Spring Security core. In this blog I am going to share the information about how can you customize Spring Security Login in your project. I assume that you have used the spring security plugin and know the power of spring security.

In my case revision control was the reason for customizing the login process. If you know then in revision control we do not delete any row of the table ,instead of deleting the row we only update a field (like isDeleted) to true when updating or deleting a row. So, i had need to only login the user which has isDeleted field false in addition to username and password. I have used the email as the username of user.

There is a custom authentication provider custom.login.auth.UserAuthenticationProvider which process the subclass of custom.login.UserAuthentication  that adds isDeleted property and a filter custom.login.ui.UserFilter that creats the authentication from request and initiates the authentication.

Here is class definition for UserAuthentication.groovy in src/groovy.
package custom.login
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken

class UserAuthentication extends UsernamePasswordAuthenticationToken
{
	private static final long serialVersionUID = 1
	final boolean deleted
	
	UserAuthentication(principal, credentials, boolean isDeleted)
	{
		super(principal, credentials)
		deleted = isDeleted
	}
	UserAuthentication(principal, credentials, boolean isDeleted, Collection authorities)
	{
		super(principal, credentials, authorities)
		deleted = isDeleted
	}
}
UserAuthenticationProvider.groovy in src/groovy.
package custom.login.auth
import grails.plugin.springsecurity.userdetails.GormUserDetailsService
import grails.plugin.springsecurity.userdetails.GrailsUser
import custom.login.UserAuthentication

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.security.authentication.AuthenticationProvider
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.dao.SaltSource
import org.springframework.security.authentication.encoding.PasswordEncoder
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UserDetailsChecker
import org.springframework.security.core.userdetails.UsernameNotFoundException

class UserAuthenticationProvider implements AuthenticationProvider
{
	protected final Logger log = LoggerFactory.getLogger(getClass())
	def springSecurityService
	PasswordEncoder passwordEncoder
	SaltSource saltSource
	UserDetailsChecker preAuthenticationChecks
	UserDetailsChecker postAuthenticationChecks
	Authentication authenticate(Authentication auth) throws AuthenticationException 
	{
		UserAuthentication authentication=auth
		String password = authentication.credentials
		String emailId = authentication.name
		boolean deleted = authentication.deleted
		GrailsUser userDetails
		def authorities
		Users.withTransaction { status ->
		Users user=Users.findByEmailIdAndDeleted(emailId,deleted)
		if (!user) {
			// TODO customize 'springSecurity.errors.login.fail' i18n message in app's messages.properties with org name
			log.warn "User not found:"
			throw new UsernameNotFoundException('User not found', emailId)
		}
		authorities = user.authorities.collect { new SimpleGrantedAuthority(it.authority) }
		authorities = authorities ?: GormUserDetailsService.NO_ROLES
		userDetails = new GrailsUser(user.emailId, user.password,
			user.enabled, !user.accountExpired, !user.passwordExpired,
			!user.accountLocked, authorities, user.id)
		}
		preAuthenticationChecks.check userDetails
		additionalAuthenticationChecks userDetails, authentication
		postAuthenticationChecks.check userDetails
		def result = new UserAuthentication(userDetails,
			authentication.credentials, deleted, authorities)
		result.details = authentication.details
		result
	}
	
	protected void additionalAuthenticationChecks(GrailsUser userDetails,
		UserAuthentication authentication) throws AuthenticationException 
	{
		
		def salt = saltSource.getSalt(userDetails)
		if (authentication.credentials == null) {
			log.debug 'Authentication failed: no credentials provided'
			throw new BadCredentialsException('Bad credentials', userDetails)
		}
		String presentedPassword = authentication.credentials
		if (!passwordEncoder.isPasswordValid(userDetails.password, presentedPassword, salt)) {
			log.debug 'Authentication failed: password does not match stored value'
			throw new BadCredentialsException('Bad credentials', userDetails)
		}
	}
	boolean supports(Class authenticationClass) {
		UserAuthentication.isAssignableFrom authenticationClass
	  }
}
UserFilter.groovy in src/groovy.
package custom.login.ui
import grails.plugin.springsecurity.web.authentication.RequestHolderAuthenticationFilter
import custom.login.UserAuthentication

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpSession

import org.springframework.security.authentication.AuthenticationServiceException
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.util.TextEscapeUtils

class UserFilter extends RequestHolderAuthenticationFilter
{
	UserFilter()
	{
		storeLastUsername=false;
	}
	@Override
	Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response)
			throws AuthenticationException 
	{
		if (!request.post) {
			throw new AuthenticationServiceException(
				"Authentication method not supported: $request.method")
		}
		String emailId = (obtainUsername(request) ?: '').trim()
		String password = obtainPassword(request) ?: ''
		boolean deleted = false
		def authentication = new UserAuthentication(emailId, password, deleted)
		HttpSession session = request.getSession(false)
		if (session || getAllowSessionCreation()) {
			request.session[SPRING_SECURITY_LAST_USERNAME_KEY] =TextEscapeUtils.escapeEntities(emailId)
		}
		setDetails request, authentication
		return getAuthenticationManager().authenticate(authentication)
	}
}
Do the bean registration in app/conf/spring/resources.groovy for the filter and the authentication provider app/conf/spring/resources.groovy
import grails.plugin.springsecurity.SpringSecurityUtils
import custom.login.auth.UserAuthenticationProvider
import custom.login.ui.UserFilter
beans = {
	def conf = SpringSecurityUtils.securityConfig
	// custom authentication
	authenticationProcessingFilter(UserFilter) {
		authenticationManager = ref('authenticationManager')
		sessionAuthenticationStrategy = ref('sessionAuthenticationStrategy')
		authenticationSuccessHandler = ref('authenticationSuccessHandler')
		authenticationFailureHandler = ref('authenticationFailureHandler')
		rememberMeServices = ref('rememberMeServices')
		authenticationDetailsSource = ref('authenticationDetailsSource')
		filterProcessesUrl = conf.apf.filterProcessesUrl
		usernameParameter = conf.apf.usernameParameter
		passwordParameter = conf.apf.passwordParameter
		continueChainBeforeSuccessfulAuthentication = conf.apf.continueChainBeforeSuccessfulAuthentication
		allowSessionCreation = conf.apf.allowSessionCreation
		postOnly = conf.apf.postOnly
	}
	// custom authentication
	daoAuthenticationProvider(UserAuthenticationProvider) {
		passwordEncoder = ref('passwordEncoder')
		saltSource = ref('saltSource')
		preAuthenticationChecks = ref('preAuthenticationChecks')
		postAuthenticationChecks = ref('postAuthenticationChecks')
	}
}
This way I was able to customize the spring security login process that is like a hack to spring security.
 
Thanks
Kundan Ray
 

 

Steps to use Kontakt Beacon

In this blog i am going to share the information about requirements and steps needed to use a Kontakt Beacon:-

Requirements:-

  1. You should have at least one  beacon device.
  2. Kontakt login credential (it is automatically created after purchase beacon).
  3. An IOS mobile device with kontakt.io app(app is available in Apple store).

Steps:-

  1. Go to http://panel.kontakt.io/signin and enter the email address and password you used to order your Kontakt.ioBeacons.
  2. Add venue (generally venue is your beacon physical location) on clicking ADD VENUE button.Give name and description of the venue and click on save button.
  3. Your venue details now visible on the left side of the Kontakt CMS.Now click on manage button.You can set cover or delete the venue(optional step).
  4. Now you have to assign some venue to the beacon.The system will inform you about the unassigned beacons click on the here button (“You have  unassigned beacons. Go here to manage them”).
  5. Now you have a list of unassigned beacons.You will also see the beaconid proximityU major and minor value .Assign beacon with the venue by clicking “Assign to” button from the top right side of the list.Choose one venue from the drop down menu.
  6. Adding Action to the Beacons:-To assign an Action to a Beacon, go to main Venue page where you see the list of assigned Beacons. Select one  or more of the Beacons from the list, and select the ‘Manage’ and then ‘Add Action’ buttons.Action is what that makes your beacon to do something in response to an event (Assume the event triggers when the mobile device come into the range of Beacon) .
  7. Lets add a action, content action .Upload a file that gets sent to the target mobile device. You will also see an option to set the proximity of the Action. This determines how close you have to be in order for the Action to be triggered.Lets set the Immediate proximity action(range less than 1 meter).

Now Kotakt CMS configuration is done,we have to follow some steps to test the beacon on mobile device.

  1. Install kontakt.io app (mobile app) from Apple store.
  2. Launch it and Go to setting(kontakt.io) then login with your kontakt login credential.
  3. Now you can access your venue.
  4. When you enter the range of the beacon you will get notification that “New beacon found”.
  5. You can also see the beacon information by clicking “enter administrator mode”.You can also change the beacon properties from here like major,minor etc by providing the beacon password.You can get your beacon password from Kontakt CMS.

You can also use the Rest Api of Kontakt to get the information about Beacon,Venue,Manager and Action.
I used the beacon Rest Api in my Java program for getting  the specific Beacon information.Let say our beacon id is ZYWX,Kontakt username is [email protected] and password is abcd.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

public class HttpGetReq
{
	public static void main(String args[]) throws UnsupportedEncodingException
	{
		//Rest URL for showing specific beacon detail
		String restUrl="http://api.kontakt.io/beacon/"+beaconId;
		String username=yourkontaktusername;
		String password=kontaktpassword;
		HttpGetReq httpPostReq=new HttpGetReq();
		HttpGet httpPost=httpPostReq.createConnectivity(restUrl , username, password);
		httpPostReq.executeReq( httpPost);
	}

	HttpGet createConnectivity(String restUrl, String username, String password)
	{
		HttpGet get = new HttpGet(restUrl);
		String auth=new StringBuffer(username).append(":").append(password).toString();
		byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
		String authHeader = "Basic " + new String(encodedAuth);
		get.setHeader("Content-Type", "application/json");
		get.setHeader("Api-Key","TXBbxWrOVZfFtffLpmhubuGTdnbnmFGl");
		get.setHeader("Accept", "application/json");
		get.setHeader("AUTHORIZATION", authHeader);
		return get;
	}

	void executeReq( HttpGet httpPost)
	{
		try{
			executeHttpGetRequest( httpPost);
		}
		catch (UnsupportedEncodingException e){
			System.out.println("error while encoding api url : "+e);
		}
		catch (IOException e){
			System.out.println("ioException occured while sending http request : "+e);
		}
		catch(Exception e){
			System.out.println("exception occured while sending http request : "+e);
		}
		finally{
			httpPost.releaseConnection();
		}
	}

	void executeHttpGetRequest( HttpGet httpPost)  throws UnsupportedEncodingException, IOException
	{
		HttpResponse response=null;
		String line = "";
		StringBuffer result = new StringBuffer();
		HttpClient client = HttpClientBuilder.create().build();
		response = client.execute(httpPost);
		System.out.println("Response Code : " +response.getStatusLine().getStatusCode());
		BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		while ((line = reader.readLine()) != null){ result.append(line); }
		System.out.println(result.toString());
	}
}

The output will receive as a json look like this:

{"id":"9abf0349-b988-45e5-8ef1-11aeb2dbda31","serial":null,"alias":null,"proximity":"f7826da6-4fa2-4e98-8024-bc5b71e0893e","major":64284,"minor":5797,"password":"6LHV","uniqueId":"ZYWX","txPower":3,"interval":350,"name":"Kontakt","venue":{"id":"114135fb-783a-4072-828d-ed2b87e9d7f1","name":"oodles technologies","description":"FF307E Gurgaon","lat":null,"lng":null,"priv":true,"coverType":"image/jpeg","beacons":[],"users":[],"rates":[],"managers":[],"beaconsCount":1},"browserActions":[],"contentActions":[{"actionType":"CONTENT","id":"4bf2f932-9822-49b5-be36-093779c0c77c","actionType":"CONTENT","distance":null,"proximity":"IMMEDIATE","beacon":null,"owner":{"id":"f746c7f3-aa6a-42ca-ba1d-05a2f8908299","email":null,"password":null,"salt":null,"company":null,"venues":null,"active":false},"contentCategory":"IMAGE","contentType":"image/jpeg","contentLength":7761,"impairmentTypes":[]}],"urlRequestActions":[],"actionsCount":1}

Add maven dependency to pom.xml.

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.3</version>
</dependency>

 

Thanks

Kundan Ray

Introduction to iBeacon or Beacon

In this blog i am going to share the information about Beacon or iBeacon.

 

Beacon and iBeacon is used exchangeably. It is a device that uses Bluetooth Low Energy for communicating with the devices (like mobile IOS and Android devices).This technology is first introduced by Apple.There are three property that has to be set for identifying beacon.

 

  1. Proximity UUID- UUID is of 16 bytes represent the company owning a number of iBeacons. Example: E2C56DB5-DFFB-48D2-B060-D0F5A71096E0.
  2. major- A 2 bytes integer typically used to represent a group of iBeacon.
  3. minor-A 2 bytes integer that identifies a specific iBeacon within a group.
    Ex-UUID:17888888-5555-3333-7777-555555555555 Major:1 Minor:1

Beacon device has some fixed range and When the phone comes into the range of a beacon, the app is notified about this, even if the phone is locked or the app is not currently running.So basically the beacon signal is identified by the mobile app.The app then communicate with the backend server to get notify.

Suppose you are entering a store and get notified with welcome message and some of the discount offer also come on your mobile screen and when you leave the store one notification also come on your mobile screen like “Thanks for visit”.This is a kind of application with the use of beacon device we can achieve.

Beacon can be useful to keep people  on time.From employees clocking in at a manufacturing plant to teachers taking attendance at school, beacons can save some time by replacing the dreaded time card. As a worker or pupil passes a beacon, their arrival and departure times will be retrieved.

How Beacon works:-

Below diagram shows how beacons work and an app get notify.

When apps detect the Beacon, they make use of these three numbers to deduce the (UUID,major,minor) location of the user. The application sends the numbers to a Beacon provider Backend server and fetches a list of promotional information related to beacon of the particular place(for ex a store). Mostly,the Beacon manufacturer has their own backend server and they provide some REST API to communicate with the application.For example Gimbal Beacon provider has its own server which is Gimbal manager server that provide a great interface for manage the beacon.

Activating beacon using  Gimbal REST API:-

 

URL-https://manager.gimbal.com/api/beacons
Request Type-POST
JDON DATA
    {
        "factory_id":"aaaa-bbbbb",
        "name":"Jony's Beacon",
        "latitude":XX.XXXXXX,
        "longitude":YY.YYYYYY,
        "config_id":wxyz,
        "visibility": "private"
    }

 

Factory Identifier Required-The unique identifier of the beacon.

Name Required-The developer provided name for the beacon.

Latitude-The latitude of the place where beacon is located.

Longitude-The longitude of the place where beacon is located.

Visibility-The visibility of the beacon to other organization. Visibility can be private or public.

Private visibility lock access the Beacon from unauthorized users.However public Beacon is visible to all the users. Generally most of the Beacons are transmitting their data in public mode.

 

 

 

Thanks

Kundan Ray

Implement Redis Publish_Subscribe messaging paradigm

I have implemented recently the Publish-Subscribe messaging paradigm in a project,so i am going to share the information about the Redis configuration and its implementation.

About Redis-
Redis is an open source, BSD licensed, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets. According to the monthly ranking by DB-Engines.com, Redis is the most popular key-value store.The name Redis means REmote DIctionary Server.

About Publish-Subscribe:-
Publish/subscribe is a pretty simple paradigm. Think of it like you're running a talk show on a radio station. That's PUBLISH. You're hoping at least one or more people will pick up your channel to listen to your messages on the radio show (SUBSCRIBE).Subscribers express interest in one or more channels, and only receive messages that are of interest, without knowledge of what (if any) publishers there are. This decoupling of publishers and subscribers can allow for greater scalability and a more dynamic network topology.
Installation of Redis-Server:-
Download, extract and compile Redis with:

$ wget http://download.redis.io/releases/redis-2.8.9.tar.gz
$ tar xzf redis-2.8.9.tar.gz
$ cd redis-2.8.9
$ make

The binaries that are now compiled are available in the src directory. Run Redis with:

$ src/redis-server

We can interact with Redis using the built-in client:

$ src/redis-cli
redis> set foo bar
OK
redis> get foo
"bar"

Installing Redis more properly:-
I assume you already copied redis-server and redis-cli executables under /usr/local/bin.
Create a directory where to store your Redis config files and your data:

sudo mkdir /etc/redis
sudo mkdir /var/redis

Copy the init script that you'll find in the Redis distribution under the utils directory into /etc/init.d.
I suggest calling it with the name of the port where you are running this instance of Redis. For example:

	sudo cp utils/redis_init_script /etc/init.d/redis_6379

Edit the init script.

sudo vi /etc/init.d/redis_6379

Make sure to modify REDIS_PORT accordingly to the port you are using. Both the pid file path and the configuration file name depend on the port number.
Copy the template configuration file you'll find in the root directory of the Redis distribution into /etc/redis/ using the port number as name, for instance:

sudo cp redis.conf /etc/redis/6379.conf

Create a directory inside /var/redis that will work as data and working directory for this Redis instance:

sudo mkdir /var/redis/6379

Edit the configuration file, making sure to perform the following changes:

Set daemonize to yes (by default it is set to no).
Set the pidfile to /var/run/redis_6379.pid (modify the port if needed).
Change the port accordingly. In our example it is not needed as the default port is already 6379.
Set your preferred loglevel.
Set the logfile to /var/log/redis_6379.log
Set the dir to /var/redis/6379 (very important step!)
Finally add the new Redis init script to all the default runlevels using the following command:
sudo update-rc.d redis_6379 defaults

You are done! Now you can try running your instance from terminal with:

/etc/init.d/redis_6379 start 

Make sure that everything is working as expected:
Try pinging your instance with redis-cli.
Do a test save with redis-cli save and check that the dump file is correctly stored into /var/redis/6379/ (you should find a file called dump.rdb).
Check that your Redis instance is correctly logging in the log file.
If it's a new machine where you can try it without problems make sure that after a reboot everything is still working.
Implementation of Publish-Subscribe from terminal:-
Run the Server:-

/etc/init.d/redis_6379 start

Start Redis built-in client:-

redis-cli
127.0.0.1:6379>ping
PONG (working correctly)

Now subscribe a channel named “message”

127.0.0.1:6379> subscribe message 
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "message"
3) (integer) 1

Now publish the data through message channel with new redis-cli(open second terminal tab)

 

	redis-cli
127.0.0.1:6379> publish message "how are u all"
(integer) 1
On the first tab you can see the message that is published
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "message"
3) (integer) 1
1) "message"
2) "message"
3) "how are u all"

Publish-Subscribe example in java through Redis java client(Jedis):-
We  need Jedis2.4.2 jar into our classpath for running it.
The maven dependency of Jedis is:-

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.4.2</version>
</dependency>

Java Program to implement Pub-Sub functionality:-
RedisPubSub.java

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisPubSub
{
    public static final String channel_name= "redisChannel";
    
    public static void main(String[] args) throws Exception
    {       
        JedisPool jedispool = new JedisPool("localhost");
        final Jedis subscriberJedis = jedispool.getResource();

        final Subscriber subscriber = new Subscriber();
        new Thread(new Runnable(){
            public void run()
            {
                try
                {
                    System.out.println("Subscribing to " +channel_name);
                    subscriberJedis.subscribe(subscriber,channel_name);
                    System.out.println("Subscription ended.");
                }
                catch (Exception e)
                {
                    System.out.println("Subscribing failed."+e);
                }
            }
        }).start();

        Jedis publisherJedis = jedispool.getResource();
        new Publisher(publisherJedis,channel_name).start();
        subscriber.unsubscribe();
        jedispool.returnResource(subscriberJedis);
        jedispool.returnResource(publisherJedis);
    }
}

Publisher.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import redis.clients.jedis.Jedis;
public class Publisher
{
    private final Jedis publisherJedis ;
    private final String channel_name;
 
    public Publisher(Jedis publisherJedis, String channel)
    {
           this.publisherJedis = publisherJedis;
            this.channel_name = channel;
    }
    public void start()
    {
    	System.out.println("Type your message....exit for terminate");
    	try 
	  {
        	BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
 
             while (true) 
             {
                  String line = reader.readLine();
                  if (!"exit".equals(line)) {
                     publisherJedis.publish(channel_name, line);
                    } 
		    else {
                            break;
                      }
            	}
     	}
 	catch (IOException e) {
                System.out.println("IO failure while reading input, e");
        }
    }
}

Subsciber.java

import redis.clients.jedis.JedisPubSub;
public class Subscriber extends JedisPubSub {
	@Override
	public void onMessage(String channel, String message) 
	{
        	System.out.println("Message received from channel: "+channel+ " Msg: " + message);
 	}
	@Override
        public void onPMessage(String pattern, String channel, String message) {
        }
	@Override
        public void onSubscribe(String channel, int subscribedChannels) {
	}
	@Override
        public void onUnsubscribe(String channel, int subscribedChannels) {
	}
	@Override
        public void onPUnsubscribe(String pattern, int subscribedChannels) {
	}
	@Override
        public void onPSubscribe(String pattern, int subscribedChannels) {
	}
     }

When you run the RedisPubSub the output will be look like this:

When you run the RedisPubSub the output will be look like this:
Type your message....exit for terminate
Subscribing to redisChannel
hello!!
Message received from channel: redisChannel Msg: hello!!

 

Thanks
Kundan Ray

Implement RabbitMQ for JMS

In this blog i am going to share the information about how to configure and implement RabbitMQ in your project.

About:-
It is an open source message broker software that implement the advance message Queueing protocol .In simple words we can say that it implement publish(sending) and subscribe (receiving) channel.We can take a real world example when we only once  subscribe for the newspaper and it daily comes to us through a channel(newspaper man). RabbitMQ is fast becoming the messaging server of choice in multiple sectors because it offers a consistent and interoperable approach to messaging across any platform.RabbitMq is equally well suited for server side,browser,mobile phones or cloud cases.

Here P is producer or simply you can call it Sender that sends the Data through channel hello. C is consumer or you can call it Receiver that receives data sent by the Sender. One point to note is that the name of the Queuechannel must be same on both of the end.

Configuring RabbitMQ Server:-

We will need an AMQP server,  to use with the client library. We can download from-http://www.rabbitmq.com/download.html


Install the rabbitmq-server_3.2.4-1_all.deb.


Add Java AMQP client library to project in build path. We can download it from http://www.rabbitmq.com/releases/rabbitmq-java-client/v3.3.1/rabbitmq-java-client-bin-3.3.1.zip


The RabbitMQ Java AMQP library is available as a Maven artifact on the central maven repository and mirrors thereof.  To include it in project, add this dependency to  pom.xml:

<dependency>
  <groupId>com.rabbitmq</groupId>
  <artifactId>amqp-client</artifactId>
  <version>3.3.1</version>
</dependency>


Now we can use RabbitMQ Java AMQP library in our project.

Java code to implement RabbitMQ
Sender.java

 

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
public class Sender {
	private final static String queue_name = "myQueue";
	public static void main(String[] argv) throws Exception {
	      ConnectionFactory factory = new ConnectionFactory();
	      factory.setHost("localhost");
	      Connection con = factory.newConnection();
	      Channel rabbitChannel = con.createChannel();
          rabbitChannel.queueDeclare(queue_name, false, false, false, null);
	      for(int i=0;i<10;i++)
	      {
	      	String msg = "Hello !! This is Oodles Tech. Pvt. Ltd ";
	      	rabbitChannel.basicPublish("",queue_name, null, msg.getBytes());
	      	System.out.println(" ….Sent '" + msg + "'");
	      	Thread.sleep(1000);
	    }
	    rabbitChannel.close();
	    con.close();
	  }
}

Receiver.java

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
public class Receiver {
    private final static String queue_name = "myQueue";
    public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection con = factory.newConnection();
    Channel rabbitChannel = con.createChannel();
    rabbitChannel.queueDeclare(queue_name, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    QueueingConsumer rabbitConsumer = new QueueingConsumer(rabbitChannel);
    rabbitChannel.basicConsume(queue_name, true,rabbitConsumer);
    while (true) {
        QueueingConsumer.Delivery delivery = rabbitConsumer.nextDelivery();
        String msg = new String(delivery.getBody());
        System.out.println(" …. Received '" + msg + "'");
    }
  }
}

Output will look like this after ruuning Sender.java :-

….Sent 'Hello !! This is Oodles Tech. Pvt. Ltd '
….Sent 'Hello !! This is Oodles Tech. Pvt. Ltd '
….Sent 'Hello !! This is Oodles Tech. Pvt. Ltd '
….Sent 'Hello !! This is Oodles Tech. Pvt. Ltd '
….Sent 'Hello !! This is Oodles Tech. Pvt. Ltd '

And output will look like this after running Receiver.java

[*] Waiting for messages. To exit press CTRL+C
…. Received 'Hello !! This is Oodles Tech. Pvt. Ltd '
…. Received 'Hello !! This is Oodles Tech. Pvt. Ltd '
…. Received 'Hello !! This is Oodles Tech. Pvt. Ltd '
…. Received 'Hello !! This is Oodles Tech. Pvt. Ltd '
…. Received 'Hello !! This is Oodles Tech. Pvt. Ltd '

Thanks
Kundan Ray
 

 

Banner

Don't just hire talent,
But build your dream team

Our experience in providing the best talents in accordance with diverse industry demands sets us apart from the rest. Hire a dedicated team of experts to build & scale your project, achieve delivery excellence, and maximize your returns. Rest assured, we will help you start and launch your project, your way – with full trust and transparency!