Apr 28, 2018

How to Convert JSON String to Java Object and Java Object to JSON String : Use Jackson API to convert JSON to Java Object

In previous post we saw how to convert JSON String to JSON Object(JsonNode) and retrieve information from it. In this post we will convert JSON string to Java class and it is very common use case when we are working with JSON in java application. Using Jackson API(a high-performance JSON processor for Java) we can convert JSON string to Java Object and vice versa

JSON String to Java Object : Using jackson ObjectMapper class we create mapper Object and readValue() method convert Sting to Java Object(specified in readValue method).
/*Creating Jackson Object Mapper*/
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
/* Converting JSON String to Employee Object */
Employee employee = objectMapper.readValue(jsonString, Employee.class);

Java Object to JSON String : Using jackson ObjectMapper class we create mapper Object and writeValueAsString() method convert Java Object to String.
ObjectMapper objectMapper = new ObjectMapper();
/* To suppress serializing properties with null value */
objectMapper.setSerializationInclusion(Include.NON_NULL);
/* To pretty print JSON String */
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String employeeJSON = objectMapper.writeValueAsString(employeeObject);

Sample Program : Below method convertJsonStringToJavaObject() convert JSON response into Employee Object and method convertJavaObjectToJSONString() convert Employee object to JSON String.

package com.devinline.jackson;

import java.io.IOException;
import java.util.Scanner;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
 * 
 * @author nikhil(www.devinline.com)
 * 
 */
public class JSONStringToJavaObject {
 public static final String jsonInput  = "{\n" + 
   "            \"employeeId\": \"ORA098\",\n" + 
   "            \"department\": \"PSR-CP\",\n" + 
   "            \"personalDetail\":{\n" + 
   "                \"firstName\": \"Nikhil\",\n" + 
   "                \"lastName\": \"Ranjan\",\n" + 
   "                \"address\": {\n" + 
   "                    \"addressLineOne\": \"House# 206\",\n" + 
   "                    \"addressLineTwo\": \"SLS APRTMENT\",\n" + 
   "                    \"zip\": 560043,\n" + 
   "                    \"state\": \"Karnataka\",\n" + 
   "                    \"country\": \"INDIA\",\n" + 
   "                    \"landmark\": \"HSR Layout\"\n" + 
   "                },\n" + 
   "                \"bloodGroup\": \"O+\"\n" + 
   "            },\n" + 
   "            \"designation\": \"Senior Engineer\"\n" + "        }";

 public static void main(String[] args) {
  System.out.println("\n1. JSON String to Java Object : ");
  System.out.println("\n2. JAVA Object to JSON String : ");
  System.out.println("\nEnter your choice: ");
  Scanner sc = new Scanner(System.in);
  int choice = sc.nextInt();
  
  switch (choice) {
  case 1:
   convertJsonStringToJavaObject();
   break;
  case 2:
   convertJavaObjectToJSONString();
  default:
   break;
  }
  sc.close();
 }

 private static void convertJsonStringToJavaObject() {
  ObjectMapper objectMapper = new ObjectMapper();
  /*
   * DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES added to deal with JSONs
   * with unknown properties
   */
  objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  try {
   /* Converting JSON String to Employee Object */
   Employee employee = objectMapper.readValue(jsonInput, Employee.class);
   System.out.println("***** Accessing Employee Object *****");
   System.out.println("Blood group of " + employee.getPersonalDetail().getFirstName() + " is "
     + employee.getPersonalDetail().getBloodGroup());
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 private static void convertJavaObjectToJSONString() {
  ObjectMapper objectMapper = new ObjectMapper();
  /*
   * To suppress serializing properties with null values
   */
  objectMapper.setSerializationInclusion(Include.NON_NULL);
  /* To pretty print JSON String */
  objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
  Employee employee = getEmployeeObjet();
  try {
   String employeeJSON = objectMapper.writeValueAsString(employee);
   System.out.println("***** Employee JSON String is ******** \n " + employeeJSON);
  } catch (JsonProcessingException e) {
   e.printStackTrace();
  }

 }

 private static Employee getEmployeeObjet() {
  Employee employee = new Employee();
  employee.setDepartment("PSR-CP");
  employee.setEmployeeId("ORA098");
  employee.setDesignation("Senior Engineer");
  PersonalDetail pdtail = new PersonalDetail();
  pdtail.setBloodGroup("O+ve");
  pdtail.setFirstName("Nikhil");
  pdtail.setLastName("Ranjan");
  Address address = new Address();
  address.setAddressLineOne("House# 206");
  address.setAddressLineTwo("SLS APRTMENT");
  address.setCity("Bangalore");
  address.setCountry("India");
  address.setLandmark("HSR LAYOUT");
  address.setZip("560043");
  pdtail.setAddress(address);
  employee.setPersonalDetail(pdtail);
  return employee;
 }

}

Sample output:

1. JSON String to Java Object :
2. JAVA Object to JSON String :

Enter your choice:
2

***** Employee JSON String is ********
 {
  "employeeId" : "ORA098",
  "department" : "PSR-CP",
  "personalDetail" : {
    "firstName" : "Nikhil",
    "lastName" : "Ranjan",
    "bloodGroup" : "O+ve",
    "address" : {
      "addressLineOne" : "House# 206",
      "addressLineTwo" : "SLS APRTMENT",
      "landmark" : "HSR LAYOUT",
      "city" : "Bangalore",
      "zip" : "560043",
      "country" : "India"
    }
  },
  "designation" : "Senior Engineer"
}
-------------
1. JSON String to Java Object : 
2. JAVA Object to JSON String : 

Enter your choice: 
1
***** Accessing Employee Object *****
Blood group of Nikhil is O+



Reference: 

How to convert JSON String to JSON Object and fetch Specific part of JSON : Without specifying Java Class name convert JSON string to Object

It is common use case to retrieve information from JSON without converting in into Java Object. Suppose we retrieve a JSON string as response from some service and we want to retrieve some information from it and we do not have Java  class which response can directly map to.

If we have Java class available we can directly map response with Java class using readvalue() API of Jackson as follows:
objectMapper.readValue(responseString, <RESPONSE_CLASS_NAME>.class);

Suppose we do not have RESPONSE_CLASS available or we do not want to map whole response to any Java class & retrieve information from JSON directly.

Using Jasckosn JsonNode : Convert JSON String to JsonNode and access Json as key/value from tree structure. We can reach from one node to another node and retrieve details without converting into Java class.

Consider below JSON String response and our goal is to find Blood group of all employees.
{
 "status": "SUCCESS",
 "payload": {
  "employees": [{
    "employeeId": "015823300000500788",
    "department": "1524637468898",
    "personalDetails": {
     "firstName": "Nikhil",
     "lastName": "Ranjan",
     "address": {
      "addressLineNumber1": "House# 206",
      "addressLineNumber2": "SLS APRTMENT",
      "zip": 560043,
      "state": "Karnataka",
      "country": "INDIA",
      "landmark": "HSR Layout"
     },
     "bloodGroup": "O+"
    },
    "designation": "Senior Engineer"
   },
   {
    "employeeId": "015823300000500788",
    "department": "1524637468898",
    "personalDetails": {
     "firstName": "Rahul",
     "lastName": "kant",
     "address": {
      "addressLineNumber1": "House# 96",
      "addressLineNumber2": "ARP Road",
      "zip": 560086,
      "state": "Karnataka",
      "country": "INDIA",
      "landmark": "BTM Layout"
     },
     "bloodGroup": "B+"
    },
    "designation": "Lead Engineer"
   }
  ]
 }
}

Sample program:
Here we have used Jackson cor API jar and converted JSON string to JsonNode and later retrieved list of all employees as ArrayNode. Iterate ArrayNode and retrieve relevant information forn JsonNode.

package com.devinline;

import java.io.IOException;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
/**
 * 
 * @author nikhil(www.devinline.com)
 * 
 */
public class JSONStringToObject {

 public static void main(String[] args) throws IOException {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  /*Convert JSON String to JsonNode */
  JsonNode responseJsonNode = objectMapper.readTree(response);
  /*Retrieve payload node from JsonNode */
  JsonNode payloadJsonNode = responseJsonNode.get("payload");
  /*Retrieve Employees list node from payload */
  ArrayNode employeesArray = (ArrayNode) payloadJsonNode.get("employees");
  
  /*Iterate over ArrayNode and retrieve details*/
  for (JsonNode employee : employeesArray) {
   JsonNode personalDetailsNode = employee.get("personalDetails");
   String bloodGroup = personalDetailsNode.get("bloodGroup").asText();
   String firstName = personalDetailsNode.get("firstName").asText();
   System.out.println("Blood group of " + firstName + " is : " + bloodGroup);
  }

 }

 public static final String response = "{\n" + 
   "\"status\": \"SUCCESS\",\n" + 
   "\"payload\": {\n" + 
   "    \"employees\": [\n" + 
   "        {\n" + 
   "            \"employeeId\": \"015823300000500788\",\n" + 
   "            \"department\": \"1524637468898\",\n" + 
   "            \"personalDetails\":{\n" + 
   "                \"firstName\": \"Nikhil\",\n" + 
   "                \"lastName\": \"Ranjan\",\n" + 
   "                \"address\": {\n" + 
   "                    \"addressLineNumber1\": \"House# 206\",\n" + 
   "                    \"addressLineNumber2\": \"SLS APRTMENT\",\n" + 
   "                    \"zip\": 560043,\n" + 
   "                    \"state\": \"Karnataka\",\n" + 
   "                    \"country\": \"INDIA\",\n" + 
   "                    \"landmark\": \"HSR Layout\"\n" + 
   "                },\n" + 
   "                \"bloodGroup\": \"O+\"\n" + 
   "            },\n" + 
   "            \"designation\": \"Senior Engineer\"\n" + 
   "        },\n" + 
   "        {\n" + 
   "            \"employeeId\": \"015823300000500788\",\n" + 
   "            \"department\": \"1524637468898\",\n" + 
   "            \"personalDetails\":{\n" + 
   "                \"firstName\": \"Rahul\",\n" + 
   "                \"lastName\": \"kant\",\n" + 
   "                \"address\": {\n" + 
   "                    \"addressLineNumber1\": \"House# 96\",\n" + 
   "                    \"addressLineNumber2\": \"ARP Road\",\n" + 
   "                    \"zip\": 560086,\n" + 
   "                    \"state\": \"Karnataka\",\n" + 
   "                    \"country\": \"INDIA\",\n" + 
   "                    \"landmark\": \"BTM Layout\"\n" + 
   "                },\n" + 
   "                \"bloodGroup\": \"B+\"\n" + 
   "            },\n" + 
   "            \"designation\": \"Lead Engineer\"\n" + 
   "        }\n" + 
   "    ]\n" + 
   "}\n" + 
   "}";
 }

Sample Output
:

Blood group of Nikhil is : O+
Blood group of Rahul is : B+

Pom.xml entry for jackson jar
:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.5</version>
</dependency>

Reference:
https://github.com/zytham/JSONPlayWithJackson

Apr 25, 2018

Get started with Cassandra Query Language (CQL) : Cassandra CRUD Operation using CQLSH Client

Prerequisite: In order to follow this tutorial and do hands-on, make sure you have installed Apache Cassandra and its up & running at least locally on one node. I have placed Apache Cassandra at
"/Users/n0r0082/opt/packages/cassandra/apache-cassandra-2.1.1".

The Apache Cassandra installation includes the cqlsh utilitya python-based command line client for executing Cassandra Query Language (CQL) commands.

Before going into details of database operations lets familiarise with Cassandra terminologies :
  • Cluster - It is collection of nodes(data centers) arranged in a ring architecture.
  • Keyspace - The keyspace is the outermost container for data in Cassandra. The main attributes to keyspace are the Replication Factor, the Replica Placement Strategy and the Column Families. Relational database schema is analogous to keyspace in Cassandra. 
  • Column Family - Column Families in Cassandra are like tables in Relational Databases. Each Column Family contains a collection of rows. The key gives the ability to access related data together,
  • Column- A column in Cassandra is a data structure which contains a column name, a value and a timestamp.
Lets start with outermost shell creation and later does CRUD Operations followed by table creation. We will execute CSQL in cqsh utility.

Start cqslh utility present in bin directory of Cassandra Installation which in turn gives cqlsh prompt.
  ~ cd /Users/n0r0082/opt/packages/cassandra/apache-cassandra-2.1.1/bin
  bin ./cqlsh 
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 2.1.1 | CQL spec 3.2.0 | Native protocol v3]
Use HELP for help.
cqlsh> 

Create a keyspace : Create a keyspace named as "OCPorc" with replication strategy attributes. On successful execution prompt does not return any status. We can see it using describe keyspaces.
cqlsh:my_status> CREATE KEYSPACE "OCProc"
             ... WITH REPLICATION = {
             ...   'class': 'SimpleStrategy', 'replication_factor': 1
             ... };

List keySpaces : Below describe command lists all keyspaces present in given cluster node.
cqlsh:my_status> describe keyspaces;

system_traces  my_status  "OCProc"  system

Selecting a keyspace : Since column families (like table in RDMS) are created in context of keyspace, we need to select keyspace we want to work with.
cqlsh:my_status> use "OCProc" ;
cqlsh:OCProc> 

Create Table(Column Family) in selected Keyspace: Create table name USERS with username as primary key and other associated properties like boolean_filter, grace_seconds, etc. In Cassandra terminology Table are termed as Column Family.  Instead of using "Create TABLE USERS ....." keyword, we can use "CREATE COLUMNFAMILY USERS ..... "
cqlsh:OCProc> CREATE TABLE "USERS" (
          ...   "username" text PRIMARY KEY,
          ...   "email" text,
          ...   "city" text,
          ...   "phone" varint,
          ...   "encrypted_password" blob
          ... ) WITH bloom_filter_fp_chance = 0.01
          ...    AND comment = 'Creating USERS Tabel to store users details'
          ...    AND dclocal_read_repair_chance = 0.1
          ...    AND default_time_to_live = 0
          ...    AND gc_grace_seconds = 864000
          ...    AND max_index_interval = 2048
          ...    AND memtable_flush_period_in_ms = 0
          ...    AND min_index_interval = 128
          ...    AND read_repair_chance = 0.0
          ...    AND compaction = {'min_threshold': '4', 'class':
          ...    'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy',
          ...    'max_threshold': '32'}
          ...    AND compression = {'sstable_compression':
          ...    'org.apache.cassandra.io.compress.LZ4Compressor'}
          ...    AND speculative_retry = '99.0PERCENTILE';
cqlsh:OCProc>  describe tables;

"USERS"

Insert data in USERS Table(
Column Family) : Below we insert 3 rows in USERS table.  On successful execution of INSERT statement we do not see any response in the shell whatsoever; it should simply provide us with a new command prompt.
cqlsh:OCProc> INSERT INTO "USERS"
          ... ("username", "email", "city", "phone", "encrypted_password")
          ... VALUES (
          ...   'zytham',
          ...   'zytham@gmail.com',
          ...   'Patna',
          ...   9999888800,
          ...   0x9792977ed729792e403da53024c6069a9158b8c4
          ... );
cqlsh:OCProc> INSERT INTO "USERS"
          ... ("username", "email", "city", "phone", "encrypted_password")
          ... VALUES(
          ...   'ranjan',
          ...   'ranjan@gmail.com',
          ...   'Bangalore',
          ...    678998800,
          ...   0x8914977ed729792e403da53024c6069a9158b8c4
          ... );
cqlsh:OCProc> 
cqlsh:OCProc> INSERT INTO "USERS"
          ... ("username", "email", "city", "phone", "encrypted_password")
          ... VALUES(
          ...   'mishra',
          ...   'zytham@gmail.com',
          ...   'Torento',
          ...    00980099766,
          ...   0x891497745729792e403da53024c6069a9158b8c4
          ... );
Note: We can insert columns values partially. i.e: Some fields can be empty, like below command insert one row but phone field is empty.
cqlsh:OCProc> INSERT INTO "USERS"
          ... ("username", "email", "city", "encrypted_password")
          ... VALUES (
          ...   'Rahul',
          ...   'rahul@gmail.com',
          ...   'Mumbai',
          ...   0x9792977ed729792e403da53024c6069a9158b8c4
          ... );

Select rows from USERS table(Column Family): SELECT command is same as used in RDBMS SQL. it returns all 4 records, notice phone is null in row with username "Rahul"
cqlsh:OCProc> SELECT * FROM "USERS"
          ... ;

 username | city      | email            | encrypted_password                         | phone
----------+-----------+------------------+--------------------------------------------+------------
   zytham |     Patna | zytham@gmail.com | 0x9792977ed729792e403da53024c6069a9158b8c4 | 9999888800
   ranjan | Bangalore | ranjan@gmail.com | 0x8914977ed729792e403da53024c6069a9158b8c4 |  678998800
    Rahul |    Mumbai |  rahul@gmail.com | 0x9792977ed729792e403da53024c6069a9158b8c4 |       null
   mishra |   Torento | zytham@gmail.com | 0x891497745729792e403da53024c6069a9158b8c4 |  980099766

(4 rows)

Other variations of SELECT Query:
  • List specific columns in result-set
  • List all rows whose primary key provided 
  • Pagination query using LIMIT 

Below query shows all above use case. When we execute IN query with non-primary key it throw error as "not supported".
cqlsh:OCProc> SELECT "username", "email" FROM "USERS" WHERE "city" = 'Patna' ;

 username | email
----------+------------------
   zytham | zytham@gmail.com

(1 rows)
cqlsh:OCProc> SELECT * FROM "USERS" WHERE "username" IN ('zytham', 'mishra');

 username | city    | email            | encrypted_password                         | phone
----------+---------+------------------+--------------------------------------------+------------
   zytham |   Patna | zytham@gmail.com | 0x9792977ed729792e403da53024c6069a9158b8c4 | 9999888800
   mishra | Torento | zytham@gmail.com | 0x891497745729792e403da53024c6069a9158b8c4 |  980099766

(2 rows)
cqlsh:OCProc> SELECT * FROM "USERS" WHERE "city" IN ('Patna', 'Torento');
code=2200 [Invalid query] message="IN predicates on non-primary-key columns (city) is not yet supported"
cqlsh:OCProc> SELECT * FROM "USERS" LIMIT 2;

 username | city      | email            | encrypted_password                         | phone
----------+-----------+------------------+--------------------------------------------+------------
   zytham |     Patna | zytham@gmail.com | 0x9792977ed729792e403da53024c6069a9158b8c4 | 9999888800
   ranjan | Bangalore | ranjan@gmail.com | 0x8914977ed729792e403da53024c6069a9158b8c4 |  678998800

(2 rows)

Delete columns data : Execute Delete Query and we can notice difference in terms of email value in first row.
cqlsh:OCProc> SELECT * FROM "USERS";

 username | city      | email            | encrypted_password                         | phone
----------+-----------+------------------+--------------------------------------------+------------
   zytham |     Patna | zytham@gmail.com | 0x9792977ed729792e403da53024c6069a9158b8c4 | 9999888800
   ranjan | Bangalore | ranjan@gmail.com | 0x8914977ed729792e403da53024c6069a9158b8c4 |  678998800
    Rahul |    Mumbai |  rahul@gmail.com | 0x9792977ed729792e403da53024c6069a9158b8c4 |       null
   mishra |   Torento | zytham@gmail.com | 0x891497745729792e403da53024c6069a9158b8c4 |  980099766
cqlsh:OCProc> DELETE "email" FROM "USERS" WHERE "username"= 'zytham';
cqlsh:OCProc> SELECT * FROM "USERS";

 username | city      | email            | encrypted_password                         | phone
----------+-----------+------------------+--------------------------------------------+------------
   zytham |     Patna |             null | 0x9792977ed729792e403da53024c6069a9158b8c4 | 9999888800
   ranjan | Bangalore | ranjan@gmail.com | 0x8914977ed729792e403da53024c6069a9158b8c4 |  678998800
    Rahul |    Mumbai |  rahul@gmail.com | 0x9792977ed729792e403da53024c6069a9158b8c4 |       null
   mishra |   Torento | zytham@gmail.com | 0x891497745729792e403da53024c6069a9158b8c4 |  980099766

(4 rows)

Note
: In Delete command we cannot use non-primary key. Below query executions fails because where clause using "City", non-primary key
cqlsh:OCProc> DELETE "email" FROM "USERS" WHERE "city"= 'Patna';
code=2200 [Invalid query] message="Non PRIMARY KEY city found in where clause"

Update table row:
cqlsh:OCProc> UPDATE "USERS" SET "city"='Delhi' WHERE "username" = 'zytham' ;
cqlsh:OCProc> SELECT * FROM "USERS";

 username | city      | email            | encrypted_password                         | phone
----------+-----------+------------------+--------------------------------------------+------------
   zytham |     Delhi |             null | 0x9792977ed729792e403da53024c6069a9158b8c4 | 9999888800
   ranjan | Bangalore | ranjan@gmail.com | 0x8914977ed729792e403da53024c6069a9158b8c4 |  678998800
    Rahul |    Mumbai |  rahul@gmail.com | 0x9792977ed729792e403da53024c6069a9158b8c4 |       null
   mishra |   Torento | zytham@gmail.com | 0x891497745729792e403da53024c6069a9158b8c4 |  980099766

(4 rows)

Note
: Update command also expect primary key in WHERE clause ,below command execution failed because of non-primary key column "city"
cqlsh:OCProc> UPDATE "USERS" SET "city"='Delhi' WHERE "city" = 'Patna' ;
code=2200 [Invalid query] message="Non PRIMARY KEY city found in where clause"


Note
:  Using Secondary index we can avoid primary key requirement with WHERE clause.
Create Index on USERS : Below command create an index based on column name city
cqlsh:OCProc> CREATE INDEX emp_city_idx ON "USERS" (city);

It is recommended by Datastax to avoid Secondary Index. Secondary indexes are tricky to use and can impact performance greatly. The index table is stored on each node in a cluster, so a query involving a secondary index can rapidly become a performance nightmare if multiple nodes are accessed.
==== ***** =====



Apr 24, 2018

Apache Cassandra CRUD operation Using Java client : Step by step guide to setup Java client for CRUD operation with Cassandra

In previous post we used CQLSH Client for performing CRUD operation and created Keyspace, Table and inserted records in it. In this post we will use Java client to achieve the same.
In order to follow below post Apache Cassandra should be up and running. Here I have used a single node cluster with default settings of host and port to connect Cassandra database.
To simulate CRUD operation with Cassandra using Java client, we will create a Java project and under that create various classes to perform CRUD operations in Cassandra.

1. Create Java Project and convert into maven project or Create a Maven project
2. Add dependency for Cassandra in pom.xml
<dependencies>
    <dependency>
        <groupId>com.datastax.cassandra</groupId>
        <artifactId>cassandra-driver-core</artifactId>
        <version>3.1.0</version>
    </dependency>
</dependencies>

3. Connection(Cluster and Session) class: Create a class "CASConnection" for storing connection objects (Cluster and Session). In Cassandra, session object is created with cluster object.

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Session;

/**
 * 
 * @author nikhil(www.devinline.com)
 * 
 */
public class CASConnection {
 /* Cassandra Cluster. */
 private Cluster cluster;
 /* Cassandra Session. */
 private Session session;

 public CASConnection() {

 }

 public CASConnection(String node, Integer port) {
  connectionUtils(node, port);
 }

 public Cluster getCluster() {
  return cluster;
 }

 public void setCluster(Cluster cluster) {
  this.cluster = cluster;
 }

 public Session getSession() {
  return session;
 }

 public void setSession(Session session) {
  this.session = session;
 }

 public void connectionUtils(final String node, final int port) {
  this.cluster = Cluster.builder().addContactPoint(node).withPort(port).build();
  Metadata metadata = cluster.getMetadata();
  System.out.printf("Connected to cluster: %s\n", metadata.getClusterName());
  for (Host host : metadata.getAllHosts()) {
   System.out.printf("Datacenter: %s; Host: %s; Rack: %s\n", host.getDatacenter(), host.getAddress(),
     host.getRack());
  }
  session = cluster.connect();
 }

 public Session getSession(String keySpace) {
  return cluster.connect(keySpace);
 }

 public void close() {
  session.close();
  cluster.close();
 }
}
4. Create a connectionFactory class "CASConnectionFactory" which gives connection object (Cluster and Session) for CRUD operation.

/**
 * 
 * @author nikhil(www.devinline.com)
 * 
 */
public class CASConnectionFactory {
 private static CASConnection INSTANCE;
 private final static String node = "localhost";
 private final static Integer port = 9042;

 /**
  * Get instance of GetBalanceCashOutUtil
  * 
  * @return
  */
 public static CASConnection getInstance() {
  if (INSTANCE == null) {
   synchronized (CASConnectionFactory.class) {
    if (INSTANCE == null) {
     INSTANCE = new CASConnection(node,port);
    }
   }
  }
  return INSTANCE;
 }
}
5. Create Database operation class: Here we write various CRUD operation methods.
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;

/**
 * 
 * @author nikhil(www.devinline.com)
 * 
 */
public class CassandraDBOperation {
 public Boolean createKeyspace(String keyspaceName, String replicationStrategy, int replicationFactor) {
  StringBuilder sb = new StringBuilder("CREATE KEYSPACE IF NOT EXISTS ").append(keyspaceName)
    .append(" WITH replication = {").append("'class':'").append(replicationStrategy)
    .append("','replication_factor':").append(replicationFactor).append("};");
  String query = sb.toString();
  CASConnectionFactory.getInstance().getSession().execute(query);
  CASConnectionFactory.getInstance().getSession().close();
  return Boolean.TRUE;
 }

 public Boolean createTable(String query, String keyspace) {
  Session session = CASConnectionFactory.getInstance().getSession(keyspace);
  session.execute(query);
  session.close();
  return Boolean.TRUE;
 }

 public Boolean createNewOrder(String keyspace, String orderNumber, String order_date, String item_id,
   Double item_price, String delivery_date) {
  Session session = CASConnectionFactory.getInstance().getSession(keyspace);
  PreparedStatement prepared = session.prepare(CQLQueryConstants.CREATE_NEW_ORDER);
  BoundStatement boundStmt = prepared.bind(orderNumber, order_date, item_id, item_price, delivery_date);
  session.execute(boundStmt);
  session.close();
  return Boolean.TRUE;
 }

 public Boolean deleteOrder(String keyspace, String orderNumber) {
  Session session = CASConnectionFactory.getInstance().getSession(keyspace);
  PreparedStatement prepared = session.prepare(CQLQueryConstants.DELETE_ORDER);
  BoundStatement boundStmt = prepared.bind(orderNumber);
  session.execute(boundStmt);
  CASConnectionFactory.getInstance().close();
  return Boolean.TRUE;
 }

 public ResultSet getOrderDetailByOrdrNumber(String keyspace, String orderNumber) {
  Session session = CASConnectionFactory.getInstance().getSession(keyspace);
  PreparedStatement prepared = session.prepare(CQLQueryConstants.SELECT_ORDER);
  BoundStatement boundStmt = prepared.bind(orderNumber);
  ResultSet result = session.execute(boundStmt);
  CASConnectionFactory.getInstance().close();
  return result;
 }

 public ResultSet getAllOrders(String keyspace) {
  Session session = CASConnectionFactory.getInstance().getSession(keyspace);
  ResultSet resultSet = session.execute(CQLQueryConstants.SELECT_ORDER_ALL);
  CASConnectionFactory.getInstance().close();
  return resultSet;
 }

}
6. SQL Query and parametrised query constant: Create a class with following constants which are used in above class file.
/**
 * 
 * @author nikhil(www.devinline.com)
 * 
 */
public class CQLQueryConstants {
 public static final String CREATE_ORDER_TABLE = "CREATE TABLE \"ORDERS\" \n" + 
   "(\n" + 
   "   order_number varchar,\n" + 
   "   order_date varchar,\n" + 
   "   item_id varchar,\n" + 
   "   item_price double,\n" + 
   "   delivery_date varchar,\n" + 
   "   PRIMARY KEY (order_number)\n" + 
   ");";
 
 public static final String SCHEDULE_DELIVERY_TABLE = "CREATE TABLE ORDER_DELIVERY \n" + 
   "(\n" + 
   "   shipment_number varchar,\n" +
   "   order_number varchar,\n" + 
   "   expected_delivery_date int,\n" + 
   "   customer_id varchar,\n" + 
   "   delivery_mode varchar,\n" + 
   "   PRIMARY KEY (shipment_number,order_number)\n" + 
   ");";
 
 public static final String CREATE_NEW_ORDER = "INSERT into \"ORDERS\" ("
   + "order_number, "
   + "order_date,"
   + "item_id,"
   + "item_price,"
   + "delivery_date) "
   + "VALUES (?,?,?,?,?)";
 
 public static final String UPDATE_ORDER_DELIVERY_DATE = "UPDATE \"ORDERS\"  SET "
   + "delivery_date = ?"
   + "WHERE order_number = ?";
 
 public static final String DELETE_ORDER = "DELETE FROM \"ORDERS\" WHERE order_number=? IF EXISTS;";
 
 public static final String SELECT_ORDER = "SELECT * FROM \"ORDERS\" WHERE order_number= ?;";
 
 public static final String SELECT_ORDER_ALL = "SELECT * FROM \"ORDERS\";";
}

7. Client/Driver Program unit : Finally we create Java client program which create Keyspace, Create table, Insert rows, etc.
import java.net.UnknownHostException;
import java.util.Random;
import java.util.Scanner;

import com.datastax.driver.core.ResultSet;
/**
 * 
 * @author nikhil(www.devinline.com)
 * 
 */
public class CASClient {
 private static String KEY_SPACE_NAME = "\"SPOrders\"";
 private static String REPLICAION_STRATEGY = "SimpleStrategy";
 private static Integer REPLICATION_FACTOR = 1;

 public static void main(String[] args) throws UnknownHostException {
  System.out.print("******Enter Operation**********");
  System.out.print("\n 1. CREATE_KEYSPACE, " + "\n 2. CREATE_ORDER_TABLE, " + "\n 3. CREATE_NEW_ORDER, "
    + "\n 4. DELETE_ORDER, " + "\n 5. SELECT_ORDER_BY_ORDER_NUMBER, " + "\n 6. SELECT_ALL_ORDER");
  System.out.print("\n*******************************");
  Scanner sc = new Scanner(System.in);
  System.out.println("\nEnter your choice: ");
  int choice = sc.nextInt();
  switch (choice) {
  case 1:
   doDBOperation("CREATE_KEYSPACE");
   break;
  case 2:
   doDBOperation("CREATE_ORDER_TABLE");
   break;
  case 3:
   doDBOperation("CREATE_NEW_ORDER");
   break;
  case 4:
   doDBOperation("DELETE_ORDER");
   break;

  case 5:
   doDBOperation("SELECT_ORDER_BY_ORDER_NUMBER");
   break;

  case 6:
   doDBOperation("SELECT_ALL_ORDER");
   break;

  default:
   break;
  }
  sc.close();

 }

 public static void doDBOperation(String value) {
  CassandraDBOperation dbOperation = new CassandraDBOperation();
  DBOperationsEnum operation = DBOperationsEnum.valueOf(value);
  switch (operation) {
  case CREATE_KEYSPACE:
   System.out.println("CREATE_KEYSPACE");
   /* Create Keyspace */
   if (dbOperation.createKeyspace(KEY_SPACE_NAME, REPLICAION_STRATEGY, REPLICATION_FACTOR)) {
    System.out.println("Keyspace " + KEY_SPACE_NAME + " created successfully !");
   }
   break;
  case CREATE_ORDER_TABLE:
   System.out.println("CREATE_ORDER_TABLE");
   /*
    * Create ORDERS table : KEY_SPACE_NAME is passed in input
    */
   if (dbOperation.createTable(CQLQueryConstants.CREATE_ORDER_TABLE, KEY_SPACE_NAME)) {
    System.out.println("TABLE CREATE_ORDER created successfully !");
   }
   break;
  case CREATE_NEW_ORDER:
   System.out.println("CREATE_NEW_ORDER");
   String orderNumber = getOrderNum();
   if (dbOperation.createNewOrder(KEY_SPACE_NAME, getOrderNum(), "2018-03-18", getItemNum(), getPrice(),
     "2018-03-23")) {
    System.out.println("New ORDER created successfully with order number " + orderNumber);
   }
   break;

  case DELETE_ORDER:
   Scanner sc = new Scanner(System.in);
   System.out.println("\nEnter Order Number: ");
   String orderNumberDel = sc.next();
   if (dbOperation.deleteOrder(KEY_SPACE_NAME, orderNumberDel)) {
    System.out.println("ORDER " + orderNumberDel + "deleted successfully ");
   }
   sc.close();
   break;

  case SELECT_ORDER_BY_ORDER_NUMBER:
   System.out.println("\nEnter Order Number: ");
   Scanner sc1 = new Scanner(System.in);
   String orderNumSel = sc1.next();
   ResultSet resultSet = dbOperation.getOrderDetailByOrdrNumber(KEY_SPACE_NAME, orderNumSel);
   if (null != resultSet) {
    System.out.println(resultSet.all());
   }
   sc1.close();
   break;

  case SELECT_ALL_ORDER:
   ResultSet resultSet1 = dbOperation.getAllOrders(KEY_SPACE_NAME);
   if (null != resultSet1) {
    System.out.println(resultSet1.all());
   }
   break;

  default:
   System.out.println("No operations selectd !!");
   break;
  }
 }

 private static String getOrderNum() {
  Random rand = new Random();
  int value = rand.nextInt(50);
  return "ORDER" + value;
 }

 private static Double getPrice() {
  Random rand = new Random();
  int value = rand.nextInt(50);
  return value * 0.9;
 }

 private static String getItemNum() {
  Random rand = new Random();
  int value = rand.nextInt(50);
  return "ITEM" + value;
 }
}

enum DBOperationsEnum {
 CREATE_KEYSPACE, CREATE_ORDER_TABLE, CREATE_NEW_ORDER, DELETE_ORDER, SELECT_ORDER_BY_ORDER_NUMBER, SELECT_ALL_ORDER

}

Sample Output
:
Hide Output
******Enter Operation**********
 1. CREATE_KEYSPACE, 
 2. CREATE_ORDER_TABLE, 
 3. CREATE_NEW_ORDER, 
 4. DELETE_ORDER, 
 5. SELECT_ORDER_BY_ORDER_NUMBER, 
 6. SELECT_ALL_ORDER
*******************************
Enter your choice: 
1
CREATE_KEYSPACE
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Connected to cluster: Test Cluster
Datacenter: datacenter1; Host: localhost/127.0.0.1; Rack: rack1
Keyspace "SPOrders" created successfully !


******Enter Operation**********
 1. CREATE_KEYSPACE, 
 2. CREATE_ORDER_TABLE, 
 3. CREATE_NEW_ORDER, 
 4. DELETE_ORDER, 
 5. SELECT_ORDER_BY_ORDER_NUMBER, 
 6. SELECT_ALL_ORDER
*******************************
Enter your choice: 
3
CREATE_NEW_ORDER
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Connected to cluster: Test Cluster
Datacenter: datacenter1; Host: localhost/127.0.0.1; Rack: rack1

New ORDER created successfully with order number ORDER44



cqlsh:SPOrders> select * from "ORDERS";
 order_number | delivery_date | item_id | item_price | order_date
--------------+---------------+---------+------------+------------
      ORDER44 |    2018-03-23 |  ITEM34 |       12.6 | 2018-03-18
      ORDER30 |    2018-03-23 |  ITEM20 |       14.4 | 2018-03-18

******Enter Operation**********
 1. CREATE_KEYSPACE, 
 2. CREATE_ORDER_TABLE, 
 3. CREATE_NEW_ORDER, 
 4. DELETE_ORDER, 
 5. SELECT_ORDER_BY_ORDER_NUMBER, 
 6. SELECT_ALL_ORDER
*******************************
Enter your choice: 
5

Enter Order Number: 
ORDER30
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Connected to cluster: Test Cluster
Datacenter: datacenter1; Host: localhost/127.0.0.1; Rack: rack1
[Row[ORDER30, 2018-03-23, ITEM20, 14.4, 2018-03-18]]

******Enter Operation**********
 1. CREATE_KEYSPACE, 
 2. CREATE_ORDER_TABLE, 
 3. CREATE_NEW_ORDER, 
 4. DELETE_ORDER, 
 5. SELECT_ORDER_BY_ORDER_NUMBER, 
 6. SELECT_ALL_ORDER
*******************************
Enter your choice: 
4

Enter Order Number: 
ORDER30
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Connected to cluster: Test Cluster
Datacenter: datacenter1; Host: localhost/127.0.0.1; Rack: rack1
ORDER ORDER30deleted successfully 


cqlsh:SPOrders> select * from "ORDERS";
 order_number | delivery_date | item_id | item_price | order_date
--------------+---------------+---------+------------+------------
      ORDER44 |    2018-03-23 |  ITEM34 |       12.6 | 2018-03-18