Saturday, 29 October 2016

Getting started with angular 2

What is Angular2

Angular 2 is client side framework of the MV* design pattern. The framework is built on TypeScript, which is a superset of ECMAScript6.

Angular 2 came with almost everything you need to build a complicated frontend web or mobile apps, from powerful templates to fast rendering, data management, HTTP services, form handling and so much more......

Angular 2 applications written in TypeScript are compiled(transpiled) to JavaScript for run-time use. Angular 2 is not backwards compatible with Angular1 because it is the rewrite of the framework.

Why Upgrade to Angular 2

Angular 2 is not backwards compatible, so it poses the question, why should I switch to a new framework.

Well, Angular 2 provides several improvements over Agular 1.

A major improvement to the framework is reduced complexity. One example is the redesign of the change detection. Angular 2's change detection system will perform a depth-first search from the application root through the child binding. In angular 1, Angular digest makes multiple passes over bounded objects to identify and update changes before rendering. Benchmark tests indicate, Angular 2 significantly reduces the rendering time.

Another example of reduced complexity of Angular 2 is a number of built-in directives. In Angular1 there are over 70 built-in directives many of which are DOM wrappers. In Angular 2 the number of built-in directives is cut to 23, due to support for directly binding to DOM element properties and events.

A final example of reduced complexity is the adoption of a single standard for DI(Dependency Injection) and service creation. Now developer will not debate on five forms of service creation and multiple implementations of DI. In Angular 2, services will be implemented via classes while dependencies will be injected via constructor injection.

Besides reduced complexity, the framework gains advantage by being built on ECMAScript2015(ES6). The framework supports new structure such as classes and modules, similar to that in higher level languages. This enables the developer to encapsulate business concepts while increasing readability.

The framework also supports dynamic module loading, enable modules to be loaded via the dependency chain, thus eliminating the need to pre-load dependent JavaScript files via <script> tags.

Another enhancement to the framework is support for type declarations (via TypeScript). Also found in higher level language, typing enables developers to detect defects earlier in the development process.

Components
In Angular 2, components are the main way we build and specify elements and logic on the page. In Angular1 we achieved this through directives, controller and scopes.
A component is an encapsulation of business logic and template markup associated with custom HTML tags.

Simple example of Component

Here is simple Angular 2 Component that renders our name.

import { Component} from '@angular/core;
@Component({
  selector: 'my-component',
  template: 'Hello my name is {{name}}.'

})

export class MyComponent {
  constructor() {
    this.name = 'Giridhar'
  }
}

When we use the tag <my-component></my-component>  in our HTML, this component will be created, our constructor called and rendered.

You can find the code at GitHub.

Next, I would be writing blog on how to create form and validate it, so stay tuned.....





Monday, 22 June 2015

Custom Exception Handling Using ResposneEntityExceptionHandler in Java, Spring:

Sometime Java developers need to create custom exceptions, i.e. Exceptions which are not defined in JDK. Spring provides a exception handler class which help us  to handle custom exceptions gracefully.

Here is  complete code example of creating custom or user defined exception in Java. In this example I created UserNotFoundException  and  RestResponseEntityExceptionHandler class.


Steps for handling Custom Exception:

1. Create Custom Java Class which will inherit Exception Class

public class UserNotFoundException extends Exception {

  private static final String DEFAULT_MESSAGE = "User not found!";

  public UserNotFoundException() {
    super(DEFAULT_MESSAGE);
  }

  public UserNotFoundException(String message) {
    super(message);
  }
}

2. Create Exception Handler Java Class

 /**
   * REST  exception handlers defined at a global level for the application
   *
   **/
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(value = {UserNotFoundException.class})
  protected ResponseEntity<RestResponse> handleUserNotFound(UserNotFoundException ex, WebRequest request) {
    return handleException(ex.getMessage(), HttpStatus.FORBIDDEN);
  }

  private ResponseEntity<RestResponse> handleException(String message, HttpStatus status) {
    LOGGER.error(message);
    return new ResponseEntity<RestResponse>(new RestResponse(Boolean.FALSE, ImmutableList.of(message), null), status);
  }
}

ResponseEntityExceptionHandler: A class that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods.

This  class provides an @ExceptionHandler for handling standard Spring MVC exceptions that returns a ResponseEntity.

 @ControllerAdvice: A class annotated with it will act as global handler class for all controllers. It is used to define @ExceptionHandler methods that apply to all @RequestMapping methods.

3. Create service which will throw UserNotFoundException.class if user doesn't found in the DB.

public interface UserService {

  User findByEmailId(String emailId) throws UserNotFoundException;

}


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;


    @Override
    public User findByEmailId(String emailId) throws UserNotFoundException {

        if ((emailId == null) || (emailId == "")) {
            throw new IllegalArgumentException("userId not found ");
        }
        User user = userRepository.findByEmail(emailId);
        if (user == null) {

            throw new UserNotFoundException();
        }

        return user;
    }
}

4. Create Controller which will call service method


@Controller
@RequestMapping(value = "/user")
public class UserController {

  @Autowired
  private UserService userService;

 @RequestMapping(value = "/findby-email", method = RequestMethod.POST)
 @ResponseBody

    public ResponseEntity<RestResponse> findByEMail(@RequestParam String email) throws       UserNotFoundException {

        return new ResponseEntity<RestResponse>(new RestResponse(Boolean.TRUE, "Succesfully Logged In!", userService.findByEmailId(email)), HttpStatus.OK);
    }
}

For complete running application refer Github Repository

Keywords: GloabalExcetionHandling, SpringMVC, ResponseEntityExceptionHandler@ControllerAdvice, REST