Wilson’s Theorem to find prime number

Wilson’s Theorem states that a natural number is p > 1 is a prime number if only if the below condition is met.


  (p - 1) ! ≡  -1   mod p 
 OR  (p - 1) ! ≡  (p-1) mod p

For example, Take p as 4
(4 – 1)! = 3 ! => 3 * 2 * 1 = 6
(6 % 4) != 3 => 6 not equals to 3
So p is not a prime number.

Take p as 5
(5-1)! = 4 ! => 4*3*2*1 = 24
24%5 == 4
4 == 4
So p is a prime number.

Refer the below code to know how to do with a java program.


import java.util.Scanner;

public class PrimeFInder {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int number = scanner.nextInt();
        System.out.println("The entered number is "+number);

        //  (p - 1) ! ≡  (p-1) mod p
        int lhs = getFactorialValue(number- 1) % number;
        int rhs = number - 1;
        if(lhs == rhs){
            System.out.println("Its a prime number");
        }else{
           System.out.println("Its an non prime number");
        }
    }

    private static int getFactorialValue(int n) {
        int value = 1;
        for (int i = 1; i <= n; i++) {
            value *= i;
        }
        return value;
    }
}

The output is given below,


12
The entered number is 12
Its an non prime number


Advertisements

Unroll annotation in Spock Testing framework

Spock is a testing framework for Java and Groovy application. This is a best alternative to Junit. In this post, Let’s see how we can use Unroll annotation of spock framework with an example.

Let’s assume that we have a class called “MathOperation” contains methods to perform arithmetic operations and we have a spock test class to test those methods.

MathOperation.java


public class MathOperation {
    
    private MathOperation(){
        
    }

    public static int sum(int a, int b) {
        return a + b;
    }

    public static int divide(int a, int b) {
        return a / b;
    }

    public static int multiply(int a, int b) {
        return a * b;
    }

    public static int minus(int a, int b) {
        return a - b;
    }
}


The spock test for testing the ‘sum’ method is as below.


import spock.lang.Specification

class MathOperationSpec extends Specification {

    def "sum of two numbers"() {

        expect:
        int actual = MathOperation.sum(num1, num2);
        actual == expected

        where:

        num1 | num2 | expected
        1    | 2    | 3
        2    | 3    | 5
    }

When we run this test case, the test run will look like below,

spock-withouunroll

When an error happened, we are not sure which line caused the problem. It will report only the error method but would not give the information about the exact line. The Unroll annotation helps to fix this problem. Unroll annotation has no effect on how the method gets executed but its an alternation in reporting.

Lets rewrite the above test with Unroll annotation as below.


import spock.lang.Specification
import spock.lang.Unroll

class MathOperationSpec extends Specification {

    @Unroll
    def "sum of two numbers #num1 #num2"() {

        expect:
        int actual = MathOperation.sum(num1, num2);
        actual == expected

        where:

        num1 | num2 | expected
        1    | 2    | 3
        2    | 3    | 5
    }
}

When we run the above one, it will look like below,
spock-withunroll

Java 8: Stream sorted

In this post, we are going to see how we can use Stream.sorted method to sort a collection with an example.

Consider that we have Person class contains “name” and “age” fields and want to sort the list of person objects by age and then by name.

Refer the below code to know how to do that.


import com.google.common.collect.Lists;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class CollectionMain {

    static class Person {
        String name;
        Integer age;

        Person(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return new ToStringBuilder(this, ToStringStyle.SIMPLE_STYLE)
                .append("name", name)
                .append("age", age)
                .toString();
        }

        public String getName() {
            return name;
        }


        public Integer getAge() {
            return age;
        }

    }

    private static final Comparator PERSON_COMPARATOR = Comparator.comparing(Person::getAge).thenComparing(Person::getName);

    public static void main(String[] args) {
        List persons = Lists.newArrayList(new Person("John", 32),
            new Person("Tom", 33),
            new Person("Brad", 35),
            new Person("Varma", 38),
            new Person("Andy", 33));

        System.out.println(persons
            .stream()
            .filter(p -> p.age > 32)
            .sorted(PERSON_COMPARATOR)
            .collect(Collectors.toList()));

    }
}



[Andy,33, Tom,33, Brad,35, Varma,38]

Java: Stream.Reduce

In this post, we are going to see how we can use Stream reduce operation on a list with an example.

Stream.Reduce()

Stream.Reduce() is a general purpose reduction operation. We can use this operation to process a list and find out the max, min and average value. It’s like applying to a list of values and get a single result value.

The syntax is given below


T reduce(T identity, BinaryOperator accumulator)

Here identity is the initial value and accumulator is a function for combining values.

reduce

In the above example, I have a list of string and want to find out the long string in it. I have used reduce operation to find it out.

Let’s see another example. Assume that we want to process a list and modify the value of it and then reduce the value into a single value. Refer the below example to know how we can achieve this with reduce operation.

reduce-modify-list

Dozer Mapping

Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.

This mapper helps us to avoid unnecessary mapping code in our application. Internally it uses reflection.

In this post, We are going to see how we can use this with an example.

Assume that we have a “Person” Bean class which contains the first name, last name, age and address fields. We want to map it into another bean class PersonVO. In addition to that, we want to map the name details into NameVO and address details into AddressVo. Let’s look at below to know how we can do that with Dozer.

Here is our Person Bean class.

Person.java


package com.dozerExample;

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

public class Person {

    private String id;

    private String firstName;

    private String lastName;

    private int age;

    private String streetAddress;

    private String city;

    private String state;

    private String zip;

    private String phoneNumber;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getStreetAddress() {
        return streetAddress;
    }

    public void setStreetAddress(String streetAddress) {
        this.streetAddress = streetAddress;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }
}

We want to map the Person Bean into PersonVO bean and also the first name and last name fields are mapped to NameVO and address are mapped to AddressVO.

Here is the PersonVO Bean class contains the person id, age and NameVo and AddressVo fields.

PersonVO


package com.dozerExample;

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

public class PersonVO {

    private String id;

    private int age;

    private NameVO nameVO;

    private AddressVO addressVO;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public NameVO getNameVO() {
        return nameVO;
    }

    public void setNameVO(NameVO nameVO) {
        this.nameVO = nameVO;
    }

    public AddressVO getAddressVO() {
        return addressVO;
    }

    public void setAddressVO(AddressVO addressVO) {
        this.addressVO = addressVO;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }
}


Here is the NameVO Bean contains the first and last name fields.
NameVO


package com.dozerExample;

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

public class NameVO {

    private String firstName;

    private String lastName;

    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;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }

}

Here is the AddressVO Bean contains the stress address, city, state, zip and phone number fields.
AddressVO


package com.dozerExample;

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

public class AddressVO {

    private String streetAddress;

    private String city;

    private String state;

    private String zip;

    private String phoneNumber;

    public String getStreetAddress() {
        return streetAddress;
    }

    public void setStreetAddress(String streetAddress) {
        this.streetAddress = streetAddress;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }
}

We have to include the below dependency in your pom.xml file.
pom.xml


<dependency>
            <groupId>com.github.dozermapper</groupId>
            <artifactId>dozer-core</artifactId>
            <version>6.1.0</version>
 </dependency>

Then, we need to define the bean mapping field details in an XML. Here is the dozer mapping XML.


<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozermapper.github.io/schema/bean-mapping"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://dozermapper.github.io/schema/bean-mapping http://dozermapper.github.io/schema/bean-mapping.xsd">
    <mapping wildcard="true" map-null="false">
        <class-a>com.dozerExample.Person</class-a>
        <class-b>com.dozerExample.PersonVO</class-b>
        <field>
            <a>firstName</a>
            <b>nameVo.firstName</b>
        </field>
        <field>
            <a>lastName</a>
            <b>nameVo.lastName</b>
        </field>
        <field>
            <a>streetAddress</a>
            <b>addressVo.streetAddress</b>
        </field>
        <field>
            <a>city</a>
            <b>addressVo.city</b>
        </field>
        <field>
            <a>state</a>
            <b>addressVo.state</b>
        </field>
        <field>
            <a>zip</a>
            <b>addressVo.zip</b>
        </field>
        <field>
            <a>phoneNumber</a>
            <b>addressVo.phoneNumber</b>
        </field>
    </mapping>
</mappings>

Now, Let’s use the above mapping file and convert Person into PersonVO and vice versa.



package com.dozerExample;

import org.dozer.DozerBeanMapperBuilder;
import org.dozer.Mapper;

import java.util.UUID;

public class DozerApp {

    public static final String PERSON_DOZER_MAPPING_XML = "dozer-mapping.xml";

    private static Mapper mapper = DozerBeanMapperBuilder.create().withMappingFiles(PERSON_DOZER_MAPPING_XML).build();;

    public static void main(String[] args) {
        Person person = new Person();
        person.setId(UUID.randomUUID().toString());
        person.setFirstName("Michael");
        person.setLastName("Keller");
        person.setAge(45);
        person.setStreetAddress("102 walker st");
        person.setCity("Delaware");
        person.setState("OH");
        person.setZip("45454");
        person.setPhoneNumber("614-434-4535");
        PersonVO personVO = mapper.map(person, PersonVO.class);
        System.out.println("Converting from person to personVO" + personVO);
        Person newPerson = mapper.map(personVO, Person.class);
        System.out.println("Converting from personVO to person" + newPerson);
    }
}

The following is the output of the above program.


Converting from person to personVOcom.dozerExample.PersonVO@467aecef[id=bd993f0e-48f6-4bf7-a942-f902c156ffd4,age=45,nameVO=com.dozerExample.NameVO@5bfbf16f[firstName=Michael,lastName=Keller],addressVO=com.dozerExample.AddressVO@25af5db5[streetAddress=102 walker st,city=Delaware,state=OH,zip=45454,phoneNumber=614-434-4535]]
Converting from personVO to personcom.dozerExample.Person@5f3a4b84[id=bd993f0e-48f6-4bf7-a942-f902c156ffd4,firstName=Michael,lastName=Keller,age=45,streetAddress=102 walker st,city=Delaware,state=OH,zip=45454,phoneNumber=614-434-4535]

JUnit4 Exception testing

In this post, I am going to show how we can write a JUnit test case to test a method which throws an exception.

We can follow any one of the below approaches to test the method throws an exception. Here, I am using JUnit 4.

1. @Test annotation with “expected” attribute
2. try-catch and fail()
3. ExpectedException

Here is my class and contains a method “validateUserData” which has logic to validate the userName and name. If anyone of this has either null or blank then it will throw a RuntimeException with the appropriate message.


import org.apache.commons.lang3.StringUtils;

public class UserDataValidator {

    public void validateUserData(String userName, String name){
        if(StringUtils.isBlank(userName)){
            throw new RuntimeException("userName is null or blank");
        }
        if(StringUtils.isBlank(name)){
            throw new RuntimeException("name is null or blank");
        }
    }
}

Let’s write a JUnit test case to test this method with the above approaches.

@Test annotation with “expected” attribute

Here is the JUnit test to test the “validateUserData” method. I am passing the “userName” as null. So as expected the method throws a RuntimeException.


import org.junit.Test;

public class UserDataValidatorTest {

    @Test(expected = RuntimeException.class)
    public void testValidateUserData_userNameIsNull(){
        UserDataValidator userDataValidator = new UserDataValidator();
        userDataValidator.validateUserData(null, "test");
    }
}

try-catch and fail()

if we want to assert the exception message, then we can follow this approach.


import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

public class UserDataValidatorTest {
    
    @Test
    public void testValidateUserData_userNameIsNull(){
        UserDataValidator userDataValidator = new UserDataValidator();
        try{
            userDataValidator.validateUserData(null, "test");
            fail();
        }catch (Exception e){
            assertEquals("userName is null or blank", e.getMessage());
        }

    }
}

ExpectedException

The ExpectedException rule is used to test the exception type and also the exception message.


import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class UserDataValidatorTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testValidateUserData_userNameIsNull(){
        thrown.expect(RuntimeException.class);
        thrown.expectMessage("userName is null or blank");
        UserDataValidator userDataValidator = new UserDataValidator();
        userDataValidator.validateUserData(null, "test");
    }
}

Java 8 Lambda – Using Map

In this post, I am going to show some examples of using Java 8 Stream map().

I have an arraylist which contains list of strings and want to change the contents of that list to upper case. We can easily do that with map() but I want to make sure that my code should work fine for all types of input such as valid list, empty list and null list.

Refer the below code to know how to do that.


import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class LambdaExample {

    public static void main(String[] args) {

        //Passing valid list
        List validList = Arrays.asList("Name1", "Name2");
        System.out.println("Converting valid list contents to upper case: " + convertAllToUpperCase(validList));
        //Passing an empty list
        System.out.println("Converting an empty list  to upper case: " + convertAllToUpperCase(Collections.emptyList()));
        //Passing null
        System.out.println("Converting null list to upper case: " + convertAllToUpperCase(null));
    }

    private static List convertAllToUpperCase(List list) {
        return Optional.ofNullable(list)
                .orElseGet(Collections::emptyList).stream().map(String::toUpperCase)
                .collect(Collectors.toList());
    }

}


Here, I have used the “Optional” class to handle null list. The code “Optional.ofNullable(list).orElseGet(Collections::emptyList)” will return an empty list when the list is null.

The output of the above program will look like below,


Converting valid list contents to upper case: [NAME1, NAME2]
Converting an empty list  to upper case: []
Converting null list to upper case: []

Now lets see an another example to show how we can map one model class to an another class via Java 8 Functional interface.

There are two model classes here. They are Person and PersonBean. So I want to iterate through the Person list and create an another list of PersonBean.

I have used Function inferface which represents a function that accepts one argument and produces a result. Here the argument is Person and the result is PersonBean.

The first step is to define the function and then use that function while mapping. Refer the below code to know how to do that.


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

public class LambdaExample {

    Function personBeanFunction = person -> {
        PersonBean personBean = new PersonBean();
        personBean.age = person.age;
        personBean.firstName = person.givenName;
        personBean.lastName = person.familyName;
        return personBean;
    };

    public static void main(String[] args) {
        LambdaExample lambdaExample = new LambdaExample();
        List personList = new ArrayList();
        Person person = new Person();
        person.age = 45;
        person.familyName = "test";
        person.givenName = "test";
        personList.add(person);
        System.out.println("PersonList list:" + personList);
        System.out.println("Person Bean list:" + lambdaExample.convert(personList));
    }

    private List convert(List list) {
        return Optional.ofNullable(list).orElseGet(Collections::emptyList).stream()
                .map(personBeanFunction).collect(Collectors.toList());
    }

    private static class Person {
        String familyName;
        String givenName;
        int age;

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("Person{");
            sb.append("familyName='").append(familyName).append('\'');
            sb.append(", givenName='").append(givenName).append('\'');
            sb.append(", age=").append(age);
            sb.append('}');
            return sb.toString();
        }
    }

    private static class PersonBean {
        String firstName;
        String lastName;
        int age;

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("PersonBean{");
            sb.append("firstName='").append(firstName).append('\'');
            sb.append(", lastName='").append(lastName).append('\'');
            sb.append(", age=").append(age);
            sb.append('}');
            return sb.toString();
        }
    }
}

The output of the above program will look like below,


PersonList list:[Person{familyName='test', givenName='test', age=45}]
Person Bean list:[PersonBean{firstName='test', lastName='test', age=45}]