Wednesday, 21 November 2018

 Java 7 features

1)Strings in Switch:

public void testStringInSwitch(String param){
       final String JAVA5 = "Java 5";
       final String JAVA6 = "Java 6";
       final String JAVA7 = "Java 7";
       switch (param) {
           case JAVA5:
               System.out.println(JAVA5);
               break;
           case JAVA6:
               System.out.println(JAVA6);
               break;
           case JAVA7:
               System.out.println(JAVA7);
               break;
       }
   }

2)Binary Literals:

public void testBinaryIntegralLiterals(){
        int binary = 0b1000; //2^3 = 8
        if (binary == 8){
            System.out.println(true);
        } else{
            System.out.println(false);
        }
}

3)Underscore Between Literals:

public void testUnderscoresNumericLiterals() {
    int oneMillion_ = 1_000_000; //new
    int oneMillion = 1000000;
    if (oneMillion_ == oneMillion){
        System.out.println(true);
    } else{
        System.out.println(false);
    }
}

4)Type Inference for Generic Instance:

List<String> l = new ArrayList<>();
l.add("A");
l.addAll(new ArrayList<>());

5)Multiple exception catching:

public void testMultiCatch(){
    try {
        throw new FileNotFoundException("FileNotFoundException");
    } catch (FileNotFoundException | IOException fnfo) {
        fnfo.printStackTrace();
    }
}

Java 8 features

1)forEach() method in Iterable interface

Whenever we need to traverse through a Collection, we need to create an Iterator whose whole purpose is to iterate over and then we have business logic in a loop for each of the elements in the Collection. We might get ConcurrentModificationException if iterator is not used properly.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
import java.lang.Integer;

public class Java8ForEachExample {

public static void main(String[] args) {

//creating sample Collection
List<Integer> myList = new ArrayList<Integer>();
for(int i=0; i<10; i++) myList.add(i);

//traversing using Iterator
Iterator<Integer> it = myList.iterator();
while(it.hasNext()){
Integer i = it.next();
System.out.println("Iterator Value::"+i);
}

//traversing through forEach method of Iterable with anonymous class
myList.forEach(new Consumer<Integer>() {

public void accept(Integer t) {
System.out.println("forEach anonymous class Value::"+t);
}

});

//traversing with Consumer interface implementation
MyConsumer action = new MyConsumer();
myList.forEach(action);

}

}

//Consumer implementation that can be reused
class MyConsumer implements Consumer<Integer>{

public void accept(Integer t) {
System.out.println("Consumer impl Value::"+t);
}


}

2)default and static methods in Interfaces
3)Functional Interfaces and Lambda Expressions

Functional interfaces are new concept introduced in Java 8. An interface with exactly one abstract method becomes Functional Interface. We don’t need to use @FunctionalInterface annotation to mark an interface as Functional Interface.
One of the major benefits of functional interface is the possibility to use lambda expressions to instantiate them. We can instantiate an interface with anonymous class but the code looks bulky.
Runnable r = new Runnable(){
@Override
public void run() {
System.out.println("My Runnable");
}};
(or)
Runnable r1 = () -> {
System.out.println("My Runnable");
};

4)Java Stream API for Bulk Data Operations on Collections

A new java.util.stream has been added in Java 8 to perform filter/map/reduce like operations with the collection. Stream API will allow sequential as well as parallel execution.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class StreamExample {

public static void main(String[] args) {

List<Integer> myList = new ArrayList<>();
for(int i=0; i<100; i++) myList.add(i);

//sequential stream
Stream<Integer> sequentialStream = myList.stream();

//parallel stream
Stream<Integer> parallelStream = myList.parallelStream();

//using lambda with Stream API, filter example
Stream<Integer> highNums = parallelStream.filter(p -> p > 90);
//using lambda in forEach
highNums.forEach(p -> System.out.println("High Nums parallel="+p));

Stream<Integer> highNumsSeq = sequentialStream.filter(p -> p > 90);
highNumsSeq.forEach(p -> System.out.println("High Nums sequential="+p));

}

}

5)Java Time API

Java Time API has some sub-packages java.time.format that provides classes to print and parse dates and times and
java.time.zone provides support for time-zones and their rules.

package com.shris.java8.time;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateParseFormatExample {

public static void main(String[] args) {

//Format examples
LocalDate date = LocalDate.now();
//default format
System.out.println("Default format of LocalDate="+date);
//specific format
System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));


LocalDateTime dateTime = LocalDateTime.now();
//default format
System.out.println("Default format of LocalDateTime="+dateTime);
//specific format
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu                                                                   HH::mm::ss")));
System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));

Instant timestamp = Instant.now();
//default format
System.out.println("Default format of Instant="+timestamp);

//Parse examples
LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48",
DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"));
System.out.println("Default format after parsing = "+dt);
}

}

The new Time API prefers enums over integer constants for months and days of the week. One of the useful class is DateTimeFormatter for converting datetime objects to strings.

6)Collection API improvements

We have already seen forEach() method and Stream API for collections. Some new methods added in Collection API are:

Iterator default method forEachRemaining(Consumer action) to perform the given action for each remaining element until all elements have been processed or the action throws an exception.
Collection default method removeIf(Predicate filter) to remove all of the elements of this collection that satisfy the given predicate.
Collection spliterator() method returning Spliterator instance that can be used to traverse elements sequentially or parallel.
Map replaceAll(), compute(), merge() methods.
Performance Improvement for HashMap class with Key Collisions

7)Concurrency API improvements

Some important concurrent API enhancements are:

ConcurrentHashMap compute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce() and search() methods.
CompletableFuture that may be explicitly completed (setting its value and status).
Executors newWorkStealingPool() method to create a work-stealing thread pool using all available processors as its target parallelism level.

8)Java IO improvements

Some IO improvements known to me are:

Files.list(Path dir) that returns a lazily populated Stream, the elements of which are the entries in the directory.
Files.lines(Path path) that reads all lines from a file as a Stream.
Files.find() that returns a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file.
BufferedReader.lines() that return a Stream, the elements of which are lines read from this BufferedReader.

Sunday, 11 November 2018

Angular Framework 20

1. Angular Framework

Angular is a TypeScript-based open-source front-end framework maintained by Google. It helps developers build scalable single-page applications (SPAs) with two-way data binding, dependency injection, routing, and modular architecture. Angular follows MVC-like patterns and provides reusable components and services.


2. Angular Modules

Definition:
Modules are containers that group related components, directives, services, and pipes. Every Angular app has a root module (AppModule) and can have multiple feature modules for modularity. They improve maintainability and lazy loading.

Example (app.module.ts):

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { CourseCardComponent } from './course-card/course-card.component'; @NgModule({ declarations: [AppComponent, CourseCardComponent], imports: [BrowserModule], bootstrap: [AppComponent] }) export class AppModule {}

3. Components

Definition:
Components are building blocks of Angular apps. They control a part of the UI using HTML templates, CSS styles, and TypeScript logic. Each component is associated with a selector used in HTML.

Example (course-card.component.ts):

import { Component } from '@angular/core'; @Component({ selector: 'app-course-card', templateUrl: './course-card.component.html', styleUrls: ['./course-card.component.css'] }) export class CourseCardComponent { title = "Angular Basics"; }

4. Services

Definition:
Services hold business logic and data retrieval logic. They are reusable across components and injected via Angular’s Dependency Injection (DI) system.

Example (courses.service.ts):

import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CoursesService { getCourses() { return ['Angular', 'React', 'Vue']; } }

5. Templates

Definition:
Templates define the view (UI) of a component using HTML and Angular syntax like interpolation ({{ }}), property binding, event binding, and structural directives.

Example (course-card.component.html):

<h2>{{ title }}</h2> <button (click)="enroll()">Enroll</button>

6. Pipes

Definition:
Pipes transform data before displaying it in templates. Angular provides built-in pipes like date, currency, uppercase, and we can create custom pipes.

Example:

<p>{{ today | date:'fullDate' }}</p>

Custom Pipe (truncate.pipe.ts):

import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'truncate' }) export class TruncatePipe implements PipeTransform { transform(value: string, limit = 10): string { return value.length > limit ? value.substring(0, limit) + '...' : value; } }

7. Routing

Definition:
Routing allows navigation between different views (components) without reloading the page. It defines paths mapped to components.

Example (app-routing.module.ts):

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { CourseCardComponent } from './course-card/course-card.component'; const routes: Routes = [ { path: 'courses', component: CourseCardComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {}

8. Directives

Definition:
Directives are instructions in the DOM that add behavior to elements.

  • Structural Directives: Change DOM structure (*ngIf, *ngFor).

  • Attribute Directives: Change DOM appearance/behavior (ngStyle, ngClass).

  • Custom Directives: Developer-defined logic.

Example – Built-in:

<p *ngIf="isVisible">Visible Content</p> <li *ngFor="let course of courses">{{ course }}</li>
Structural Directives (change DOM layout)
  1. *ngIf – Conditionally include/exclude elements.

  2. *ngFor – Loop over arrays.

  3. *ngSwitch, *ngSwitchCase, *ngSwitchDefault – Switch-case rendering.

<div *ngIf="isLoggedIn">Welcome!</div> <ul> <li *ngFor="let course of courses">{{ course }}</li> </ul> <div [ngSwitch]="role"> <p *ngSwitchCase="'admin'">Admin Panel</p> <p *ngSwitchDefault>User Panel</p> </div>

Attribute Directives (modify appearance/behavior)

  1. ngClass – Apply classes dynamically.

  2. ngStyle – Apply styles dynamically.

  3. [(ngModel)] – Two-way data binding.

<p [ngClass]="{active: isActive}">Dynamic Class</p> <p [ngStyle]="{'color': isActive ? 'green' : 'red'}">Dynamic Style</p> <input [(ngModel)]="username">

Custom Directive Example

@Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef, private renderer: Renderer2) {} @HostListener('mouseenter') onEnter() { this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'lightblue'); } @HostListener('mouseleave') onLeave() { this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor'); } }

9. Decorators in Angular

Definition:
Decorators add metadata to classes, properties, and methods. They tell Angular how to process a class or element.

1. @NgModule

  • Defines a module that bundles components, directives, pipes, and services.

  • Every Angular app has a root module (AppModule).

  • Helps organize the application into functional blocks.

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], // components, directives, pipes imports: [BrowserModule], // other modules providers: [], // services bootstrap: [AppComponent] // root component }) export class AppModule {}

2. @Component

  • Declares a component (UI + logic).

  • Connects HTML template, CSS styles, and TypeScript logic.

import { Component } from '@angular/core'; @Component({ selector: 'app-hello', template: `<h1>Hello {{name}}</h1>`, styles: ['h1 { color: blue; }'] }) export class HelloComponent { name = 'Angular'; }

3. @Injectable

  • Declares a service available for Dependency Injection.

  • Ensures the class can be injected into components or other services.

import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' // singleton service }) export class CourseService { getCourses() { return ['Angular', 'Spring Boot', 'AWS']; } }

4. @Directive

  • Creates a custom directive (structural or attribute).

import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appRedText]' }) export class RedTextDirective { constructor(el: ElementRef) { el.nativeElement.style.color = 'red'; } }

5. @Pipe

  • Defines a custom pipe to transform data.

import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'capitalize' }) export class CapitalizePipe implements PipeTransform { transform(value: string): string { return value.charAt(0).toUpperCase() + value.slice(1); } }

6. @Input / @Output

  • @Input → Pass data from parent to child component.

  • @Output → Send events from child to parent.

// child.component.ts @Input() title!: string; @Output() clicked = new EventEmitter<string>(); onClick() { this.clicked.emit(this.title); }

7. @HostListener / @HostBinding

  • @HostListener → Listen to DOM events.

  • @HostBinding → Bind properties to host element.

@Directive({ selector: '[appHover]' }) export class HoverDirective { @HostBinding('style.backgroundColor') bgColor = 'transparent'; @HostListener('mouseenter') onMouseEnter() { this.bgColor = 'yellow'; } @HostListener('mouseleave') onMouseLeave() { this.bgColor = 'transparent'; } }

8. @ViewChild / @ViewChildren

  • Access template DOM elements or child components.

@ViewChild('myInput') inputRef!: ElementRef; ngAfterViewInit() { console.log(this.inputRef.nativeElement.value); }

9. @ContentChild / @ContentChildren

  • Access projected content inside <ng-content>.

@ContentChild('projected') projected!: ElementRef;

10. Dependency Injection Decorators

  • @Optional → Service may or may not exist.

  • @Self → Look only in current injector.

  • @SkipSelf → Look in parent injector.

  • @Host → Look in host component injector.

Common Angular Decorators:

  • @Component → Defines a component.

  • @NgModule → Defines a module.

  • @Injectable → Marks a service for DI.

  • @Directive → Defines a custom directive.

  • @Pipe → Defines a custom pipe.

  • @Input → Pass data from parent → child.

  • @Output → Emit events child → parent.

  • @HostListener → Listen to DOM events.

  • @ViewChild / @ViewChildren → Access child elements/components.

Example (Input/Output):

@Component({ selector: 'app-child', template: `<button (click)="notify()">Notify Parent</button>` }) export class ChildComponent { @Output() notifyEvent = new EventEmitter<string>(); notify() { this.notifyEvent.emit("Hello Parent!"); } }

10. Project Architecture (src/app folder)

src/ └── app/ ├── app.module.ts ├── app.component.ts / .html / .css ├── course-card/ │ ├── course-card.component.ts / .html / .css ├── services/ │ └── courses.service.ts ├── directives/ │ └── highlighted.directive.ts ├── pipes/ │ └── truncate.pipe.ts ├── models/ │ └── course.ts └── app-routing.module.ts

11. Angular Architecture Flow (Diagram – textual form)

Modules → Components → Templates ↘ Services → Models Templates → Directives & Pipes → DOM

12. MVC Mapping in Angular

  • Model: Data models (Course class), services (CourseService).

  • View: Templates (.html), directives, and pipes controlling UI.

  • Controller: Components (.ts) act as controllers connecting Model & View.

MVC Diagram (textual form):

Model (Services + Data) ↔ Component (Controller) ↔ View (Templates + Directives + Pipes)

Some Angular CLI Commands

# Install Angular CLI npm install -g @angular/cli # Create new Angular project ng new angular-course

# To start application npm start (or) ng serve # Generate a component ng generate component course-card # Generate Angular control flow (structural directive block) ng generate @angular/core:control-flow # Generate custom directives ng g directive directives/highlighted ng g directive directives/ngx-unless # Generate a service ng g service services/courses # Generate standalone component ng generate @angular/core:standalone