Saturday, 20 February 2016

Upgrading Eclipse from Juno to Kepler

Background

In this post I will show you how to upgrade your Eclipse from Juno to Kepler. My current installation details are as follows -



Upgrading Eclipse from Juno to Kepler

  • First you need to add update sites. So go to Windows -> preference. Then search for "Available software sites" and select Add... Then you need to add following 2 sites -
    1. Kepler release repo: http://download.eclipse.org/releases/kepler
    2. Kepler update repo: http://download.eclipse.org/eclipse/updates/4.3
  • Next go to Windows -> Check for Update

  • Previous step may take come time as it checks for new updates. Next select updates as follows -
  • Click Next, accept TnC and click finish to start installation of updates. After installation is complete simply restart Eclipse and you should get Eclipse Kepler.


Using Lambda Expressions from Java 8

Background

It's been some time since Java 8 is out and with it there are some major changes that have come in. Some examples are -
  • Lambda expression
  • Stream collection APIs
  • Functional interfaces etc.
In this post we will see what are Lambda expressions and how we use it in code. 

Introduction

Lambda expression is essentially an anonymous method. But it's not just any method. It is implementation of abstract method that is present in an functional interface. So lambda expression form a kind of anonymous class. Lambda expressions are also called closures.

We said lambda expression essentially implements an abstract method in an functional interface. But what is an functional interface. Functional interface is nothing but an interface with just one abstract method. For example consider interface Runnable . It has a single abstract method run(). So Runnable is a functional interface.

NOTE : A functional interface may specify any public method defined by Object, such as equals( ),
without affecting its “functional interface” status. The public Object methods are considered implicit
members of a functional interface because they are automatically implemented by an instance of a
functional interface.

Lambda expressions and function interfaces

Enough with the introduction. Lets see an example of lambda expression. Consider following interface - 

interface MyInterface {
       int getAge(); 
} 

Does above interface qualify as a functional interface? It certainly does. It just has one method and all methods in an interface and by default public and abstract [Note : There is an exception to this as since Java 8  you can specify default implementation in interface itself but for now I am going to keep default methods away from discussion. We can revisit it in some future post]. Ok So we have a functional interface. Now lets see how we can write a lambda expression for this.

MyInterface myInterface = () -> 24;
System.out.println(myInterface .getAge());

And you should get 24 printed in console. Before we go in the details of this expression lets first look how lambda expression is structure and read. Lambda expression used is - 

  () -> 24
'->' operator is called lambda operator or arrow operator. It divides your lambda expression into two parts. LHS of the operator specifies the arguments of the abstract method of the functional interface. RHS is the body of the method (the return value). RHS can either be a single line or a block of code. The lambda expression is read as "LHS goes to RHS".



NOTE : Single line lambda expressions are called expression lambdas where as the ones with block are called block lambdas.

Difference : Difference between expression and block lambdas is that block lambdas must have a return statement unlike expression lambdas where is it obvious (RHS).

Some more examples

Lets take some more examples to understand this better. Consider following functional interface

interface MyInterface {
       boolean isAllowedAge(int currentAge); 
} 

For this your lambda expression can be -

MyInterface myInterface = (n) -> n>=18;
System.out.println(myInterface.isAllowedAge(4));


Couple of points to note here -

  • Note we are no where specifying the type of n. It is automatically inferred from the functional interface. But if you wish you can specify it -

    MyInterface myInterface = (int n) -> n>=18;
    System.out.println(myInterface.isAllowedAge(4));
    


    However if you specify type of one arguments you should do that for all other arguments. So something like (int n, m) -> n>=m; is not allowed. Also the argument should qualify/match. So something like below wont work


    MyInterface myInterface = (int n) -> "test";   //will not work
    System.out.println(myInterface.isAllowedAge(4));
    
  • If you just have one argument then you don't need parenthesis on the LHS of lambda expression. So you can do something like - 
    MyInterface myInterface = n -> n>=18;
    System.out.println(myInterface.isAllowedAge(4));
    


    But it may get confusing at time. So it is better to always use a parenthesis even if you have one argument :)
Lets see a two argument lambda expression -

Your interface is

interface MyInterface {
       boolean isAllowedAge(int currentAge, int minAge); 
}


and your lambda expression would look something like -

MyInterface myInterface = (n,m) -> n>=m;
System.out.println(myInterface.isAllowedAge(4,5));

Block lambda expression for same interface would look like -

MyInterface myInterface = (n,m) -> {
    int minAge = m;
    if (n >= minAge )
        return true;
    else
        return false;
    }
System.out.println(myInterface.isAllowedAge(4,5));



As you must have noticed you can have local variables, loops, switch statement etc in your block body.

Another good example would be -

Comparator c = (a, b) -> Integer.compare(a.length(), b.length());

OR

Runnable myRunner= () ->{
    System.out.println("I am running");
}; 


NOTE : The default methods introduced in Java 8 do not affect the functional status of an interface. By definition functional interface just has one abstract method. It can have other default methods.

I am going to end up this post here that was intended for lambda expressions introduction. I know there are various follow up topis -

  1. Generic
  2. used as Method arguments
  3. Exception handling

I will come to these topics in subsequent posts.  So stay tuned :)

2nd Part of this tutorial updated -
NOTE  :While it is a good practice to mark a functional interface with the @FunctionalInterface
annotation for clarity, it is not required with functional programming. The Java compiler
implicitly assumes that any interface that contains exactly one abstract method is
a functional interface. Conversely, if a class marked with the @FunctionalInterface
annotation contains more than one abstract method, or no abstract methods at all, then
the compiler will detect this error and not compile.

NOTE : Remember that the parentheses are optional only when there is one parameter and it doesn’t have a type declared.  If you are not using braces you cannot say return something.


NOTE : any public method defined by Object, any default methods or any static methods do not affect the functional status of an functional interface. As long as it has just one abstract method.

 NOTE : If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless an abstract method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface. (JLS)

NOTE : Main thing to understand about Lambdas is deferred execution. This part of code will be executed at a later point of time.

NOTE : Lambdas use the same access rules as inner classes.
Lambda expressions can access static variables, instance variables, effectively final method parameters, and effectively final local variables. 

Related Links

Thursday, 4 February 2016

Android Booting process

Background

Android as we know uses a Linux kernel underneath and as all operating systems it has a boot sequence. Android has following stack -


You can see complete details in one of my previous posts - 

In this process we will see how booting happens in Android.


Android Boot Sequence

To represent the entire process in a picture it would be something like below - 



  1. When you power on your Android device Boot ROM which is hardwired code at a predefine location in your ROM starts executing. This loads your Bootloader code in your RAM and starts executing.
  2. Bootloader is a process that starts before Android OS is loaded. Bootloader code itself is not a part of Android operating system. This code will be customized by the OEMs to put in their restrictions. This program sets up necessary things to run the kernel like memory, clock, network etc.
  3. Next kernel is launched. As the kernel launches, is starts to setup cache, protected memory, scheduling and loads drivers. System can now use virtual memory and launch user space processed. When the kernel finishes the system setup , it looks for “init” in the system files and launch it as the initial user space process.
  4.  init process is the parent process of all processed. This can be found at location  -
    • <android source>/system/core/init
    It is the 1st user process that starts. It has two resposibilities -.
    1. Mounts directories like /sys , /dev or /proc and
    2. Runs init.rc file located at - <android source>/system/core/rootdir/init.rc
    This is a script that describes the system services, file system and other parameters that need to be set up. If you refer above picture init process initializes zygote, runtime and daemon processed. At this point you should see the Android logo on your screen. 
  5. As we know each Java process runs in a separate JVM. However in an handheld system like that of Android both memory footprint and startup time must be considered. So JVM with some customizations needed for Android is called Dalvik VM that runs Android applications.  Also initi process which starts up Zygote process preloads and initializes core libraries needed for the VM. For each new app a new VM is forked from zygote and app is run in it's sandboxed environment. Zygote provides pre warmed up VM instance to the app to run thereby reducing the startup time.
  6. After complete above steps, runtime request Zygote to launch system servers. System Servers are written in native and java both. The system server is the first java component to run in the system. It will start system services like Power Manager, Activity Manger, Telephony Service etc.
  7. Once System Services up and running in memory, Android has completed booting process, At this time “ACTION_BOOT_COMPLETED” standard broadcast action will fire.
 When an app starts new VM is forked from zygote and app is started in it (sanboxed).



NOTE : When zygote does a fork on receiving a command it uses copy-on-write technique. Memory is copied only when the new process tries to modify it.

Also the core libraries that zygote loads on startup are read only and cannot be modified. So they are not copied over but shared with new forked processes.

All of these led to quick startup and less memory footprint.

NOTE : Zygote isn't really bound up with Dalvik, it's just an init process. Zygote is the method Android uses to start apps. Rather than having to start each new process from scratch, loading the whole system and the Android framework afresh each time you want to start an app, it does that process once, and then stops at that point, before Zygote has done anything app-specific. Then, when you want to start an app, the Zygote process forks, and the child process continues where it left off, loading the app itself into the VM.

Related Links

Monday, 25 January 2016

Replacing web.xml with Java based configuration for Servlet 3.x Webapplications using Spring

Background



As we know if you want to deploy a web app in a container like tomcat you have a context file called web.xml that creates context necessary for you app to run. For eg. you can provide libraries that will be available to your web app. 

Your typical web.xml will look like - 


<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>Spring Web MVC Demo Application</display-name>

  <servlet>
      <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
     <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
  </servlet-mapping>
   

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
</web-app>


Lets see its Java equivalent

Java Configuration

  • For Java configuration you can write your own class that implements WebApplicationInitializer  interface and override it's
    onStartup() method.
  • WebApplicationInitializer is an interface provided by Spring MVC that ensures your implementation is detected and automatically used to initialize any Servlet 3 container.
  • An abstract base class implementation of WebApplicationInitializer named AbstractDispatcherServletInitializer makes it even easier to register the DispatcherServlet by simply overriding methods to specify the servlet mapping and the location of the DispatcherServlet configuration.  
  • This is from Spring 3.1+
Lets now see the Java config -


public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
    
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

        rootContext.register(RootApplicationConfig.class);
       
        container.addListener(new ContextLoaderListener(rootContext));
       
        AnnotationConfigWebApplicationContext displacherContext = new AnnotationConfigWebApplicationContext();
        displacherContext.register(MyWebConfig.class);
    
    
        ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(displacherContext));
        registration.setLoadOnStartup(1);
        registration.addMapping("/");
    }
} 


Code for MyWebConfig.java and RootApplicationConfig.java are given below -

Or as I mentioned before you can extend abstract class AbstractDispatcherServletInitializer.

public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {

    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }

    @Override
    protected WebApplicationContext createServletApplicationContext() {
        XmlWebApplicationContext cxt = new XmlWebApplicationContext();
        cxt.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
        return cxt;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }


Now you don't need web.xml as part of your web application. Your container will startup your app using Java config provided. This classes are detected automatically.

 RootApplicationConfig.java

 package com.osfg.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * 
 * @author athakur
 * Root applciation context
 * Services and data sources should go here - common to all web application contexts
 */
@Configuration
@ComponentScan({ "com.osfg" })
@PropertySource(value = { "classpath:com/osfg/resources/spring-props.properties" })
public class RootApplicationConfig {


}


Source :  https://github.com/aniket91/SpringFeaturesDemo/blob/master/src/com/osfg/config/RootApplicationConfig.java



MyWebConfig.java

package com.osfg.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * 
 * @author athakur
 * Dispacher servlet context - web app context
 * All Controllers. handler mappings, viewresolvers etc should go here
 */
@Configuration
@ComponentScan({ "com.osfg.controllers" })
@EnableWebMvc
public class MyWebConfig {
    
    @Bean
    public ViewResolver getViewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/pages/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

}


Source : https://github.com/aniket91/SpringFeaturesDemo/blob/master/src/com/osfg/config/MyWebConfig.java


 You can see the complete sample code in my github repo -



If you are not using Spring you will need to do -

  1. Create a custom class that implements ServletContainerInitializer (i.e. com.osfg.MyServletContainer
  2. Create a file in your META-INF/services folder named javax.servlet.ServletContainerInitializer which will contain the name of your implementation above (com.osfg.MyServletContainer)
In Spring ofcourse you don't need to do this.

Related Links

Friday, 8 January 2016

Making @PathVariable optional in Spring MVC

Background



A simple controller class would look like - 


    @RequestMapping(value="/home/{name}", method = RequestMethod.GET)
    public String welcome(Model model,  @PathVariable(value="name") String name, @RequestParam(value="surname") String surname) {
        model.addAttribute("test", "TestValue");
        System.out.println("Name : " + name);
        System.out.println("Surname : " + surname);
        return "welcome";
    }

This controller method basically expects a URL like 
  • http://localhost:8080/WebProject/home/aniket?surname=thakur
where aniket is the name (path variable) where as thakur is the surname (request param).

Here you cannot have name or surname blank. If you do you will get an error.  So URLs like -
  • http://localhost:8080/WebProject/home?surname=thakur OR

    You will get  HTTP Status 404 - Requested Resource is not available
  • http://localhost:8080/WebProject/home/aniket

    You will get - HTTP Status 400 - Required String parameter 'surname' is not present
 will not work!

 Only URL that will work as mentioned above is -

  • http://localhost:8080/WebProject/home/aniket?surname=thakur
For this URL you should see output as -

Name : aniket
Surname : thakur

However you can make @RequestParam option. Spring provides you this functionality. All you have to do is set it's required property as false i.e
  • @RequestParam(value="surname", required=false) String surname
Now you can hit the URL -
  •  http://localhost:8080/WebProject/home/aniket
and you should not see 404 error. Output would print -

Name : aniket
Surname : null

However there is no such parameter in @PathVariable. So you cannot truly make it optional. However there are alternative and we will look at them now.

 Making @PathVariable optional in Spring MVC

There are two way in which you can work - 

  1. Provide two paths in value - One with path param and one without. In Arguments take map of path params and check for null.


        @RequestMapping(value={"/home/{name}","/home"}, method = RequestMethod.GET)
        public String welcome(@PathVariable Map<String, String> pathVariablesMap) {
            if (pathVariablesMap.containsKey("name")) {
                //corresponds to path "/home/{name}"
                System.out.println("With Name : " + pathVariablesMap.get("name"));
            } else {
                //corresponds to path "/home"
                System.out.println("With No Name");
            }   
            return "welcome";
        }
    


    Here you are essentially saying this controller will map to both URLS - "/home/{name}" and "/home" and if you do get name in pathparams map then the URL was "/home/{name}" else it was "/home".

    And now if you hit http://localhost:8080/WebProject/home/aniket you should get output as - "With Name : aniket" and if you hit http://localhost:8080/WebProject/home you should see output - "With No Name".
  2.  Another way is to use java.util.Optional provided by Java8. So if you are using Spring 4.1 and Java 8 you can use java.util.Optional which is supported in @RequestParam, @PathVariable, @RequestHeader and @MatrixVariable in Spring MVC -

        @RequestMapping(value="/home/{name}", method = RequestMethod.GET)
        public String welcome(@PathVariable Optional<String> name) {
            if (name.get() != null) {
                //corresponds to path "/home/{name}"
                System.out.println("With Name : " + name.get());
            } else {
                //corresponds to path "/home"
                System.out.println("With No Name");
            }   
            return "welcome";
        }
    


    Repeat same test as point 1. You should get same result. This is just another alternate way.

So as we have seen pathvariables cannot truly be null but there are workarounds. This case should not typically arise as it is poor design. You should always have some value in path param. If you are certain it can be null better make it a @RequestPram and use requiref=false.


Related Links

t> UA-39527780-1 back to top