How to install Android N ( Version 7) on Nexus 5


You can install Android N (AOSP) build on your Nexus 5 and use the functionality such as multi windows support, quick notification reply on your Nexus 5 as well. 

Before going ahead, I would remind you that by following this method will void your device warranty/guaranty. There are chances that your device may get bricked (unusable). So make sure you follow the steps correctly and do not stop the process in between.


Requirements:

  • Working android SDK platform tools ( fastboot and dab)
  • Updated USB driver for your device installed on computer.
  • USB debugging enabled on device. Check this for how to enable USB debugging on mobile.
  • Download recovery from TWRP 
  • Download latest Android N (AOSP) image from xda-dev forum, you can choose any other image shared on forum.

Unlocking Bootloader

  • Once you have enabled USB debugging on device and connected device to computer execute below command on command prompt or terminal
    • adb reboot bootloader
  • Once your device restarted, check if the device is in fastboot by executing below command
    • fastboot devices
  • Above command should show your device serial number. If the device serial number is displayed then execute below command
    • fastboot oem unlock
  • A disclaimer will display on the device that must be accepted. Use the volume keys to cycle through the options. Pressing the power button should confirm your selection.
  • Reboot the device from menu if device does not rebooted automatically. Now the bootloader should be unlocked. After reboot if you see the unlocked icon on the bottom of boot screen menu. 
Installing TWRP recovery

  • Connect your device to computer via USB.
  • On command prompt or terminal execute below command
    • adb reboot bootloader
  • Check if the device is on fastboot mode like above. 
  • Make sure the recovery image is in the directory from where you are executing commands.
  • If the device is in fastboot mode, flash recovery entering below command
    • fastboot flash recovery recovery_image_file_name.img
  • Once the flash completes successfully, make sure you reboot the device. 
  • To check if the recovery completed successfully, reboot device in recovery mode, you should see the TWRP recovery menu.
  • In order to manually go to recovery mode -> Powered down the device. Now hold the Volume Down and Volume Up buttons. Then press and hold the Power button until a boot menu appears. Navigate using the volume keys and select RECOVERY using the Power key.
Installing Android N(AOSP)

  • Copy the Android image zip to SD card, you can use the below command to do the same after connecting your device to computer via USB. ( USB debugging is still on)
    • adb push android_image_file_name.zip /sdcard/ 
  • Reboot your device to recovery mode
In TWRP there is an option to backup. You should create a backup before installing custom ROM so that you can go back if anything goes wrong.
Once you have taken a backup:
  • Select Wipe and then Factory Reset.
  • Select Install.
  • Navigate to /sdcard and select the android_image_file_name.zip package.
  • Follow the on-screen notices to install the package.
Once installation has finished, return to the main menu and select Reboot, then System. The device will now boot into Android N.

You can follow the xda-dev forum for troubleshooting if required.



How to enable USB debugging on Android devices

USB debugging has a number of uses on Android devices. To enable USB debugging you should first enable Developer options. Developer options have some setting relevant ro advanced users and developers.

Developer options is hidden by default, and can be activated with the following steps:

  • From Settings, select About phone (or About tablet).
  • Tap the Build number entry seven times. On the seventh tap, you will be notified that "You are now a developer."
  • Return to Settings. Developer options should now be visible just above the About phone ( or About tablet).
Now to enable USB debugging click on the Developer options -> USB debugging (Android debugging). Some devices might require Developer options to be on before clicking on USB debugging.


Design an Parking lot system

Let's consider below are the requirements for parking lot. Based on these requirements we will have to design a parking lot.

Requirements
  • The parking lot has multiple slots.
  • The parking lot can park motorcycles, cars, and buses.
  • The parking lot has small slots, compact slots, and large slots.
  • A motorcycle can park in any slot.
  • A car can park in either a single compact slot or a single large slot.
  • A bus can park only in a single large slot.

We can devise below use cases from above requirement.

Use cases
  • Any vehicle enters and asks for free parking slot ID.
  • If any appropriate parking slot is available, vehicle will get assigned parking slot and that parking slot will be blocked for parking till vehicle leaves the slot.
  • Any vehicle when leaves the parking slot, the same slot will be free for parking other vehicles.
  • If appropriate parking slot (to fit the vehicle) is not available, parking lot will return parking full message.

Lets break up the use cases in different module of functionality.

Parking Lot
  • Parking lot has multiple slots.
  • Parking lot can display is parking is full.
  • Parking lot can tell if given vehicle can be parked or not.
  • Parking lot can allot slot for vehicle.
  • Parking lot can clear allotted slot for vehicle.
  • Parking lot has Parking slot allotter.

Parking slot allotter
  • Parking slot allotter allots the parking slot based  on below algorithm
    • motorcycle can park in any slot
    • car can park in either a single compact slot or a single large slot.
    • bus can park only in a single large slot.
  • If no slot is free for vehicle return, Parking Full message.

Parking Slot
  • Parking slot has type.
  • Parking slot has status.
  • Parking slot has ID.
  • Parking slot can tell if given vehicle can be fit in the slot.

Vehicle
  • Vehicle has a size (small, compact, large), which states how much space required to park
  • Vehicle has type.
  • Vehicle has park and leave parking functionality. 

Slot Type
  • Small
  • Compact
  • Large

Vehicle Type
  • Motorcycle
  • Car
  • Bus

Slot Status
  • Free
  • Occupied


We need to take care that we should not derive individual vehicle type from vehicle, like Car, Bus etc.. Because tomorrow if slot is supporting 10 additional types of vehicle there will be class explosion and we are not much interested in vehicle types here but we are only interested in size of vehicle. Same analogy applies for the parking slot.

Elevator system design

Let's first start with the use cases or requirements of the elevator. There are multiple modules/ systems involved in complete elevator system. We will break down the uses cases as per the individual system.

High Level Requirements:

  1. User should able to request the elevator from the floor.
  2. Once elevator reaches the requested floor, User should get in and should able to choose destination floor.
  3. Once destination is chosen by user, elevator should move to destination floor. 
  4. Once elevator reaches destination floor, user leaves elevator.


User
  • Presses the button on particular floor to request the elevator. 
  • Inside elevator cabin (referred as Cabin here after) user presses the required floor button.
  • Leaves the cabin once elevator reaches particular floor.
Floor
  • Floor has ID which indicates which floor it is.
  • Floor has buttons to request the elevator.
  • Floor has a display which indicates current location of the lift.
Buttons
  • Button get illuminated when pressed indicating the action is performed.
  • Button should stop illuminating once action is complete. 
  • When pressed, button places request for elevator for particular floor.
Cabin
  • Cabin can move up or down as requested by controller.
  • Cabin has set of buttons which tells user which all floors elevator can go.
  • Cabin has button to close/open door.
  • Cabin has door.
  • Cabin commands door to open.
  • Cabin commands door to close.
  • Cabin has weight limit, which indicate how many passengers it can carry.
Door
  • Door can be opened or closed as requested.
  • Once door is open it closes automatically after certain delay.
Elevator Controller
  • Elevator controller start up or stops the elevator.
  • Elevator controller has status of the elevator.
  • Elevator controller accepts request from floor and cabin buttons.
  • Elevator controller commands cabin to move to particular floor.
  • Elevator controller commands cabin to stop.
  • Elevator controller updates status to each floor.
Elevator Request
  • Stores all elevator requests.
  • Has a scheduling algorithm which decides, which request should be served next.
  • Each request has direction, floor id. 

Elevator Status
  • Cabin State
  • Current floor
  • Directions
Cabin State
  • Moving
  • Idle
  • Under Maintenance
Direction
  • Up
  • Down
Now we have got the requirements and also modeled in different artifacts, we can build the UML diagram of the same. 

Installing MariaDB 10.1 on CentOS 6

Inorder to install MariaDB 10.1 you nned to have your MariaDB.repo entry. So create a file "/etc/yum.repos.d/MariaDB.repo" under "/etc/yum.repos.d/" directory.
Update the MariaDB.repo file with below text for 64bit OS

[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.1/centos6-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

Update the MariaDB.repo file with below text for 32bit OS
`
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.1/centos6-x86
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

Now run below command just to check if the repo is set correctly.

#sudo yum search Mariadb 

Now install MariaDB using below command

# yum install MariaDB-server MariaDB*engine MariaDB-client

Error : class_name is not mapped, Hibernate


You may get this error while using Hibernate with Java. There could be multiple reasons why this can happen

  1. You haven't really mapped the class name in config.
  2. The class name ( Entity) is case sensitive, meaning you should specify the entity name as is in the query. Your entity name may differ than table  name in DB, but still you will have to refer to exact case of entity name. 


Exception handling with RestTemplate

Spring framework offers RestTemplate for consuming RESTful services. Recently I used RestTemplate for consuming one of the third party RESTful service.

RestTemplate offers 'ResponseErrorHandler'; which you can extend to decide which are errors for you and how to handle those error. You can override hasError and handleError methods of ResponseErrorHandler.
In handleError you can throw customException if you want, as outlined in below code.

import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;

public class RestTemplateErrorHandler implements ResponseErrorHandler {

    @Override
    public void handleError(ClientHttpResponse response) throws IOException
    {
        throw new MyCustomException(response.getStatusText(), response.getStatusCode());
    }

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException
    {
        if ( (response.getStatusCode().series() == HttpStatus.Series.CLIENT_ERROR)
                || (response.getStatusCode().series() == HttpStatus.Series.SERVER_ERROR))
        {
            return true;
        }
        return false;
    }
}

But there is caveat with this error handler. If the server is down or not accessible, RestTemplate throws 'ResourceAccessException'. Internally RestTemplate encounters 'IOException' when server is not accessible. RestTemplate catches 'IOException' and throws 'ResourceAccessException'. In this process error handler doesn't  get invoked hence the custom exception will not be thrown.

So to avoid this situation I handled 'RestClientException' in code where RestTemplate was being invoked, and returned proper error message.

Related Posts:
Exception handeling for RESTful service

Exception handling for RESTful service in Spring framework

In last couple of posts we have seen how to create RESTful service using Spring framework. Here we will see how can we handle error conditions and return appropriate status code and message.


  • Use @ResponseStatus on custom exception

In case of error, throw custom exception annotate with @ResponseStatus. Code below shows how to define CustomException. 


@ResponseStatus(value = HttpStatus.SERVICE_UNAVAILABLE, reason = "The service is unavailable")
class CustomException extends RuntimeException{
 //...   
}


  • Return ResponseEntity<> with appropriate error code

ResponseEntity can be used as below.


@RestController
public class HelloController {
    @RequestMapping("/hello")
    public ResponseEntity sayHello(@RequestParam(value="name", required = false, defaultValue = "World") String name) {
        try {
            return new ResponseEntity<>(String.format("Hello %s with Spring Boot !!!", name), HttpStatus.OK);
        }catch (RuntimeException excp){
            //log error excp
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}


  • You also throw RuntimeException which will return with error code "Internal Server Error" always. 

Path variable with Spring Boot

In the last post "Query parameter handling with Spring Boot"  we have seen how to provide the query parameter . I will be using same project and extending HelloController for this.

For RESTful service to access specific resource via their Id/name we would also need path variable so that those can be accessed with specific path like "hello/{id}".

This can be achieved with @ PathVariable annotation. Replace the HelloController.java with below code.

package hello;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello/{id}")
    public String sayHello(@PathVariable("id") String id) {
        return  String.format("Hello world with Spring Boot !!! Id used here %s", id);
    }
}

Run the application and hit http://localhost:8080/hello/myId in your browser. You should get "Hello world with Spring Boot !!! Id used here myId" in return. 

Query parameter handling with Spring Boot

In last post, Hello World with Spring Boot we have seen how to create REST service with Spring Boot. Now we will extend the same HelloController to work on query parameters.

Here we will get the "name" as query parameter, and respond with updated message. Update HelloController.java file with below code. 

  
package hello;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String sayHello(@RequestParam(value="name") String name) {
        return  String.format("Hello %s with Spring Boot !!!", name);
    }
}

We have added @RequestParam annotation which will assign value of query parameter 'name' to variable name. Now run you application and hit "http://localhost:8080/hello?name=XYZ" on browser. You should get "Hello XYZ with Spring Boot !!!" in return.
But with this code the "http://localhost:8080/hello" URL will return error "bad request" as query parameter is missing. This is helpful when you want the query parameter as mandatory input.

In order to support optional query parter, you can have default value for parameters as below.
 
package hello;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String sayHello(@RequestParam(value="name", defaultValue="World") String name) {
        return  String.format("Hello %s with Spring Boot !!!", name);
    }
}

'defaultValue' allows the query parameter to be optional. Optional query parameters can be handled using 'required = false' as code below.  'defaultValue' will assign default value to variable 'name', if it's not specified value of 'name' would be null. 


@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String sayHello(@RequestParam(value="name", required = false, defaultValue = "World") String name) {
        return  String.format("Hello %s with Spring Boot !!!", name);
    }
}

Hello World REST Service with Spring boot

Recently I tried creating RESTful service with Spring Boot.  Its very easy to create RESTful service using Spring Boot, and also it removes lots of boilerplate code.

I will be walking through creating a simple hello world service. I have used Intellij Idea 15 and Java SDK 1.8, Maven 4.0.0 to build and run the project.

Lets start by creating a maven based project in Intellij. Specified required  SDK, groupId, artifactId and project name.

Now create a directory named "hello" under src->main->java.  Create a new Java class named HelloController (under directory 'hello'). Add below code to HelloController.Java

package hello;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String sayHello() {
        return "Hello World with Spring Boot !!!";
    }
}
Your hello REST controller is ready now.
Create Application.Java file under src->main->java->hello directory. Update Application.java with below code.

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

locate your pom.xml it should be under parent directory of project.
Update pom.xml with below dependencies.

    
        1.8
    

    
        org.springframework.boot
        spring-boot-starter-parent
        1.3.3.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

Now to run the application, create application run configuration. Select project and click on edit configuration (Under Run menu). Add new configuration for "Application", for Main class select hello.Application. Set the working directory as project root and OK.

Now run the application and go to your browser and hit "http://localhost:8080/hello"

You should see the service returns with "Hello World with Spring Boot!!!".

Reference : Rest-service with Spring

Error : java.lang.SecurityException: Can not initialize cryptographic mechanism

During certificate import using InstallCert.Java, I faced this issue. This can cause if you don't have required restriction policy file or the key size is greater than the once deployed by Java by default which is 128 bit. 

This can be solved by downloading the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files from Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files  and copying them in your JRE.

Error : unable to find valid certification path to requested target

I was trying to run Java application, which was using REST Template to implement rest client. The application was connecting to REST service (REST API's) over SSL. The certificate used for SSL was self signed certificate.

The self signed certificate was causing error "unable to find valid certification path to requested target" every time I tried to connect to REST Service. 

In order to resolve this error, I had to add the certificate to the JVM key store. I tried multiple steps, even corrupted the keystore but finally was able to run application successfully. 

You would need InstallCert.Java to successfully import the certificate which can be found at InstallCert.Java

Above git repo has ReadMe which details out all steps required for importing the certificate. 
If you happen to corrupt the keystore you can follow below link to restore it.

http://architecturalatrocities.com/post/19073788679/fixing-the-trustanchors-problem-when-running


Error: Cannot connect to the Docker daemon. Is the docker daemon running on this host?

If you are trying to start docker first time, you might get an error "Cannot connect to the Docker daemon. Is the docker daemon running on this host?"


This might happen because of multiple reasons.

1. You might not have permissions to to access docker
You should grant permission to use docker for specific user if he is not  root user.
In order to grant permission execute below command:

$ sudo usermod -aG docker <username>

replace <username> with actual user name. Also make sure you log off/restart machine before using docker, after executing above command.

2. Docker service might not be running

In order to re-start the docker service execute below commands

$ sudo service docker stop
$ sudo service docker start

Now you should be able to use docker.


Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...