Monday, 12 December 2016

Design pattern Basics

What is Design Pattern?
These are well proved solutions to any specific problem/task.

Eg. 
Suppose you want to create a class for which only a single instance (or object) should be created and that single object can be used by all other classes.
Ans -Singleton Design Pattern

Advantages -
1.Reusable
2.Define System Architecture 
3.Better System
4.Easy to scale and maintain app 

When to use Design Pattern?
During the analysis and requirement phase of SDLC(Software Development Life Cycle). 

Classification -
1.Core Java Design Pattern 
2.J2EE Design Pattern

A.Core Java Design Patterns-
1.Creational Design Pattern -
  
Singleton Design Pattern -
It defines a class that has only one instance and provide global access to it.
It has two types -
1.Early Initialization  - Instance creation when class is loaded
2.Lazy Initialization - Instance creation when required(on calling getInstance())

How to create?
Private & Static variable - To get memory once.
Private Constructor -  To prevent instance creation from outside class
Static Factory Method - For global access to user to the Singleton Object

With Early Initialization
With lazy Initialization
 Above eg. Singleton is A class

Significance Of Classloader in Singleton -
If singleton is loaded by two classloader then 2 instances of Singleton will be created.
Each singleton instance per each Classloader.


Significance Of Serialization in Singleton -
We can serialize and deserialize Singleton instance.
But on deserializing it will not return Singleton object.

Solution -
Override readResolve() to enforce to give Singleton Object.

Singleton Real Life Example  from JDK -
1.Runtime (java.lang.Runtime). There is only one Runtime instance for Java Application.
2.Toolkit (java.awt.Toolkit)
3.Desktop (java.awt.Desktop)

Which class can be made Singleton ?
The class which can be available for whole application and only one instance is available throughout application.
Eg.
Real Life example could be  GUI Popup.
We can make sure that at a time only one popup is available on the screen.  
 

Factory Method Pattern -
It defines an Interface or Abstract class to create object but let sub-classes decide which  class to be instantiated.
In short, subclasses are responsible for creation on object.
 
Advantages -
1.It let subclasses choose which object to create
2.It promotes loose-coupling by eliminating the need to bind classes into code.
It means code interacts with Interface or Abstract Classes.

Eg.Electricity Bill Calculation
http://www.javatpoint.com/factory-method-design-pattern 

Prototype Design Pattern -
It helps in cloning of existing object instead of creating new one.
And new cloned object can be customized as per requirement.

When to use?
When price of creating object using new keyword is expensive.

Advantages -
1.Hides complexities for creating new object.
2.You can add or remove object at runtime.

Eg.Employee Record
http://www.javatpoint.com/prototype-design-pattern


Proxy Design Pattern -
Proxy means object representing another object.
It provides control over access of original object. 

Advantage-
It protects original object from outside world.

When to use-
Protective proxy server

Eg.Proxy Internet Access
http://www.javatpoint.com/proxy-pattern







 
 

Saturday, 10 December 2016

How to create angularJs 2 project using angular-cli

Prerequisite -
Install nodejs and npm

1.Install angular-cli
npm install -g angular-cli

2.Create new Project using  angular-cli
ng new ProjectName
It will angular project skeleton with all config files such as tsconfig.json, typings.json and package.json,
 
3. cd to new Project 
cd  ProjectName

4. run created app
ng nerve

Now , This project will be setup using Webpack bundle.
You can see Webpack bundle is valid as successful message.

Now,
http://localhost:4200  to load app component.

Issues -
Experimental-decorators warnings in AppComponent and other Components.
This is due to typescript version mismatch.
TS build uses v1.8.10 and tsconfig(ts compiler) uses v2.0.0

Hence we correct this conflict  in setting.json file.
We set node Module ts version for ts compiler to avoid conflict.
add below property -
"typescript.tsdk": "./node_modules/typescript/lib"



Friday, 9 December 2016

How to create angularJs2 Project

Main Configuration Files -

1. tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}

2. typings.json
{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160317120654",
    "jasmine": "registry:dt/jasmine#2.2.0+20160505161446",
    "node": "registry:dt/node#4.0.0+20160509154515"
  }
}


3. package.json 
{
  "name": "angular2-Sample",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common":  "2.0.0-rc.1",
    "@angular/compiler":  "2.0.0-rc.1",
    "@angular/core":  "2.0.0-rc.1",
    "@angular/http":  "2.0.0-rc.1",
    "@angular/platform-browser":  "2.0.0-rc.1",
    "@angular/platform-browser-dynamic":  "2.0.0-rc.1",
    "@angular/router":"3.0.0-alpha.7",
    "@angular/router-deprecated":  "2.0.0-rc.1",
    "@angular/upgrade":  "2.0.0-rc.1",
    "systemjs": "0.19.27",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "angular2-in-memory-web-api": "0.0.10",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings":"^1.0.4"
  }
} 


4. systemjs.config.js

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Add package entries for angular packages
  ngPackageNames.forEach(function(pkgName) {
     //Router has no "bundel" folder
    if (pkgName == "router"){
       packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
    }else{
    packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
    }
  });
  var config = {
    map: map,
    packages: packages
  }
  System.config(config);
})(this); 


5. index.html

<!DOCTYPE html>
<html>
    <head>
        <!-- 1.For HTML 5 Browser PushStart  -->
        <base href=".">
        <!-- 2.Add Default Css at project root -->
        <link  rel="stylesheet"  href="base.css">
         <!-- 3.Load Polyfill(s) for older browsers -->
        <script src="node_modules/core-js/client/shim.min.js"></script>
        <script src="node_modules/zone.js/dist/zone.js"></script>
        <script src="node_modules/reflect-metadata/Reflect.js"></script>
        <script src="node_modules/systemjs/dist/system.src.js"></script>
        <!-- 4.Add Configure SystemJS -->
        <script src="systemjs.config.js"></script>
        <script>
          System.import('app').catch(function(err){ console.error(err); });
        </script>
    </head>
   <body>
       <!-- 5. Main Container to hold view -->
       <myApp>Hello Ang2-startup</myApp>
   </body>
</html> 


6.typings folder 
It contains global dependencies like core-js, jasmine, node inside globals folder.  

 7.app folder

Note*- All folders must be kept in root 

 

Saturday, 3 December 2016

AJAX Basics

AJAX is Asynchronous JavaScript and Xml

AJAX allows you to send and receive data asynchronously without reloading the web page. So it is fast.
           AJAX allows you to send only important information to the server not the entire page.
So only valuable data from the client side is routed to the server side. It makes your application interactive and faster.

Why used (advantages)-
1.User is not blocked
2.Faster

What is XmlHttpResuest  ?
This Object is used to communicate between client and server.

Main Functions -
1. sends data from client in the background
2. receives data from server
3. updates webpage with new data without reloading it.


XmlHttpRequest Properties - 
readyState - State of request
                   0 - un-opened
                   1 - opened but send() not called
                   2 - send() called
                   3 - downloading data and responseText holds data
                   4 - request completed fully (response ready)

responseText -   returns response as Text
responseXML - returns response as XML

              
XmlHttpRequest Methods - 
1 .void open(method,URL,sync)  
                method - get or post  
                Url - url to be hit
                Sync - synchronous or asynchronous call

2. send(String) 
                 With String - post request
                 Without String - get request 

When is response received ?  
request.readyState == 4 

How to connect with DB ?
Use Scriplate Tag  <% %> to connect with Db and fire query.

link --> http://www.javatpoint.com/ajax-example-with-database
 

Why not to use(Disadvantage) -
1. makes jsp's complex by using a lot of script code.
    Eg.
   In case of database interaction.
2. difficult debugging
3. security issues  (AJAX source code is readable and also scripts can be changed)         
                

How to call AJAX using jQuery:
1.$.get(url,data,callback(result));
   $.post(url,data,callback(result));

2.$.ajax(url.data).done(callback(result))
 


HTML 5 Basics

New Features in Html 5 -

1.<audio>           -To play audio file directly.
2.<canvas>         -To draw graphics/canvas.
3.<article>          -To display document/article/magazine
4.<video>           -To play video file directly.
5.<svg>               -To display shapes
6.<nav>               -To show navigation link
7.<section>          -To define section in document.
8.<Footer>           -To define section inside a footer.
9.<Header>          -To define header inside Section
10.<dialog>          -To show window/dialog directly
11.<progress>       -To show progress bar.

12. Local Storage - Alternative to Cookies. 

All above is shown inside DOM document .

What is <!DOCTYPE html>  ?
It is mandatory to convey browser t. hat this is HTML 5 document.
If <!DOCTYPE html> is not mentioned, will not make HTML 5 tags function properly. Im[

Validation  Update -
1.required field is used in input tags for form validation.
Eg.     Name: <input type="text" name="name" required>

2. new <input> type -> email
Eg.    <input type="email">

What is Local Storage ?
Its an alternative to Browser Cookies.
           With local Storage, Web application can store data locally within user's Browser.
Before HTML5, application data had to be stored in cookies, included in every server request.

Advantages -
1.More secure than cookies.
Because Cookies is sent with all the future HTTP request to the server,
But Local-storage data resides with browser only.It is never sent to Server with HTTP request. 

2.Hold more data than cookies(upto 4KB) without compromising web application performance.(> 5 MB)
Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.


Local Storage is Global Object.
It can be accessed as below -
window.localStorage 
 
 

jQuery Basics

jQuery is small, light-weight,fast javaScript library.

 Application -
1. Html manipulation
2. Dom manipulation
3. Css manipulation
4. Html Animation
5. Ajax calling
6. Json parsing 
7. Handling Html events 

How to use - 
1. can be used in .js file or <script> tag inside HTML page
2. use jquery.min.js file or absolute url http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js

$(document).ready()   vs  Window.onload() -
$(document).ready()  is as same as $() 

           $() is jQuery event and called before Window.onload().$() gets called as soon as the DOM is ready (which means that the browser has parsed the HTML and built the DOM tree). This allows you to run code as soon as the document is ready to be manipulated.  
            Window.onload() is javaScript event.It called when complete (DOM + images+ frame )is loaded.
Also,$() can be called any number of time but Window.onload() can be called only once.
$() cannot access images and frames .Window.onload() can be used to access the same.

jQuery Selector -
1.By element  -     $(" element ")
2.By element Id -  $(" #id ")
3.By Class -          $(".className")

jQuery Effects -
Display effects - hide()   - hide selected elements
                            show()  - display selected elements
                            toggle() - switches between Hide() and Show()
Sliding effect -    slideDown() - shows element with sliding down.
                            slideUp() - shows element with sliding up.
                            slideToggle() - switches between slideUp() and slideDown()

animate()
delay() - delay showing of element.



 
 


 

Sunday, 20 November 2016

AngularJS2

Basics -
I. AngularJS2 is framework to build heavy javaScript applications.
It is mainly used to create SPA(Single Page Application.)
AngularJS2 is completely independent of AngularJS framework.

SPA vs MPA (Multi Page Application)
In multi page app each time a request is submitted a new page is served by the server and rendered.
This approach is OK for simple applications.
           But in case of rich use interface page becomes complex and to be loaded with a lot of  data.
Generating complex pages on server and transferring them to client over internet and rendering them in browser takes time and degrades user experience.
           Introduction of AJAX  improved MPA by refreshing a part of page( not full page) but increased page complexity.
SPA is a evolution of MPA+AJAX pattern,where only shell page is generated on the server and  UI is rendered by browser javaScript Code. SPA requests markup (HTML) and data separately and renders page directly in browser. 
In SPA only a part of shell page changes instead whole page.
eg. Gmail is SPA


SPA Advantages :
1.Faster page loading
2.Improved user interface because data is loaded in the background from server.
3.No need to write code to render page on server.
4.decoupling of Front end and Back end Development
5.can use same back end code(Web development) for Mobile development.

SPA Disadvantages :
1.Heavy frameworks to be loaded in browsers
2.UI code is not compiled hence its harder to debug.
3.search engine optimization problems

II. Typescript is used to develop angularJS2 app.
     TypeScript is a super set of javaScript. (Any valid JavaScript code is TypeScript code).
     TypeScript = JavaScript + additional Features
      
    Why to use TypeScript instead of JavaScript?
     These additional features are --> (modules,classes,interfaces,access  modifiers, intellisense, compile Time checking)

III.Ang2 Architecture -
    Main parts of  ng2 are -
    1.Component  - View Part
    2.Directive
    3.Router
    4.Service       -Service Part
 Component - {} encapsulates template,data and behavior (properties and methods) of view. (Is a class)
Main Component is called as Root Component.
Root Component has many sub components which help to divide app into smaller parts.
Components are completely decoupled from DOM .
In JavaScript we first select DOM element and then modify it.
In Ang2 we bind DOM element with component.
    Eg. component class variable - DOM element
          Component class method - DOM event  

Service - {} A class, which holds non-view logic like Business logic, Data Access , Logging  etc.
Router -  {} For navigarion
Directive -{} which  modifies DOM (like Component)
Unlike Component, it does not have html markup for view.