Friday 9 December 2016

Java 8 - Lambda Expression sample - Filter and Sort


Scenario :
===========

If we want to dispaly Student details with age > 30 and sort by StudentName and get the result students in List.



import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
public class Java8 {
    public static void main(String[] args) {
        Student std1 = new Student();
        Student std2 = new Student();
        Student std3 = new Student();
        Student std4 = new Student();

        std1.setStudId(1); std1.setStudName("xxx"); std1.setAge(44);
        std2.setStudId(22); std2.setStudName("zzz"); std2.setAge(22);
        std3.setStudId(3); std3.setStudName("fff"); std3.setAge(32);
        std4.setStudId(44); std4.setStudName("mmm"); std4.setAge(66);

        List<Student> studentList = new ArrayList<Student>();
        studentList.add(std1);studentList.add(std2);studentList.add(std3);studentList.add(std4);

        List<Student> list = studentList.stream()
                                .filter(st -> st.getAge() > 30)
                                .sorted(Comparator.comparing(Student::getStudName))
                                .collect(toList());

        list.forEach(System.out::println);
    }
}

class Student{

    @Override    public int hashCode() {
        return new Integer(31*studId).hashCode();
    }

    @Override    public boolean equals(Object obj) {
        return super.equals(obj);
    }

    @Override    public String toString() {
        return "Student{" +
                "studId=" + studId +
                ", studName='" + studName + '\'' +
                ", Age=" + Age +
                '}';
    }

    int studId;
    String studName;
    int Age;

    public int getStudId() {
        return studId;
    }

    public void setStudId(int studId) {
        this.studId = studId;
    }

    public String getStudName() {
        return studName;
    }

    public void setStudName(String studName) {
        this.studName = studName;
    }

    public int getAge() {
        return Age;
    }

    public void setAge(int age) {
        Age = age;
    }
}

Output:
-----------

Student{studId=3, studName='fff', Age=32}
Student{studId=44, studName='mmm', Age=66}
Student{studId=1, studName='xxx', Age=44}

Sunday 6 November 2016

import a file/dependencies from repositories - maven (pom.xml)

<properties>
   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
   <sqljdbc.version>4.0</sqljdbc.version>
</properties>

<repositories>
   <repository>
      <id>API_Repository</id>
      <name>API Repository</name>
      <url>file:\\sharedDrive\location\sample\jarsfolder</url>
   </repository>
</repositories>

<dependencies>
   <dependency>
      <groupId>com.microsoft.sqlserver</groupId>
      <artifactId>sqljdbc</artifactId>
      <version>${sqljdbc.version}</version>
   </dependency>
</dependencies>



difference between maven compile vs provided

compile
This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.

provided
This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.

=============================================================

compile
Make available into class path, don't add this dependency into final jar if it is normal jar; but add this jar into jar if final jar is a single jar (for example, executable jar)

provided
Dependency will be available at run time environment so don't add this dependency in any case; even not in single jar (i.e. executable jar etc)

==============================================================

Compile means that you need the JAR for compiling and running the app. For a web application, as an example, the JAR will be placed in the WEB-INF/lib directory.

Provided means that you need the JAR for compiling, but at run time there is already a JAR provided by the environment so you don't need it packaged with your app. For a web app, this means that the JAR file will not be placed into the WEB-INF/lib directory.

For a web app, if the app server already provides the JAR (or its functionality), then use "provided" otherwise use "compile".

Different types of scope in maven pom.xml

The <scope> element can take 6 value: compile, provided, runtime, test, system and import.

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>


compile
This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.
provided
This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.
runtime
This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.
test
This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.
system
This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.
import (only available in Maven 2.0.9 or later)
This scope is only used on a dependency of type pom in the section. It indicates that the specified POM should be replaced with the dependencies in that POM's section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

Friday 4 November 2016

Missing URI template variable - Spring MVC issue - Troubleshoot

{
  "timestamp": 1478261692885,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "org.springframework.web.bind.MissingPathVariableException",
  "message": "Missing URI template variable 'id' for method parameter of type String",
  "path": "/admin/3"
}


@RestController
public class ApiAdminController {

    @RequestMapping(name = "/admin/{id}", method = RequestMethod.GET)
    public ResponseEntity<Set<Object[]>> getPermissions(@PathVariable String id){
                .......
                .......
                }
}

Solution : Change name to value in @RequestMapping

@RestController
public class ApiAdminController {

    @RequestMapping(value = "/admin/{id}", method = RequestMethod.GET)
    public ResponseEntity<Set<Object[]>> getPermissions(@PathVariable String id){
                .......
                .......
                }
}


Monday 17 October 2016

4 Principles/Elements of Simple Design

  • Passes all the tests.
  • Express every idea we need to express.
  • Contains no duplication.
  • Minimized the number of classes, methods and other moving parts.


Three laws of TDD

Uncle Bob describes TDD with three rules:
  1. You are not allowed to write any production code unless it is to make a failing unit test pass.
  2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
  3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
Read them carefully and you'll notice they're simpler than they look like, but they have a lot of repetition so here's a "refactored" version:
  1. Write production code only to make a failing unit test pass.
  2. Write only enough of a unit test to fail.
  3. Write only enough production code to make the failing unit test pass.
It's obvious now that rule 3 implies rule 1, so here's a concise version that I've found easier to remember:
  1. Write only enough of a unit test to fail.
  2. Write only enough production code to make the failing unit test pass.
This couple of rules also serve me as a checklist when I'm developing, so I just repeat them in order, over and over, to keep me in the TDD loop.

Sunday 16 October 2016

Session affinity or Sticky Session - Load balancing

Most common load balancing techniques in web based applications are
  1. Round robin
  2. Session affinity or sticky session
  3. IP Address affinity
We talk only about Sticky Session here:
----------------------------------------------------

When your website is served by only 1 web server, for each pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.
However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 webservers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.
Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on 3 independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session. If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.
To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.

Method Parameter names in Java 8 using reflection? - Java 8 - Lambda

This is the new method added in jdk1.8
https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Executable.html#getParameters--

import java.lang.reflect.Method;
import java.util.Arrays;

public class GetParamtersEx {
    public static void main(String[] args) {
        Method[] me = SampleEx.class.getDeclaredMethods();
        Arrays.stream(me).forEach(x -> Arrays.stream(x.getParameters())
                         .forEach(y -> System.out.println(y.getName())));
    }
}

Java 8 Interface Changes – static method, default method

Java 8 interface changes include static methods and default methods in interfaces. Prior to Java 8, we could have only method declarations in the interfaces. But from Java 8, we can have default methods and static methods in the interfaces.

Java 8 Interface

Designing interfaces have always been a tough job because if we want to add additional methods in the interfaces, it will require change in all the implementing classes. As interface grows old, the number of classes implementing it might grow to an extent that it’s not possible to extend interfaces. That’s why when designing an application, most of the frameworks provide a base implementation class and then we extend it and override methods that are applicable for our application.
Let’s look into the default interface methods and static interface methods and the reasoning of their introduction in Java 8 interface changes.

Java Interface Default Method

For creating a default method in java interface, we need to use “default” keyword with the method signature. For example,
package com.journaldev.java8.defaultmethod;

public interface Interface1 {

 void method1(String str);
 
 default void log(String str){
  System.out.println("I1 logging::"+str);
 }
}
Notice that log(String str) is the default method in the Interface1. Now when a class will implement Interface1, it is not mandatory to provide an implementation for default methods of the interface. This feature will help us in extending interfaces with additional methods, all we need is to provide a default implementation.
Let’s say we have another interface with following methods:
package com.journaldev.java8.defaultmethod;

public interface Interface2 {

 void method2();
 
 default void log(String str){
  System.out.println("I2 logging::"+str);
 }

}
We know that Java doesn’t allow us to extend multiple classes because it will result in the “Diamond Problem” where the compiler can’t decide which superclass method to use. With the default methods, the diamond problem would arise for interfaces too. Because if a class is implementing both Interface1 andInterface2 and doesn’t implement the common default method, the compiler can’t decide which one to chose.
Extending multiple interfaces are an integral part of Java, you will find it in the core java classes as well as in most of the enterprise application and frameworks. So to make sure, this problem won’t occur in interfaces, it’s made mandatory to provide implementation for common default methods of interfaces. So if a class is implementing both the above interfaces, it will have to provide implementation for log() method otherwise compiler will throw compile time error.
A simple class that is implementing both Interface1 and Interface2 will be:
package com.journaldev.java8.defaultmethod;

public class MyClass implements Interface1, Interface2 {

 @Override
 public void method2() {
 }

 @Override
 public void method1(String str) {
 }

 @Override
 public void log(String str){
  System.out.println("MyClass logging::"+str);
  Interface1.print("abc");
 }
}
Important points about java interface default methods:
  1. Java interface default methods will help us in extending interfaces without having the fear of breaking implementation classes.
  2. Java interface default methods have bridge down the differences between interfaces and abstract classes.
  3. Java 8 interface default methods will help us in avoiding utility classes, such as all the Collections class method can be provided in the interfaces itself.
  4. Java interface default methods will help us in removing base implementation classes, we can provide default implementation and the implementation classes can chose which one to override.
  5. One of the major reason for introducing default methods in interfaces is to enhance the Collections API in Java 8 to support lambda expressions.
  6. If any class in the hierarchy has a method with same signature, then default methods become irrelevant. A default method cannot override a method from java.lang.Object. The reasoning is very simple, it’s because Object is the base class for all the java classes. So even if we have Object class methods defined as default methods in interfaces, it will be useless because Object class method will always be used. That’s why to avoid confusion, we can’t have default methods that are overriding Object class methods.
  7. Java interface default methods are also referred to as Defender Methods or Virtual extension methods.

Java Interface Static Method

Java interface static method is similar to default method except that we can’t override them in the implementation classes. This feature helps us in avoiding undesired results incase of poor implementation in implementation classes. Let’s look into this with a simple example.
package com.journaldev.java8.staticmethod;

public interface MyData {

 default void print(String str) {
  if (!isNull(str))
   System.out.println("MyData Print::" + str);
 }

 static boolean isNull(String str) {
  System.out.println("Interface Null Check");

  return str == null ? true : "".equals(str) ? true : false;
 }
}
Now let’s see an implementation class that is having isNull() method with poor implementation.
package com.journaldev.java8.staticmethod;

public class MyDataImpl implements MyData {

 public boolean isNull(String str) {
  System.out.println("Impl Null Check");

  return str == null ? true : false;
 }
 
 public static void main(String args[]){
  MyDataImpl obj = new MyDataImpl();
  obj.print("");
  obj.isNull("abc");
 }
}
Note that isNull(String str) is a simple class method, it’s not overriding the interface method. For example, if we will add @Override annotation to the isNull() method, it will result in a compiler error.
Now when we will run the application, we get following output.
Interface Null Check
Impl Null Check
If we make the interface method from static to default, we will get following output.
Impl Null Check
MyData Print::
Impl Null Check
Java interface static method is visible to interface methods only, if we remove the isNull() method from theMyDataImpl class, we won’t be able to use it for the MyDataImpl object. However like other static methods, we can use interface static methods using class name. For example, a valid statement will be:
boolean result = MyData.isNull("abc");
Important points about java interface static method:
  1. Java interface static method is part of interface, we can’t use it for implementation class objects.
  2. Java interface static methods are good for providing utility methods, for example null check, collection sorting etc.
  3. Java interface static method helps us in providing security by not allowing implementation classes to override them.
  4. We can’t define interface static method for Object class methods, we will get compiler error as “This static method cannot hide the instance method from Object”. This is because it’s not allowed in java, since Object is the base class for all the classes and we can’t have one class level static method and another instance method with same signature.
  5. We can use java interface static methods to remove utility classes such as Collections and move all of it’s static methods to the corresponding interface, that would be easy to find and use.

Java Functional Interfaces

Before I conclude the post, I would like to provide a brief introduction to Functional interfaces. An interface with exactly one abstract method is known as Functional Interface.
A new annotation @FunctionalInterface has been introduced to mark an interface as Functional Interface. @FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces. It’s optional but good practice to use it.
Functional interfaces are long awaited and much sought out feature of Java 8 because it enables us to uselambda expressions to instantiate them. A new package java.util.function with bunch of functional interfaces are added to provide target types for lambda expressions and method references. We will look into functional interfaces and lambda expressions in the future posts.

Friday 14 October 2016

Difference between StackOverflowError vs OutOfMemoryError

When you start JVM you define how much RAM it can use use for processing. JVM divides this into certain memory locations for its processing purpose, two of those are Stack & Heap
OutOfMemoryError is related to Heap. If you have large objects (or) referenced objects in memeory, then you will see OutofMemoryError. If you have strong references to objects, then GC can't clean the memory space allocated for that object. When JVM tries to allocate memory for new object and not enough space available it throws OutofMemoryError because it can't allocate required amount of memory.
How to avoid: Make sure un-necessary objects are available for GC
StackOverflowError is related to stack. All your local variables and methods calls related data will be on stack. For every method call one stack frame will be created and local as well as method call related data will be placed inside the stack frame. Once method execution is completed, stack frame will be removed. ONE WAY to reproduce this is, have infinite loop for method call, you will see stackoverflow error, because stack frame will be populated with method data for every call but it won't be freed (removed).
How to avoid Make sure method calls are ending (not in infinite loop)

=======================================================

Imagine you have a function like the following
public void f(int x) {
    return f(x + 1);
}
When you'll call it the call will call f again and again and again. At each call a bit of information is stored on the stack. Since the stack is limited in size you will get a StackOverflowError.
Now imagine the following code:
for (int i = 1; i > 0; i++)
    vector.add(new BigObject());
where BigObject is a normal Java object. As you see, the loop never terminates. Each allocation is done on the heap thus it will be filled with BigObjects and you will get an OutOfMemoryError.
To recap:
  • OutOfMemoryError is thrown when you are creating objects
  • StackOverflowError is thrown when you are calling functions