Saturday, 30 July 2016

jQuery (Write Less, Do More)

  • Its an open source, lightweight java script library
  • Write Less, Do More is official tag line of jQuery, which is accruate and excellent description of jQuery.
  • It is a collection of reusable code that handles the most common and most tedious tasks smoothly and easily.
    • HTML document manipulation and   traversing
    • Browser event handling
    • AJAX interactions
    • Cross-Browser java script development
    • Extensive plugin library available
    • Great community support
Basic Syntax:
  • $(selector).action();
    • $("button").click(function() {...});  // selecting the required elements upon which 
  • $(document).ready()  or $();
different selectors in jQuery
  •     $("*") -All selector - It selects all the html elements including body element
  •     $("p") -Tag selector - All paragraph elements are slected
  •     $("button, p") - multiple selector
  •     $("#btnFirst") - ID selector
  •     $(".btnclass") - class selector
  •     $(this) - the current element
Attribute based selectors
  •     $("[class]") - All the elements that have class attribute
  •     $("[id=firstDiv]") - Elements that have id attribute as firstDiv value
  •     $("[id^=firstDiv]") - Elements that have id attribute starts with firstDiv
  •     $("[id$=firstDiv]") - Elements that have id attribute ends with firstDiv
  •     $("[id*=first]") - Elements that contains value first in attribute value
  •     $("[id|=first]") - Attribute value is first OR starts with first-
  •     $("[id~=first]") - Attribute value is first OR starts with first
Position based selectors: first, last, odd, even
  •     $("p:first") - First paragraph
  •     $("p:eq(3)") - 3rd element is selected  //lt & gt also can be used
Relation based selectors:
  •     $("p:first-child") - paragraphs which are first-child of its parent
p:firstchild - All paragraphs which are first child of its parent
span:lastchild - Span that is last child of its parent


$("span:nth-child(2)).hide(2000) - span that is 2nd child of its parent
$("span:nth-last-child(2)).hide(2000) - span that is 2nd child from the last for a parent

$("p:first-of-type")  - First paragraph of its parent
$("p:nth-of-type(2)")  - First paragraph of its parent

$("p:only-child") - paragraph which is only child of element
$("p:only-of-type") - Element which is only paragraph type child of element

Child and sibling selectors:
_________________________
Child Selectors
    Direct child selector -
    $("div>span") - Span elements that are direct child of div
    $("div span") - Span elements that are direct/indirect child of div
    Descendent selector
Sibling selectors

    Adjacent sibling selector
    $("p+span") - Span elements that are adjacent(sibling) to P element
    General sibling selector
    $("p~span") - All the span elements that are sibling of P element


Form based selectors
    $(":input")- All input type elements
    $(":text")- All input type TEXT elements
    $(":password")-
    $(":input")- All input type elements

State based selectors
    $(":hidden").show(2000) - show all hide
    $(":visible").hide(2000) -
    Similarly :enabled, :disabled, :selected, :checked, :animated

Content based selectors:
   
    $(":contains(First)") - All elements that contain First
    $("span:has(div)") - All span elements that has div as child
    $(":empty") - Element that doesn't have a child or a Text node
    $(":parent") - Elements that have either child or a text node
    $(":not(:parent)")

Events
    Any action that happens on web page can be considered as Event.
Types of Events:
    System initiated event
    User initiated event
Mouse Events:
    $("#box").click(), $("#box").dblclick()
    $("#box").mouseenter(), $("#box").mouseleave()
    $("#box").hover(),
    $("#box").mousedown(), $("#box").mouseup()

Keyboard events:
    $("#txt").keydown(),     $("#txt").keyup(),
    $("#txt").keydown(),     $("#txt").keyup(),
    $("#txt").keydown(),     $("#txt").keyup(),
    $("#txt").keydown(),     $("#txt").keyup(),

Form events:
    $(":text").focus(),     $(":text").blur()
    $(":text").focusin(),     $(":text").focusout() //when either element or its child gets focus
    $("form").submit()

Wednesday, 27 July 2016

Ajax

  • Asynchronous Javascript and XML
  • Primary use is to update small section of webpage without reloading entire page eg: search box
How it works:
  • Browser sends request to the server with out changing the page
  • The server will receive the page and send the processed results to client browser
  • The client browser receives the results and presents to user.

Object XMLHttpRequest is used to interact with server. It is used to send the request to server as well as to receive response from the server

Following are the properties and methods of XMLHttpRequest
  •  readyState: it is used to determine the current status of the request
  • status: it specifies if request was successful or not
    • 200: OK i.e request was successful
    • 404: page was not found   
  • Onreadystatechange: This is an event handler where a call back function can be registered. It holds a function which runs(called/invoked) everytime the value of readyState changes(it will get called 4 times for a successful ajax call)
  • open(method, server url, asynchronous) : used to specify the connection parameters. method is the type of method(GET/POST), asynchrounous is to tell weather it is synchronous or asynchronous call
  • send(): send() for GET Method or send(data) for POST method
  • In case of Post request, contentType header has to be set on the header. This indicates how the request body is encoded. Browsers always encode post data as application-x-www-form-urlencoded

     setRequestHeader("Content-type", "application/x-www-form-urlencoded");



Sunday, 24 July 2016

Knockout JS

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js "></script>
</head>
<body>
    <h2>This is a heading</h2>
    <p>This is <span data-bind="text: para1" </span></p>
    <p>This is another para2.</p>

    <script>
            var myViewModel={
                para1: 'Paragraph1',
                para2: 'Paragraph2'
            };
        ko.applyBindings(myViewModel);
    </script>

</body>
</html>

Using JQuery document ready function:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js "></script>
   
    <script>
        $(function(){
            var myViewModel={
                para1: 'Paragraph1',
                para2: 'Paragraph2'
            };
        ko.applyBindings(myViewModel);
        });
    </script>
   
</head>
<body>
    <h2>This is a heading</h2>
    <p>This is <span data-bind="text: para1" </span></p>
    <p>This is another para2.</p>

</body>
</html>

We can make the viewModel available to specific section of document by passing id
        ko.applyBindings(myViewModel, document.getElementById('p1'));

MVVM design pattern - View and Model are separated by ViewModel so that they are not dependent on each other. Also, it is a two way binding between view and ViewModel.


<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js "></script>
   
    <script>
        $(function(){
            var data={
                Para1: 'Paragraph1',
                Para2: 'Paragraph2'
            }

            var myViewModel={
                para1: ko.observable(data.Para1),
                para2: ko.observable(data.Para2)
            };
        ko.applyBindings(myViewModel);
        });
    </script>
   
</head>
<body>
    <h2>This is a heading</h2>
    <p id="p1">This is <span data-bind="text: para1" </span></p>
    <p>This is another para2.</p>



</body>
</html>

Observable: If a property is marked observable, the target changes when source changes and source changes when target value is changed.

Templates
  • Define Script tag of type text/html. Add html elements along with data bind
  • Body
    • <div data-bind: "template: {name:'mytemplate',data: <js var>}">  </div>
    • <div data-bind: "template: {name:'mytemplate',foreach: <js arrayvar>}">  </div>
    •  containerless binding
      • <!-- ko  template: {foreach: <js arrayvar>} -->
          html code with bindings
        <!-- /ko > -->
Components
  • Helps to organize code into modular, reusable chunks
  • They represent individual controls and widgets
  • can be loaded asynchronously
  • register component
    • ko.components.register('component-name',{
      viewModel:...
      template:....
      })
      viewModel is Optional & template is required
  • <div data-bind: 'component: "myComponent"'>  </div>
  • <div data-bind: 'component: {name: "myComponent", params:"{...}"'>  </div>
  •  


Wednesday, 13 July 2016

Java Script

IDE suggested- Brackets by Adobe

JavaScript
  • It is a programming language  Single threaded, synchronous programming language
  • Object in javascript - It is a collection of name, value pair. However, value may be inturn name, value pair

  • Java script code is run inside execution context(Global). It creates Global Object(Window) & variable called 'this' which refers to Window object.

    Variables and functions which are not inside a function are attached to GLOBAL Object.

    Function Invocation and execution stack
        Invocation in java script is by paranthesis
        When ever a funtion is invoked, a new Execution context is created and placed on execution stack. And variable 'this' is pointed to respective execution stack
Object Creation:
  • var obj1=new Object()
  • var obj2={} 
  •  

NameSpaceA container for variables and functions. Typically to keep variables and functions with the same name separate.

First Class Functions: In java script functions are objects & they are first class funcitons. Every thing that you can do with other types can be done with functions. (assign them to variables, pass them as parameters annd create them on the fly.

Callback function - A function you give to other funciton, to be run when the other function is finished.


call(), apply(), method()
.bind creates a copy of what ever function you are calling and points 'this' variable to Object that you pass as parameter.

logName.bind(person);

Call()
  func() and func.call() are same. It just invokes the function. However, with call() we can control the 'this' variable.  Unlike bind, call() directly executes with out copying the function.

logName.call(person);

apply() is same as Call(). It just expects the parameters in Array rather than individual values.

Function Currying:  Creating a copy of a function but with some preset parameters. This can be achieved by bind funciton passing the parameter values.


Inheritance in Java script: One object gets access to the properties and methods of another object.

 Java script adds hidden method and proerties that we don't directly interact.

All Objects have proto {} property. It is a reference to another object called proto.

John and Person are two independent objects
John.__proto__=person will make person as parent of John

Except the base object(Object{}), every other object has the Prototype.
(one can find the proto by using a.__proto__ in console log)

Proto for function is function Empty(){} and Proto for Array is [].  However, {} is proto for the Empty(){} & [].

Reflection: An object can look at itself, listing and changing its properties and methods.

eg: Suppose John is a Object. Following snippet will loop over its own members.

for (var prop in John){

console.log(prop + ": " + john[prop]);
}


Building Objects:
 var obj=new functionObj();

The above statement creates empty object with 'this' pointing to it. It then copies the statements from funtion where ever 'this' is referred. (as long as the function doens't return any thing)
Also, functionObj() will be the Proto for obj.

Note: Prototype on function is not proto of the function. Rather it is proto of the Objects created using Function as constructor.

Object creation - method 2:
var obj=Object.create(Person);
This creates an empty object and its Prototype points to the Object that you pass as argument.


Github.com - to learn famous open source javascript code

Method Chaining: Calling one method after another, and each method affects the parent object.
eg: obj.method1().method2() where both methods end up with a 'this' variable pointing at 'obj'.






Friday, 8 July 2016

Tomcat

Installation Steps
  • Install java 1.7
  • Download and extract Apache-Tomcat zip to any loacation 
  • Define JAVA_HOME environment variable to java 1.7
  • Download ojdbc5.jar to Apache-Tomcat\lib folder 
  • Place any supporting java classes in WEB-INF\classes directory 
  • run startup.bat file 
  • Invoke jsp from browser
To access admin console of tomcat:
  •  Go to conf folder-> tomcat-users.xml
  • Add role "manager-gui" role using following xml tag
        <role rolename="manager-gui"/>
  • add user with the "manager-gui" role using following xml tag
         <user username="admin" password="admin" roles="manager-gui"/>
  • Remove unwanted users from the list     
  • Restart server 
Connection Pool in TomCat: 
  • Download jdbc driver jar file
    • Place it in WEB-INF/lib directory
  • Define connection pool in WebContent/META-INF/context.xml
  • Define resource reference in WEB-INF/web.xml
    • <resource-ref>
          <description>BugDB Connection Pooling</description>
          <res-ref-name>jdbc/bugap_db </res-ref-name>
          <res-type> javax.sql.DataSource</res-type>
          <res-auth> Container</res-auth>
      </resource-ref>
  • Get connection pool reference in java code
  1.  Using Java Naming and Directory Interface
    public Connection getConnection() { 
    Connection connection = null;  
        try {
            Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
            DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");
            connection = ds.getConnection();
        }
        catch (Exception e) {
            System.out.println("Connection error: " + e.getMessage());  
        }
        return connection;
    }
  2. Resourcing injection with servlets

    @Resource(name="jdbc/bugap_db")
    private DataSource dataSource;