Convert Object to JSON and JSON to Object with FasterXML/jackson-databind

Refer the FasterXml/Jackson-bind API from the below GitHub repo. This is very helpful for handling the various data format especially JSON

https://github.com/FasterXML/jackson-databind

The sample code to convert Object to JSON and JSON to Object is given below,

Maven Dependencies,


 <dependency>
            <groupId>com.fasterxml.jackson.jr</groupId>
            <artifactId>jackson-jr-objects</artifactId>
            <version>2.5.0</version>
 </dependency>
 <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.0</version>
    </dependency>

Code:


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class JSONUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(JSONUtils.class);

    public static void main(String[] args) throws IOException {

        LOGGER.info("Converting Object to String");
        Customer customer = new Customer();
        customer.setCustomerId("cust1234");
        customer.setFirstName("Bala");
        customer.setLastName("samy");
        String objectString = convertObjectAsString(customer);
        LOGGER.info("Converting String:{}", objectString);

        LOGGER.info("Converting String to Customer Object");
        Customer customer1 = convertJsonStringAsObject(objectString);
        LOGGER.info("Converted Object:{}", customer1);

    }

    public static String convertObjectAsString(Object obj) throws JsonProcessingException {
        String content = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
            content = mapper.writeValueAsString(obj);
        } catch (Exception e) {
            LOGGER.error("Exception happened while doing the conversion", e);
            throw e;
        }
        return content;
    }

    public static Customer convertJsonStringAsObject(String content) throws IOException {

        Customer customer = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            customer = mapper.readValue(content, Customer.class);
        } catch (Exception e) {
            LOGGER.error("Exception happened while doing the conversion", e);
            throw e;
        }
        return customer;
    }


    public static class Customer {

        private String firstName;
        private String lastName;
        private String customerId;

        public String getFirstName() {
            return firstName;
        }

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

        public String getLastName() {
            return lastName;
        }

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

        public String getCustomerId() {
            return customerId;
        }

        public void setCustomerId(String customerId) {
            this.customerId = customerId;
        }

        @Override

        public boolean equals(Object o) {
            if (this == o) return true;

            if (o == null || getClass() != o.getClass()) return false;

            Customer customer = (Customer) o;

            return new EqualsBuilder()
                    .append(firstName, customer.firstName)
                    .append(lastName, customer.lastName)
                    .append(customerId, customer.customerId)
                    .isEquals();
        }

        @Override
        public int hashCode() {
            return new HashCodeBuilder(17, 37)
                    .append(firstName)
                    .append(lastName)
                    .append(customerId)
                    .toHashCode();
        }

        @Override
        public String toString() {
            return new ToStringBuilder(this)
                    .append("firstName", firstName)
                    .append("lastName", lastName)
                    .append("customerId", customerId)
                    .toString();
        }
    }

}

Output:


Converting Object to String
Converting String:{"firstName":"Bala","lastName":"samy","customerId":"cust1234"}
Converting String to Customer Object
Converted Object:JSONUtils$Customer@130f889[firstName=Bala,lastName=samy,customerId=cust1234]

Advertisements

Convert Object as Json using FasterXML/jackson-jr

Its an alternative to jackson-bind API for processing JSON. It provides an easy way to convert the java object to json and vice versa.

This API can be used, when the size of the third party jar and startup time matters in your application. This API has very low initialization overhead compared to jackson-bind

The Github repository is https://github.com/FasterXML/jackson-jr

pom.xml


<dependency>
  <groupId>com.fasterxml.jackson.jr</groupId>
  <artifactId>jackson-jr-objects</artifactId>
  <version>2.8.5</version>
</dependency>

Sample code to convert the Object to json is given below,
JSONUtils:


import com.fasterxml.jackson.jr.ob.JSON;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class JSONUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(JSONUtils.class);

    public static void main(String[] args) throws IOException {

        LOGGER.info("Converting Object to String");
        Customer customer = new Customer();
        customer.setCustomerId("cust1234");
        customer.setFirstName("Bala");
        customer.setLastName("samy");
        String objectString = convertObjectAsString(customer);
        LOGGER.info("Converting String:{}", objectString);

        LOGGER.info("Converting String to Customer Object");
        Customer customer1 = convertJsonStringAsObject(objectString);
        LOGGER.info("Converted Object:{}", customer1);

    }

    public static String convertObjectAsString(Object obj) throws IOException {
        return JSON.std.asString(obj);
    }

    public static Customer convertJsonStringAsObject(String content) throws IOException {
        return JSON.std.beanFrom(Customer.class, content);
    }


    public static class Customer {

        private String firstName;
        private String lastName;
        private String customerId;

        public String getFirstName() {
            return firstName;
        }

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

        public String getLastName() {
            return lastName;
        }

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

        public String getCustomerId() {
            return customerId;
        }

        public void setCustomerId(String customerId) {
            this.customerId = customerId;
        }

        @Override

        public boolean equals(Object o) {
            if (this == o) return true;

            if (o == null || getClass() != o.getClass()) return false;

            Customer customer = (Customer) o;

            return new EqualsBuilder()
                    .append(firstName, customer.firstName)
                    .append(lastName, customer.lastName)
                    .append(customerId, customer.customerId)
                    .isEquals();
        }

        @Override
        public int hashCode() {
            return new HashCodeBuilder(17, 37)
                    .append(firstName)
                    .append(lastName)
                    .append(customerId)
                    .toHashCode();
        }

        @Override
        public String toString() {
            return new ToStringBuilder(this)
                    .append("firstName", firstName)
                    .append("lastName", lastName)
                    .append("customerId", customerId)
                    .toString();
        }
    }

}

Output:


2016-12-29T11:44:54.319-0500 [main] INFO  o.c.o.m.JSONUtils - Converting Object to String
2016-12-29T11:44:54.398-0500 [main] INFO  o.c.o.m.JSONUtils - Converting String:{"customerId":"cust1234","firstName":"Bala","lastName":"samy"}
2016-12-29T11:44:54.399-0500 [main] INFO  o.c.o.m.JSONUtils - Converting String to Customer Object
2016-12-29T11:44:54.405-0500 [main] INFO  o.c.o.m.JSONUtils - Converted Object:org.cas.osd.mp.JSONUtils$Customer@31ef45e3[firstName=Bala,lastName=samy,customerId=cust1234]

Rest Assured API for Rest Service Integration testing

We use Rest Assured Api for testing the Rest services. Its very easy to implement. It works based on Given when then approach


public class RestAssuredTest{
    
    @Before
    public void setUp() {
        RestAssured.baseURI = "http://localhost"; //Domain name
        RestAssured.port = 8080; //port number
        RestAssured.basePath = "/api/"; //Service Base URL
    }

    @Test
    public void testRestService() {
        Response res = given().param("QUERY_PARAM", "QUERY_VALUE").get("REST SERVICE PATH");
        assertEquals(200, res.getStatusCode());
        assertNotNull(res.getBody());
res.getBody().asString());     
    }
}

Please refer my another posts for more information Rest Assured – Example and Rest Assured – Test Secure web services

Equals and HashCode

Consider the below example,
It’s a simple java class with one String field “key”. Inside the Main() method, We have created a HashMap and use this class object as a key and store a string as value.

Then we try to retrieve the value from that HashMap with that object. As this class does not override the hashCode() method, so invoking the hashCode() method on this class object will produce a different hashCode. So we would not able to retrieve the value with that object.


import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import java.util.HashMap;
import java.util.Map;

public class Ckey {

    private String key;

    public Ckey(String key) {
        this.key = key;
    }

    public String getKey() {
        return key;
    }

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


    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("Ckey", key)
                .toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        Ckey keyMap = (Ckey) o;

        return new EqualsBuilder()
                .append(key, keyMap.key)
                .isEquals();
    }

      /*  @Override
        public int hashCode() {
            return new HashCodeBuilder(17, 37)
                    .append(key)
                    .toHashCode();
        }*/

    public static void main(String[] args) {
        Map hashMap = new HashMap();
        Ckey k1 = new Ckey("Key1");
        hashMap.put(k1, "key1");
        System.out.println(hashMap);
        //Try to retrive the value with the same Key. You will end with null.since the hashCode are not implemented.
        // So invoking the hashCode will produce a default code which is different for every call. So you will not get the value
        System.out.println(hashMap.get(new Ckey("Key1")));
    }
}


As per the contract
1) If two objects are equal, then they must have the same hash code.
2) If two objects have the same hash code, they may or may not be equal.

If you dont override the equals() method, then the compare operation will be failed. Hence it will return a Null value. So we should override both these methods to avoid these kind of issues

Why we use Kafka

I have done some analysis to identify the messaging system for logging user specific actions in one of my systems. The user can do various activities on the site and all those actions should be logged that can be used for various analysis.

We also want the guaranteed message delivery and the message should be available and it should be distributed across the cluster so failure of any node should not cause any issue for that message. We can’t predict the number of messages created in a second. So it will be increased gradually based on number of users.

By considering all these points, we prefer to use Apache Kafka instead of RabbitMQ or other messaging system

Reverse a String using recursion


public class StringUtils {

    public static void main(String[] args) {
        String input = "reverse";
        System.out.println("Input String is " + input);
        String reversed = reverse(input);
        System.out.println("Reversed String is " + reversed);
    }

    private static String reverse(String input) {

        if (input.length() == 1) {
            return input;
        } else {
            return reverse(input.substring(1, input.length())) + input.charAt(0);
        }
    }
}

Find the Time Complexity

Find out the time complexity for the below algorithm

test = 0
for i in range(n):
test = test + 1

for j in range(n):
test = test – 1

Analysis:

test = 0      ==> 1
for i in range(n): ==> n
test = test + 1       ===> n

for j in range(n):  ==> n
test = test – 1  ==> n

4n+1 ==> ignore constant = > O(n)