Sunday, 18 February 2018

Hamcrest tutorial

Basics

      Introduction to Hamcrest
      Hello World Application

Test null values

      Match null values
      nullValue: Creates a matcher that matches if examined object is null
      notNullValue : Creates a matcher that matches if examined object is not null

Matchers to work with strings

      Hamcrest: Matchers to work with strings
      containsString: match sub string
      startsWith: Check whether string starts with given string
      endsWith: Check whether string ends with given string
      equalToIgnoringCase: check equality of strings by ignoring case
      equalToIgnoringWhiteSpace: check equality of strings by ignoring case and white spaces
      isEmptyString: Match if the string is empty
      isEmptyOrNullString: Match if the string is empty or null
      stringContainsInOrder: Matches a string against all the substrings

Work with Arrays

      Matchers to work with arrays
       array: Match every element of array with specific matcher
      hasItemInArray: Check the existence of item in the array
      arrayContaining: Match each item in the array
      arrayContainingInAnyOrder: Check array euality, order doesn't matter
      arrayWithSize: Check array length
      emptyArray: match empty array

Compare Objects

      Matchers to compare objects
      greaterThan: check whether given object is greater than this value
      greaterThanOrEqualTo: check whether given object is greater than or equal to this value
      
      lessThanOrEqualTo: Check whether object is <= other object
      comparesEqualTo: Check objects equality

Marchers to check instances

      Marchers to check instances
      instanceOf: Check whether object is instance of class or not
      sameInstance: objects equality checker
      theInstance: objects equality checker
      equalTo: objects equality using equals method

Matchers to work with collections

      Matchers to work with collections
      everyItem: All elements must match to given matcher
      hasItem: Check for the existence of at least one item
      hasItems: Check for the existence of multiple items
      hasSize: Checks the size of collection
      empty: Check emptiness of collection
      emptyCollectionOf: Check the emptiness of collection
      emptyIterable: Check the emptiness of iterables
      emptyIterableOf: Check the emptiness of iterable
      contains: Check for the existence of elements in the collection
      containsInAnyOrder: Search the elements of collection (order doesn’t matter)
      iterableWithSize: Check the size of iterable
      hasEntry: Check for the entry in map
      hasKey: Check for the existence of key
      hasValue: Check the existence of value in map
      isIn: Check the object existence in the collection
      isOneOf: Matches of altest one element matches
      IsIterableContainingInOrder: test the ordering of collection or list elements

Combining matchers

      Combining matchers
      allOf: Match against all the matchers
      both: Match against two matchers
      either: match against either of the matcher
      anyOf: match against any one of the matcher

Working with classes and objects

      Working with classes and objects
      hasProperty: Check whether given object has specific property or not
      isA: Check whether object is of given type
      typeCompatibleWith: Check the compatibility of one type with other
      samePropertyValuesAs: Check two beans properties
      any: Match an object that is instance of class

Working With Numbers

      closeTo: Working with numbers

Previous                                                 Next                                                 Home

Friday, 16 February 2018

Kotlin: complementary variance annotation: in

It is continuation to my previous post, I recommend you to go through my previous post before reading this.

When a type parameter T of a class C is declared ‘in’, C<Derived> can safely be a supertype of C<Base>. What it means is, for a reference of type T, we can able to assign the reference to the subtype of T.

var demoObjNumber: DemoObj<Number> = DemoObjImpl()

/* We can assing demoObjNumber to DemoObj<Double> reference */
var demoObjDouble: DemoObj<Double> = demoObjNumber

/* We can assing demoObjNumber to DemoObj<Int> reference */        
var demoObjInt: DemoObj<Int> = demoObjNumber

Find the below working application.

Test.kt
public interface DemoObj<in T> {
 fun toString(value: T): String
}

public class DemoObjImpl<in T> : DemoObj<T> {

 override fun toString(value: T): String {
  return value.toString()
 }

}

fun main(args: Array<String>) {
 var demoObjNumber: DemoObj<Number> = DemoObjImpl()
 var result = demoObjNumber.toString(10)
 println("result : $result")

 var demoObjDouble: DemoObj<Double> = demoObjNumber
 result = demoObjDouble.toString(10.01)
 println("result : $result")
 
 var demoObjInt: DemoObj<Int> = demoObjNumber
 result = demoObjInt.toString(10)
 println("result : $result")
}

Output
result : 10
result : 10.01
result : 10



Previous                                                 Next                                                 Home

Thursday, 15 February 2018

Kotlin: Generics

Just like in Java, kotlin supports type parameters.

Let me explain with an example,

class Employee<T>(var id: T, var name: String) {

}

Above snippet creates a generic Employee class, where id is generic type.

Create Employee object, where id is of type Int
var emp1: Employee<Int> = Employee(1, "Krishna")

Create Employee object, where id is of type String
var emp2: Employee<String> = Employee("I345123", "Chamu")

Find the below working application.

Test.kt
com.sample.test

class Employee<T>(var id: T, var name: String) {

}

private fun <T> printEmployee(emp: Employee<T>) {
 println("id : ${emp.id}")
 println("name : ${emp.name}")
}

fun main(args: Array<String>) {
 var emp1: Employee<Int> = Employee(1, "Krishna")
 var emp2: Employee<String> = Employee("I345123", "Chamu")

 printEmployee(emp1)
 printEmployee(emp2)

}

Output
id : 1
name : Krishna
id : I345123
name : Chamu

Can I declare multiple type parameters to a class?
Yes, you can declare multiple type parameters to a class.

Ex
class MapEntry<T, U>(var key: T, var value : U) {

}

Is Kotlin infer type arguments?
Most of the times (not always), kotlin can infer the type arguments based on the definition of the object.

For ex
var emp1 = Employee(1, "Krishna")
From the above statement, kotlin can infer that the Employee is of type Employee<Int>

var emp2 = Employee("I345123", "Chamu")
From the above statement, kotlin can infer that the Employee is of type Employee<String>

But there are some situations, where kotlin can’t infer the type arguments.

For example, kotlin provides listOf function to define list of values.

var primes = listOf(2, 3, 5, 7, 11)

From the above statement kotlin can infer that we are trying to create a list of Integers.

Let’s try to create empty list
var primes = listOf()


Test.kt
package com.sample.test

fun main(args: Array<String>) {
 var primes = listOf()
}

When you try to compile above program, you will end up in below error.

ERROR: Type inference failed: Not enough information to infer parameter T in inline fun <T> listOf(): List<T>
Please specify it explicitly.
 (4, 15)

It is because, you are not passing any arguments to listOf function, so kotlin can’t infer anything from empty list declaration.

To resolve above problem, you should define the list ‘primes’ like below.

var primes = listOf<String>()

Benefits of Generics
1. Stronger type checks at compile time
Types are checked at compile time, so most of the type related bugs detected at compile time.


Test.kt
package com.sample.test

class Employee<T>(var id: T, var name: String) {

}

fun main(args: Array<String>) {
 var emp1: Employee<String> = Employee(1, "Krishna")

}

Notify above snippet, I defined emp1 as of type Employee<String>, but I passed employee id as 1 (1 is integer, not string). When you try to compile above program, kotlin compiler throw below error.

ERROR: Type inference failed. Expected type mismatch: inferred type is Employee<Int> but Employee<String> was expected (9, 31)

2. Enable Programmers to implement Generic Data Structures.
I will explain about this in collections sections.


Is Kotlin had wildcard characters like java?
No, but kotlin has two other things declaration-site variance and type projections.

Kotlin: Generics: Declaration-site variance : out
Kotlin do not have wild card concept like Java, but it supports the same using Declaration-site variance and type projections

Why java support wild cards?
? is called the wild card in Java. It represents unknown type. There are some situations, where programmer certainly don't know, the kind of data that he is going to operate, in those situation wild cards are helpful.

First let us see, why generic types are invariant in Java.

Why generic types are invariant in Java?
Generic types in Java are invariant. That means, if T2 is a subtype of T1, List<T2> is not a sub type of List<T1>.


Ex
Integer is a subtype of Number.
But Stack<Integer> is not a sub type of Stack<Number>.

Why java makes generics as invariant?
Let me explain with an example.

                 /* Define a character list */
                 List<Character> chars = new ArrayList<Character>();

                 /* Java do not allow this */
                 List<Object> objs = chars;

                 /* Adding double to character list */
                 objs.add(1.23);

                 /* ClassCastException: Cannot cast double to Character */
                 Character s = chars.get(0);

As you notify above snippet. I defined a character list ‘chars’ and cast it to list of objects ‘objs’. I added a double to ‘objs’. Last statement cast the double to character, which is not possible. To prohibit these kind of things and ensure run time safety of the application, java generics are invariant.

But generic type invariant has its own implications. For example, you would like to calculate sum of numbers (number can be integer, byte, double, float etc.,). Method signatures looks like below.


         private static Double sumOfintegers(List<Integer> listOfIntegers) {

         }

         private static Double sumOfFloats(List<Float> listOfDoubles) {

         }

        
         private static Double sumOfDoubles(List<Double> listOfDoubles) {

         }

If there are ‘n’ different Number types, you will end up in writing ‘n’ different functions to calculate sum of the numbers. To resolve this kind of problem, wild card character is introduced.

         private static Double sumOfNumbers(List<? extends Number> listOfNumbers) {

                 Double sum = 0.0;

                 for (Number num : listOfNumbers) {
                          sum = sum + num.doubleValue();
                 }

                 return sum;

         }

The wildcard type operator ‘? extends Number’ indicates that this method accepts a collection of objects of number or some subtype of Numbers, not just E itself.  We can use ‘sumOfNumbers’ function to calculate the sum of different number types (Integer, Float, Double etc.,)

Sum of integers can be calculated like below.
List<Integer> intList = Arrays.asList(2, 3, 5, 7);
Double sumOfIntegers = sumOfNumbers(intList);

Sum of Doubles can be calculated like below.
List<Double> doubleList = Arrays.asList(2.0, 3.0, 5.0, 7.0);
Double sumOfDoubles = sumOfNumbers(doubleList);

Sum of Floats can be calculated like below
List<Float> floatList = Arrays.asList(2.0f, 3.0f, 5.0f, 7.0f);
Double sumOfFloats = sumOfNumbers(floatList);

Find the below working application.

Test.java
import java.util.Arrays;
import java.util.List;

public class Test {

 private static Double sumOfNumbers(List<? extends Number> listOfNumbers) {

  Double sum = 0.0;

  for (Number num : listOfNumbers) {
   sum = sum + num.doubleValue();
  }

  return sum;

 }

 public static void main(String args[]) throws CloneNotSupportedException {
  List<Integer> intList = Arrays.asList(2, 3, 5, 7);
  List<Double> doubleList = Arrays.asList(2.0, 3.0, 5.0, 7.0);
  List<Float> floatList = Arrays.asList(2.0f, 3.0f, 5.0f, 7.0f);

  Double sumOfIntegers = sumOfNumbers(intList);
  Double sumOfDoubles = sumOfNumbers(doubleList);
  Double sumOfFloats = sumOfNumbers(floatList);

  System.out.println("sumOfIntegers : " + sumOfIntegers);
  System.out.println("sumOfDoubles : " + sumOfDoubles);
  System.out.println("sumOfFloats : " + sumOfFloats);

 }
}


Output
sumOfIntegers : 17.0
sumOfDoubles : 17.0
sumOfFloats : 17.0

Let’s see a scenario, where Java generics is not intelligent enough to take decision.

For example, I had an interface DemoObj. It has single method getObj() that returns the object itself.


DemoObj.java
package com.sample.demo;

public interface DemoObj<T> {
 T getObj();
}

‘DemoObjImpl’ implements DemoObj interface like below.


DemoObjImpl.java
package com.sample.demo;

public class DemoObjImpl<T> implements DemoObj<T> {

 private T obj;

 public DemoObjImpl(T obj) {
  this.obj = obj;
 }

 @Override
 public T getObj() {
  return obj;
 }

}


Since instance of DemoObjImpl is just returning the generic object, it would be perfectly safe to store a reference to an instance of DemoObj<String> in a variable of type DemoObj<Object>. But Java doesn’t know this and prohibit the application.

DemoObj<String> demoStrObj = new DemoObjImpl("Hello World");
DemoObj<Object> demoObj = demoStrObj; // Compiler throw error


Test.java
package com.sample.demo;

public class Test {

 public static void main(String args[]) throws CloneNotSupportedException {
  DemoObj<String> demoStrObj = new DemoObjImpl("Hello World");
  DemoObj<Object> demoObj = demoStrObj;
 }
}

When you try to run above application, Java compier throw below error.

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
         Type mismatch: cannot convert from DemoObj<String> to DemoObj<Object>

         at com.sample.demo.Test.main(Test.java:7)
How to resolve above problem in Kotlin?
Kotlin solves this problem using ‘declaration-site variance'. when a type parameter T of a class C is annotated with ‘out’ keyword, C<Base> can safely be a supertype of C<Derived>.

public interface DemoObj<out T> {
         fun getObj(): T
}

fun getDemoObj(demoStrObj: DemoObj<String>): DemoObj<Any> {
         var demoObj: DemoObj<Any> = demoStrObj
         return demoObj;
}

Find the below working application.


Test.kt
public interface DemoObj<out T> {
 fun getObj(): T
}

public class DemoObjImpl<out T> : DemoObj<T> {

 private var obj: T

 public constructor(obj: T) {
  this.obj = obj;
 }

 override public fun getObj(): T {
  return obj;
 }

}

fun getDemoObj(demoStrObj: DemoObj<String>): DemoObj<Any> {
 var demoObj: DemoObj<Any> = demoStrObj
 return demoObj;
}

fun main(args: Array<String>) {
 var demoObjStr: DemoObj<String> = DemoObjImpl("Hello World")

 var demoObj: DemoObj<Any> = getDemoObj(demoObjStr)

 println("Value of demoObj : ${demoObj.getObj()}")

}

Output
Value of demoObj : Hello World


Previous                                                 Next                                                 Home

Kotlin: Data classes: Destructuring declarations

Kotling supports destructuring of object. By using destructuring declaration, we can define multiple variables in one line.

For ex
var (fName, lName, id) = employee
Above statement declares three variable fName, lName and id from employee object.

Find the below working application.

HelloWorld.kt

package com.sample.test

data class Employee(var firstName: String, var lastName: String, var id: String)

fun main(args: Array<String>) {
 var employee = Employee("Krishna", "Gurram", "12345")

 var (fName, lName, id) = employee

 println("fName : $fName")
 println("lName : $lName")
 println("id : $id")

}

Output

fName : Krishna
lName : Gurram
id : 12345


Previous                                                 Next                                                 Home

Wednesday, 14 February 2018

Get x.509 certificate from encoded string

Step 1: Decode the encoded string.

Decoder decoder = Base64.getDecoder();
byte[] decodedData = decoder.decode(encodedString);

Step 2: Get input stream from decoded data.
InputStream inputStream = new ByteArrayInputStream(decodedData)

Step 3: Generate certificate from decoded data.
CertificateFactory cf = CertificateFactory.getInstance("X.509");

java.security.cert.Certificate certificate = cf.generateCertificate(inputStream);

if (certificate instanceof X509Certificate) {
         return (X509Certificate) certificate;
}

Find the below working application.

CertificateUtil.java
package com.sample.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Base64.Decoder;;

public class CertificateUtil {
 /**
  * 
  * @param encodedString
  *            base64 encoded string
  * 
  * @return X509Certificate from the encodedString, null on failure cases
  */
 public static X509Certificate getX509Certificate(String encodedString) {
  if (encodedString == null) {
   return null;
  }

  Decoder decoder = Base64.getDecoder();
  byte[] decodedData = decoder.decode(encodedString);

  try (InputStream inputStream = new ByteArrayInputStream(decodedData)) {
   CertificateFactory cf = CertificateFactory.getInstance("X.509");

   java.security.cert.Certificate certificate = cf.generateCertificate(inputStream);

   if (certificate instanceof X509Certificate) {
    return (X509Certificate) certificate;
   }

  } catch (Exception e) {
   e.printStackTrace();
  }

  return null;

 }
}

Test.java
package com.sample.test;

import java.security.cert.X509Certificate;

import com.sample.util.CertificateUtil;

public class Test {
 
 public static void main(String args[]) throws Exception {
  String encodedString = "MIIDbTCCAlWgAwIBAgIEHUj86jANBgkqhkiG9w0BAQsFADBnMQswCQYDVQQGEwJrcjEQMA4GA1UECBMHa3Jpc2huYTEQMA4GA1UEBxMHa3Jpc2huYTEQMA4GA1UEChMHa3Jpc2huYTEQMA4GA1UECxMHa3Jpc2huYTEQMA4GA1UEAxMHa3Jpc2huYTAeFw0xODAyMDkwNDEwMjJaFw0xOTAyMDkwNDEwMjJaMGcxCzAJBgNVBAYTAmtyMRAwDgYDVQQIEwdrcmlzaG5hMRAwDgYDVQQHEwdrcmlzaG5hMRAwDgYDVQQKEwdrcmlzaG5hMRAwDgYDVQQLEwdrcmlzaG5hMRAwDgYDVQQDEwdrcmlzaG5hMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqoDP8q/LerAIb6WBx0nx3i670p7uwRbTQ/NeK54BEsV3pkjT8GlPsTP2ai6Xs038oYkgSxldlfhgpdXsWqh95+YdqDPJV2iF4LAET2Z9qrUChp6MkmHQr8HRi1+2UOS6WI0IX4fZasXapL1cQCsGTYem1b4kJmYPXczhtOMKwJXbdA0YvzE+4m2pX1wjMufi2eX8a4quojQjJrURnq74/XJepNnA0yWRuczdLG3XpPFftQaCiAj+Oa/3bKUYXRg1ODdl5VTaxUkqL/2odw4vvFs2fhSnouALsc+wyAKaBH38ZICUCoSiX6mU9hCvBpbHFk6ToQcPTo3CkWGSzBiPrQIDAQABoyEwHzAdBgNVHQ4EFgQUT1S1ED2sUYPCi8Thmz/tEqiSLIIwDQYJKoZIhvcNAQELBQADggEBAKabXk+LifQMnA8eJvDkn8xZ3FKr/9osmIcJjkO4i0vtnGOSxQ4+IyATxJ/4nrXAZwBI4+q4l13GNFw+S6ebKoYfNWEvZHUbjLALr98+nhHsURY73TIV2nw75bWOvh3QRpDDPiP/3Fzs9XjENxeUXcUV+mLGETKGa6szfcZ0Huaeva5nxDt7U+4/3xyMO9CWuYglhC8act1pd3RfZdZJaDN3fUy/+tocKXMmo0s7oLiAlyfLNhng2aqHwHu/sAoHjYyLhqz7401MmqHYX8hkOJ6FBXjJZz62zfrFUVoM10zNkByIbdL4WzNf/d8z0X57IgHg08IPpYJOfenSIqF3Rmo=";
  X509Certificate x509Certificate = CertificateUtil.getX509Certificate(encodedString);
  
  System.out.println("Issuer Name : " + x509Certificate.getIssuerX500Principal());
  
 }
}

Output
Issuer Name : CN=krishna, OU=krishna, O=krishna, L=krishna, ST=krishna, C=kr


Kotlin: Data Classes: copy function

By default, Kotlin data class generate copy function. By using copy function, we can copy data object by altering some of its properties.

         var employee1 = Employee("Krishna", "Gurram", "India")
         var employee2 = employee1.copy(firstName = "Chamu")

Find the below working application.

Test.kt
package com.sample.test

data class Employee(var firstName: String, var lastName: String, var country: String)

fun main(args: Array<String>) {
 var employee1 = Employee("Krishna", "Gurram", "India")
 var employee2 = employee1.copy(firstName = "Chamu")

 println("employee1 : $employee1")
 println("employee2 : $employee2")
}

Output
employee1 : Employee(firstName=Krishna, lastName=Gurram, country=India)
employee2 : Employee(firstName=Chamu, lastName=Gurram, country=India)


Can I provide explicit implementation of copy function?
No, it is not allowed.




Previous                                                 Next                                                 Home

Monday, 12 February 2018

Kotlin: Data classes

Data classes are special kind of classes in kotlin, their main purpose is to hold the data.

Kotlin derives below members for the data classes.

a.   equals()/hashCode() pair
b.   toString() of the form "User(name=John, age=42)"
c.   componentN() functions corresponding to the properties in their order of declaration
d.   copy().

How to define data class?
By using the keyword ‘data’ we can define data classes.

Syntax
data class ClassName(memberVariables)

Ex
data class Employee(var firstName: String, var lastName: String, var id: Int)

Find the below working application.

Test.kt
package com.sample.test

data class Employee(var firstName: String, var lastName: String, var id: Int)

fun main(args: Array<String>) {
 var obj = Employee("Krishna", "Gurram", 1)

 var firstName = obj.firstName;
 var lastName = obj.lastName
 var id = obj.id

 println("First Name : $firstName")
 println("Last Name : $lastName")
 println("Id : $id")

}

Output

First Name : Krishna
Last Name : Gurram
Id : 1

Is there any constraints while defining data classes?
Yes, below constraint are applied while defining data classes.

a.   The primary constructor needs to have at least one parameter
b.   All primary constructor parameters need to be marked as val or var
c.   Data classes cannot be abstract, open, sealed or inner

d.   Data classes may only implement interfaces.






Previous                                                 Next                                                 Home