Create Docker image with Maven build

There are lots of maven Docker plugin available to integrate the docker with maven.

In this example, I am going to show how to build the Docker image while building a maven project.

Copy the below snippet and put into your pom.xml file and then create a maven property “docker.image.name” with the appropriate docker image name and also make sure that the Dockerfile available in the correct location.

Then run the ‘mvn install’ and once its done, run ‘docker images’ and check that the docker image is available in the list of images.

pom.xml:


  <plugin>
	<groupId>org.codehaus.mojo</groupId>		
	<artifactId>exec-maven-plugin</artifactId>		
	<version>1.4.0</version>		
	<executions>		
		<execution>		
			<goals>		
				<goal>java</goal>		
			</goals>		
		</execution>		
		<execution>		
			<id>build-image</id>		
			<phase>install</phase>		
			<goals>		
				<goal>exec</goal>		
			</goals>		
			<configuration>		
				<executable>docker</executable>		
				<arguments>		
					<argument>build</argument>		
					<argument>-t=${docker.image.name}</argument>		
					<argument>.</argument>		
				</arguments>		
			</configuration>		
		</execution>		
	</executions>			
 </plugin>		
<plugin>
      
Advertisements

Create private function in AngularJs controller

If we want to create a private function inside an AngualrJS controller file, then we should prefix the function with _ symbol. Refer the below example.


class customerController {    
	// when landing on the page, get all customes and show them
	constructor($scope, $http) {
		 this.$http = $http;
		 this.customers = this._formatCustomers(this.getCustomers());
	}
	
    getCustomers() {
         this.$http({
              method: 'GET',
              url: `/api/customers`
          }).then(response => response.data);				
    }
	
    _formatCustomers(data) {
       //You can put some logic here to format the customer data.           
    }
}

angular.module('myApp').controller('customerController', customerController);


In the above example, customerController has two functions. They are getCustomers and _formatCustomers. Note that the first one is public and the later is private which can be accessed only within the controller js file.

‘Library Fine’ problem in Hackerrank – solution in Scala

Problem Statement:

The Head Librarian at a library wants you to make a program that calculates the fine for returning the book after the return date. You are given the actual and the expected return dates. Calculate the fine as follows:

If the book is returned on or before the expected return date, no fine will be charged, in other words fine is 0.

If the book is returned in the same month as the expected return date, Fine = 15 Hackos × Number of late days

If the book is not returned in the same month but in the same year as the expected return date, Fine = 500 Hackos × Number of late months

If the book is not returned in the same year, the fine is fixed at 10000 Hackos.

Refer the below link to know more about this problem. https://www.hackerrank.com/challenges/library-fine

Solution in Scala


import java.util.{Calendar, Scanner}

object Solution {

    def main(args: Array[String]) {
       val scanner: Scanner = new Scanner(System.in)

    //Actual Returned Date
    val aDate: Int = scanner.nextInt
    val aMonth: Int = scanner.nextInt
    val aYear: Int = scanner.nextInt

    //Due Date
    val dDate: Int = scanner.nextInt
    val dMonth: Int = scanner.nextInt
    val dYear: Int = scanner.nextInt

    val isValidData: Boolean = ((aDate >= 1 && aDate = 1 && dDate = 1 && aMonth = 1 && dMonth = 1 && aYear = 1 && dYear <= 3000))

    var fineAmount: Int = 0
    if (isValidData) {
      val actualCalendar: Calendar = Calendar.getInstance()
      actualCalendar.set(aYear, aMonth, aDate)

      val dCalendar: Calendar = Calendar.getInstance()
      dCalendar.set(dYear, dMonth, dDate)

      if ((actualCalendar.getTime == dCalendar.getTime) || actualCalendar.getTime.before(dCalendar.getTime)) {
        fineAmount = 0
      }
      else if (actualCalendar.getTime.after(dCalendar.getTime) && aYear == dYear) {
        fineAmount = if ((aMonth == dMonth)) 15 * (aDate - dDate) else 500 * (aMonth - dMonth)
      }
      else {
        fineAmount = 10000
      }
    }
    println(fineAmount)
    }
}

How to use ReflectionUtils to retrieve the field value

In this post, I am going to show how we can use the ReflectionUtils to get the field value from an object.

Most of the time, we use Java Reflection to retrieve the value but if the field is in the Super class, then you have to write some boilerplate code to retrieve those. But if you use ReflectionUtils, then you won’t have to worry about that.

Refer the below example,

BaseProfile and Employee are the two value objects. Here the Employee class extends BaseProfile class which has some common fields. Then in ReflectionUtilsMain, I am using Java reflection and also ReflectionUtils to retrieve the value of “firstName” field

Let’s check the code.

BaseProfile.java


import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;


public class BaseProfile {

    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 ReflectionToStringBuilder.toString(this);
    }

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

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

        BaseProfile that = (BaseProfile) o;

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

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

BaseProfile.java


import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;


public class Employee extends BaseProfile {

    private String empId;

    private String designation;

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String empId) {
        this.empId = empId;
    }

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }

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

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

        Employee employee = (Employee) o;

        return new EqualsBuilder()
                .appendSuper(super.equals(o))
                .append(empId, employee.empId)
                .append(designation, employee.designation)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .appendSuper(super.hashCode())
                .append(empId)
                .append(designation)
                .toHashCode();
    }

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

Here is our main class
ReflectionUtilsMain.java


import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;

public class ReflectionUtilsMain {

    public static void main(String[] args) {

        Employee employee = new Employee();
        employee.setEmpId("1234");
        employee.setFirstName("John");
        employee.setLastName("Turner");
        employee.setDesignation("Manager");
        System.out.println(employee);

        //Now you want to access the First Name from Employee object with Java reflection
        String firstName = null;
        String fieldName = "firstName";
        for (Class aClass = employee.getClass(); aClass != null; aClass = aClass.getSuperclass()) {
            System.out.println("aClass:" + aClass.getSimpleName());
            try {
                Field field = aClass.getDeclaredField(fieldName);
                if (!field.isAccessible()) {
                    System.out.println("Field is found "+field);
                    field.setAccessible(true);
                    firstName = (String) field.get(employee);
                    break;
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                System.err.print(ExceptionUtils.getStackTrace(e));
            }
        }
        System.out.println("Using Reflection firstName:" + firstName);
        firstName = null;
        //You can also use ReflectionUtils to get this very easily
        try {
            Field field = FieldUtils.getField(employee.getClass(), fieldName, true);
            firstName = (String) field.get(employee);
        } catch (Exception e) {
            System.err.print(ExceptionUtils.getStackTrace(e));
        }
        System.out.println("Using Reflection Utils firstName:" + firstName);

    }
}

The output will be like this,


java.lang.NoSuchFieldException: firstName
	at java.lang.Class.getDeclaredField(Class.java:2070)
	at org.cas.osd.mp.ReflectionUtilsMain.main(ReflectionUtilsMain.java:29)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
org.cas.osd.mp.Employee@42110406[empId=1234,designation=Manager,firstName=John,lastName=Turner]
aClass:Employee
aClass:BaseProfile
Field is found private java.lang.String org.cas.osd.mp.BaseProfile.firstName
Using Reflection firstName:John
Using Reflection Utils firstName:John

Scala: Enum Creation Examples

Enum is used for creating a group of constants like the days of week, colors and etc.

In this post, I am going to show how to create enums in Scala.

There are two ways,
1. Using Scala Enumeration
2. Using Scala Traits

Using Scala Enumeration

Scala has Enumerations class which can be extended to create an Enum. Check the below example.


object ScalaEnumObject {

  def main(args: Array[String]) {
    println("Event:")
    Event.values foreach println
  }
  //Extends Enumeration class
  object Event extends Enumeration {
    type Event = Value
    val CREATE, READ, UPDATE, REMOVE = Value
  }
}

The output looks below,


Event:
CREATE
READ
UPDATE
REMOVE

Using Scala Traits
We can use Trait to create Enums. Trait is similar to Java interface. So we can create a Trait and then create the case object which extends that Trait for each Enum values.

Check the below example.


object ScalaEnumObject {

  def main(args: Array[String]) {
    println("Directions:")
    val directions = List(EAST,WEST,SOUTH,NORTH)
    directions.foreach(direction => println (direction.name))
  }

   //Using Trait
  sealed trait Direction {
    def name: String
  }

  case object EAST extends Direction {
    val name = "E"
  }

  case object WEST extends Direction {
    val name = "W"
  }

  case object SOUTH extends Direction {
    val name = "S"
  }

  case object NORTH extends Direction {
    val name = "N"
  }
}

The output looke below,


Directions:
E
W
S
N