Sunday, 25 December 2016

MultiChain

MultiChain  - multichain.com
  • Open Platform for BlockChain applications
  • Technically a software which can help you setting up private BlockChain quickly
  • A Fork/extension of Bitcoin core
  • Many extended features which are not available in Bitcoin core
    • Permission management
    • Data streams transactions
    • Native asset transactions
    • Mining and Block signatures
    • Extended peer-peer handshaking
    • & more
    •  
Hashes
  • It is digest of data or crunched data
  • Result of crunching any data into fixed length of alphanumeric string. (one-way method)
  • Many algorithms exists example SHA-1, SHA-256, RIPEMD-160
  • In Bitcoin, Hash is computed twice and most of the time it is SHA-256
  • RIPEMD-160 is used for wallet addresses
MERKLE TREE
  • Binary tree of hashes
  • Bitcoin uses double SHA-256 hashes
  • In case of odd number of nodes in a row, last node's digest taken twice to make it even

BlockChain

BlockChain is a consensus based secure decentralized public database/ledger which stores information immutably over peer-to-peer network.
  • It is a decentralized database which stores information in the form of transactions.
  • It can be private or public
  • It generally stores data in immutable manner
  • It is highly secure. It is secure than traditional storage
  • Data gets stored via consensus based algorithms
  • Uses Cryptography very heavily. (Cryptography is a method of encrypting a data in such a format so that it cannot be read or understood by someone very easily, until and unless he is the owner or has the key).
BITCOIN is a decentralized virtual cryptocurrency built on top of blockchain. It is a product built on top of BlockChain technology.
  • Bitcoin is the largest cryptocurrency built on top of Blockchain technology.
  • Bitcoin removes the dependency on trusted third party to execute the transaction
  • Transaction gets executed by peers based on consensus based algorithm & recorded in the blocks by the miners
  • As of Nov 2016 there are 16M bitcoins in circulation & 1bitcoin(BTC) is worth 730 USD
  • Bitcoins allows you to execute a transaction with out trusting the receiving party within fraction of seconds
  • Yes. Even cross border transaction can be executed in seconds
 BITCOIN is a decentralized virtual cryptocurrency built on top of blockchain

MINING is the process of recording the transactions as a block into the block chain of that currency
  • The are many ways to get any virtual currency
  • Simplest way is to buy is using flat currency(ie govt exchange) through exchange
  • Another way is to earn it through mining by investing computational power into it.
  • So what will miners do if they mine a particular virtual currency?
  • Answer is that they are asked to solve a very complex computational problem to identify that next block in the block chain
  • In return of doing this computation they are rewarded with some virtual coins like bitcoins, Ethereum etc. 
  • Miners use CPU power to identify a nonce (number used only once) through which they can create the digest/signature of the next block n the BlockChain which is less that the recently added block. Miners who do it first announce the answer to entire network & get the reward. 
Consensus Algorithm is Computation methodology of resolving conflicts in BlockChain

BlockChain in Real Life  is a data structure - Arrangement of data in a computer memory(a structured way of storing data)

More details:
  • It can be imagined like a book where each page reference to the previous page through a page number one less than the current page number.
  • Easy to detect if a page has been removed
  • Easy to arrange the pages & identify suspicious activity. That's why page numbers are important in agreements
  • What if the content has been altered? It can also be identified as page numbers are produced by crunching the content of the previous page. If any one changes the content of the page then next page number will not match if we try to regenerate it using altered page content
Even More details:
  • In real Block chain case, each block is built on top of the recent block and use its previous block's content as a signature.
  • Building a block  and adding it in the blockchain is the task of the miner nodes
  • In a public Block chain it is made computationally difficult to add a block to prevent attacks.
  • Miners try to guess a number in such a way that if it gets crunched with the most recent block's fingerprint than it will create a new fingerprint  which will be less that the last/most recent block in the Blockchain.
  • It takes time and computational power to add a block in the Blockchain. Hence there is some reward (25 BTC in case of bitcoin block chain)
  • Private blockchain can choose other methods to add a block as they can trust the miners using a contract etc.
In Summary:
  • It is a decentralized distributed ledge (data structure) where data is being stored inside blocks in form of transactions.
  • Remove the dependency on the trusted third party for recording the data in Blocks
  • In Public blockchain, more complex algorithm require to avoid the malicious activities
  • Since each block is built on top of previous block immutablitiy has been achieved
  • Very difficult to fake a block and very very easy to detect the fake block
  • This all exits in memory of the computers
  • Every participant of the block chain contain the almost same copy of the block chain
Priave and Public Blockchain 
  • Public Blockchain
    • Anyone can read/write without explicit authorization
    • More complex rules for better security
    • Complex consensus algorithm
    • Computationally expensive to mine & add a block
    • No one owns it
    • Computational power is distributed globally
    • example: Bitcoin block chain, Ethreum Blockchain etc
  • Private Blockchain
    • Only authorized nodes can read/write the transaction data
    • Private, hence security can be implemented easily
    • One authorized node can be the arbitrator for any dispute
    • Easy or computatinally less expensive to add a block
    • One or more private entities own the block chain
    • eg: RecordsKeeper blockchain, Icici bank's blockchain etc
When to use a blockchain
  • When you want to store something immutably
  • When things keep adding but older one do not change
    • eg: Court Judgements, Health records
  • When you want to decentralize the control
    • eg: identity management system
  • Proof of ownership.
    • When you want to prove that you are the owner of the digital document
      • proof of existence systems like Block.ai
Why Block chain is considered more secure:
  • Nodes follow longest chain rule
  • Computationally expensive
  • Decentralized in nature
How Blockchain can be attacked:
  • 51% attack
    • Often considered as a very large flaw in public BlockChain like bitcoins blockchain
    • Let's say if a single entity contributed the majority of the network's mining hashrate, then they would have power to manipulate the public ledger
    • It is theoretically possible because Blockchain is publically open
  • Eclipse attack
    • Cripple a node in such a way that it can not talk to other nodes in the network
    • In that case less percentage owner of the network hashrate can launch the attack
    • eg: 3 nodes with 30%, 30% & 40% network hashrate power 
    • If node 2 is crippled in such a way that it cannot talk to node1 then node 3 can control the Blockchains public ledger
Can I setup my own blockchain
  • There are many ways to setup your own block chain 
  • Private blockchain will be fully owned by you. You will be responsible for its security
  • You need to take care of miners. You setup your own miners
  • Multichain
    • Multichain is the most easy way to setup a private blockchain
    • It is opensource and founded by Mr. Gideon Greenspan
    • RecordsKeeper is the official partner of Multichain. 
  • OpenChain
    • It is open source distributed ledger technology. It is suited for organizations wishing to issue and manage digital assets in a robust, secure and scalable way.
      • Anyone can spin up a new Openchain instance within seconds
      • Adiministrator defines the rules
      • Every transaction on the ledger is digitally signed, like with Bitcoin.
  • Ethereum
    • One can setup a private blockchain in Ethereum using Geth
  • Bitcoin Core
    • If you are a tech savvy you can also fork the bitcoin repository and setup your own blockchain
    • It will be complex
RecordKeeper and summary:
  • Record keeper is a record keeping solution for individuals and businesses
  • Records or documents stored in recordskeeper are immutable
  • Records remain highly structured without explicit structure
  • Highly private using PKI infrastructure
  • Available in SaaS and onpremise implementation
Use Cases:
  • Managing and structuring corporate records through automation
  • Health record management for health care industry
  • Invoice & receipt management system for supply-chain, logistic & E-com industry
  • KYC solutions for banks
  • Archiving solutions for large enterprises
  • Proof of ownership, creation and existence

Saturday, 26 November 2016

Java EE

  • It is built on Java SE platform
  • It provides an API and run environment for developing and running large-scale, multi-tiered, distributed, scalable, reliable, and secure network applications. 
    • JDBC
    • JNDI
    • EJB
    • RMI
    • JSP/Servlets 
      • Servlet is a simple java class which can take request in and can respond back with response. 
      • Jsp implictly converst to Servlet. However, it is easier to write dynamic html content in jsp rather than in Servlet 
    • JSF -> It is a web framework
    • JMS
    • JTS
    • JTA
    • JavaMail


Servlets
  • Servlet is a simple java class which can take request in and can respond back with response. 
  • HTTPServets are servlets which can take HTTP request as input and respond with HTTP response.
JSP
  • Expression Language ${name}
  • It is used to dynamically pick up content from Request, Session and other things. 
  • Scriplet
    • Any thing one writes within <%  %>
    • Any java code can be written in Scriplet
  • Scriplet Expression
    •  <%=    %>

Thursday, 29 September 2016

Apache Maven - A java build tool

Maven
  • Build automation tool 
    • Build
      • Compiling 
      • running unit tests 
      • running integration tests
      • Package jar/war
      • Deploy to server
  • Uses POM.xml to describe Project, dependencies, build order & plugins.
  • Convention over configuration
Commands
  • mvn install - install to repository
Objectives:
  • Make build process EASY
  • Uniform build system
  • Describes how software is built
    • It is described by POM(Project Object model)
  • Describes the dependencies the software has
  • Build life cycle- made of up phases
  •  It is collection of plugins. Plugins perform action in maven.
  • It suggest default 'Project Structure' & 'build life cycles'
Generate new project from archetype- Command line
POM
  1. General information
  2. Build settings(Customize the maven lifecycles, add new 'Plugins' and 'Goals')
  3. Build environment(Profiles used to configure different deployment environments, Dev, Test, Prod)
  4. POM Relationships(Modules and SubModules)
  
  • Compile - Dependency available in all build phases & packaged with application
  • Test - Test complication & execution
  • runtime - required only at runtime and not at compile time
  • provided - When container provides dependency
  • system  - Same as provided but you will tell system where exactly is the provided jar
LifeCycles(3 life cycles)
  1. clean - Cleaning up previous build
  2. default or build - building and deployment
  3. site - creating project site documentation
Each lifecycle has Phases;
  • Clean(3 phases) - Few phases have builtin goals/plugins
  • Build(23 Phases)
  • Site(
Plugins
  • They have goals associated with it
    • help:describe -Dcmd =compile ->
Installation: Env variable setup

export M2_HOME=/Users/vdesu/maven/apache-maven-3.6.2
export PATH=$M2_HOME/bin:$PATH

mvn -version
---

Apache Maven- Most used build management tool/Project management tool.
Building a project means
  • Compile
  • Run tests
  • Package into jar files
  • Bundle jar into war files
  • Deploy to server
Maven automates all the above. It follows convention over configuration
  • myproject
    • src/main/java
    • src/main/resources
    • src/test/java
    • src/test/resources
    •  
Archetypes are similar to templates.  Different archtypes are Standalone, webapp, ear etc. Maven creates folder structure based on Archetypes.

Why use Maven:
  • Common interface (standard structure)
  • Dependencies
  • Repositories

Maven Plugin & Goals: Maven Plugin is group of one or more goals. Each plugin exposes atleast one goal.  mvn <plugin name>:<goal name> followed by parameters

  • archetype:generate
  • install:install
  • eg: mvn archetype:generate -DgroupId=com.venkat -DartifactId=hellomaven -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Maven coordinates
  • group id
  • artifact id
  • packaging
  • version
POM: Project Object Model

  • Helps to manage all dependency in web application

Maven Build Life cycle:
  • Validate -> validate pom.xml 
  • Compile -> generate .classfiles
  • Test ->  run the unit tests
  • Package -> create jar file
  • Integration Test-> 
  • Verify -> 
  • Install -> install to local repository
  • Deploy

Core concepts:
  • POM
  • Plugins & goals
  • Coordinates
  • Repositories
Maven Plugins & Goals
  • Plugin is collection of one or more goals
    • syntax: pluginId:goalId
    • eg: 
      • mvn archetype:generate -DgroupId=com.desu -DartifactId=hellomaven -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
      • cd hellomaven
      • mvn install   -> this will compile, run test & package
      • java -cp target\hellomaven-1.0-SNAPSHOT.jar com.desu.App
Lifecycle phases - Phases are associated with one or more goals.
  1. process-resources > resources:resources
  2. compile > compiler:compiler
  3. test > surefire:test
  4. package > jar:jar
When a phase is executed, system runs all its prior phases before executing it. 
Coordinates
  • groupId similar to package name in Java
  • artifactId similar to class name in java
  • packaging (extension)
  • version
Repositories
  • It describes 'how' the software is built.
  • It describes 'Dependencies' the software has. 
  • It is described by 'POM' - Project Object Model - stored in xml format
  • Sheilds from build complexities
Maven Build life cycle
  • Validate -> Compile -> Test -> Package -> Integration Test -> Verify -> Install -> Deploy
Multi Module Project
  • Create/copu POM.xml in parent folder of the 2 projects(childs)
    • Change the artifact id to 'parent', name,  
    • set Packaging to POM
  • Define child projects as Modules
  • Make following changes to Child project POM
    • Add <parent> element with maven coordinates of Parent
  • Build multi module project
    • mvn clean install  // builds all 3 projects
    • Add <dependency> element incase one project is dependent on other
Scopes
  • In dependency tag
    • Compile
      • default scope
    • runtime
      •  not required for compilation
    • provided 
      • required during test and run locally. Hence not exported to war/jar
    • test
      • compile & run Tests only
    • system 
      • similar to provided .. but not provided either by maven or system
    • import
      • used for pom based projects.

Friday, 23 September 2016

Hibernate ORM

  • Persistence 
    • The state of an object can be saved to  a data store, and recreated at a later point in time. It can be persisted to a file or a db.
  • ORM
    • Object Relational mapping
    • It refers to the technique of mapping the representation of data from Java Objects to Relational Database (and vice versa).
  • Hibernate
    • Object Relational mapping solution for Java
    • Framework for mapping Object model to Relational databases
    • It maps Java data types to Database specific data types
    • Generates sql queries automatically and hence, reduces the development time
    • Database independent - can switch to different DB by editing single configuration file
    • Communication happens between Java -> Hibernate -> DB, and vice versa
  • Setup Steps
    • 1. Download hybernate orm zip from http://hibernate.org/
    • 2. Create lib directory in the project, copy jars from downloaded zip lib folders -> required, jpa, java8 directories to project lib folder in eclipse
    • 3. Copy jdbc driver into project lib folder
    • 4. Add jar to class path
        project properties -> build path -> libraries -> add jars
  • Hibernate configuration
    • 1. Add hibernate configuration file to src directory hibernate.cfg.xml
      <!DOCTYPE hibernate-configuration PUBLIC
              "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
              "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

      <hibernate-configuration>
          <session-factory>
              <!-- JDBC Database connection settings -->
              <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
              <property name="connection.url">jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=SLC03RYC.us.oracle.com)(PORT=1521)) (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=xe)))</property>
              <property name="connection.username">vdesu</property>
              <property name="connection.password">vdesu</property>

              <!-- JDBC connection pool settings ... using built-in test pool -->
              <property name="connection.pool_size">1</property>

              <!-- Select our SQL dialect -->
              <property name="dialect">org.hibernate.dialect.OracleDialect</property>

              <!-- Echo the SQL to stdout -->
              <property name="show_sql">true</property>

              <!-- Set the current session context -->
              <property name="current_session_context_class">thread</property>

          </session-factory>
      </hibernate-configuration>
    • Annotate java class(mapping class to db table).  Entity class - Java class that is mapped to a database table
      • Option 1: XML config file (legacy)
      • Option 2: Java annotations (modern, preferred)
        • @Entity
          @Table(name="student")
        •     @Id
              @Column(name="id")
        •     @Column(name="first_name")
    •  Develop java code to perform database operations
      • package com.luv2code.hibernate.demo;

        import org.hibernate.Session;
        import org.hibernate.SessionFactory;
        import org.hibernate.cfg.Configuration;

        import com.luv2code.hibernate.demo.entity.Student;

        public class CreateStudentDemo {

            public static void main(String[] args) {
               
                SessionFactory factory = new Configuration()
                                        .configure("hibernate.cfg.xml")
                                        .addAnnotatedClass(Student.class)
                                        .buildSessionFactory();
               
                Session session = factory.getCurrentSession();

              try{
                Student tempStudent = new Student("venkat","desu","venkat.desu@gmail.com");
                 session.beginTransaction();
                session.save(tempStudent);
                session.getTransaction().commit();
                System.out.println("done");
            } finally {
                factory.close();
            }
               

            }

        }
    • Execute the program.
  • Retrieve a java object with hibernate
    • Student mystudent=session.get(Student.class, <ID value>);
  • Retrieve all Students using Hibernate Query Language (HQL)
    • List<Student> theStudents = session.createQuery("from Student").list();
    • List<Student> theStudents = session.createQuery("from Student s where s.lastName='desu'").list();
    •  List<Student> theStudents = session.createQuery("from Student s where s.lastName='desu' OR s.firstName='venkat'").list();
    • List<Student> theStudents = session.createQuery("from Student s where s.lastName like 'desu%'").list(); 
  • Update Object
    • Student mystudent=session.get(Student.class, <ID value>);
      mystudent.setFirstName("asdf");
  • Bulk Update
    •  session.createQuery("update Student set lastName='desu'").executeUpdate();
  • Delete Object
    • Student mystudent=session.get(Student.class, <ID value>);
      session.delete(mystudent);
  • Bulk Delete
    •  session.createQuery("delete from Student where id=0").executeUpdate();
Hibernate Query Language:
  • HQL is an Object Oriented Query Language
  • Unlike SQL, HQL uses/operates on Classes instead of Tables
  • Advantages
    • Database independent - Easy migration from one DB to another
    • Easy for Java programmers - Quick to learn and implement
  • Creating Tables with Primary and foreign key
Hibernate Object States & LifeCycle:
  • Transient 
    • It is just a POJO Object eg: Student Object
  • Persistent -> Transient Object have association with table. Starts once Transaction is started. The state ends with Commit()
    • session.save()
    • session.persist()
    • session.saveOrUpdate() 
    • session.load()
    • session.get()
    • session.byId()
    • session.byNaturalId()
  • Detached - starts with one of the following methods
    • session.evict() - evicts from session
    • session.clear()
    • session.close() 
    • We can move from detached to Persistent using update(), merge(), saveOrUpdate()
    • It not used then it will be removed by garbage collector
  • Removed
      • session.delete() 
      • It will be available for garbage collection and cannot be used
JPA vs Hibernate(Entity Manger vs Session)


Friday, 9 September 2016

Jira by Atlassian

Agile -> Team based project management methodology.

Jira  is Agile Project management tool & issue tracker.
There are 2 methods of working with agile in JIRA. Kanban and Scrum(Agile methodologies)

Sprint is a set period of time(commonly 1 to 4 weeks). To start a sprint, the team meets with scrum board(Backlog, todo, in progress, complete) open. Two main questions are asked
  • What went well in the last sprint?
  • What can we improve on for the next sprint?
Go thru tickets to determine and agree on what will get accomplished in the next sprint

Scrum Daily Stand-Up meeting - Each team member answers 3 questions(nothing other than the three questions are discussed)
  • What did I accomplish yesterday
  • What will I do today
  • What roadblocks do I forsee to stop me from accomplishing my goal?
 Epic and user Stories
  • Epic is essentially a large user story that needs multiple sprints to complete 
    • As a content creator, I want to be able to upload any video so that I don't have to know how to convert videos to a web-friendly format myself.
  • A user story (a user focused story), that can be finished with in a sprint.
    • eg/formula: As a [role], I want [desire] so that benefit
    • As a content creator, I want to be able to upload any video so that I can see it online 
    • As a content creator, I want the server to convert videos for me so that I don't have to convert them myself.
 Some resources to
  http://agilemanifesto.org
  http://www.agilealliance.org/agile101/

JIRA
  • Issue:  Every card/ticket on board is what JIRA calls an "issue"
  • Every issue has a unique key. The key is made up of the project & a sequential number(DEMO-251, BUG-45)
  • Jira has different types of issues. Each type has different fields associated
    • Epic
    • story (Due date, assignee, Labels)
    • Feature request
    • User contact(First name, Last name, Email)
    • Bug (OS, Assignee, Screenshot)
    • Task
  • Project
    • Projects are a bucket
    • Issues live inside a project
    • Properties such as user permissions, workflows and more are associated with projects
    •  

Saturday, 20 August 2016

Amazon Webservices

What is cloud computing?
    Enables organization to obtain flexible, secure, and cost-effective IT infrastructure.
Just pay what you use. No upfront payment charged.

Infrastructure can have virtual servers, databases, storage, Messaging etc.

AWS platform has been divided into following categories:
    Compute and Network
        Amazon EC2- Supports most of OS in market-
        Amazon Route53
        Amazon VPC - Virtual private cloud
    Storage and Content Delivery
        Amazon S3(Simple Storage solutions)- Website hosting
        Amazon Glacier - to achieve the data
        Amazon CloudFront -
    Databases
        MYSQL
        MY sql server
        Oracle
    Application Services(Messaging and notifications)
        Amazon SES- Messaging
        Amazon SNS- Notification alerts
    Deployment and Management
        Amazon cloudwatch
        Amazon IAM(Identity and access management) -

Cloud Computing

  • What is Cloud
    •  Enables organization to obtain flexible, secure, and cost-effective IT infrastructure.
      Just pay what you use. No upfront payment charged. Infrastructure can have virtual servers, databases, storage, Messaging etc.
  • Service Models.
    • IAAS - Infrastructure as service - AWS, Azure
    • PAAS - Platform as service - AWS
    • SAAS - Software as service - GMAIL (Multi tenant environment) 
      • Best value for money
http://robertgreiner.com/uploads/images/2014/AzureServicesOverview.png
  • Essential Characteristics
    • On demand self service - Provision computing capabilities, such as server time and network usage, as needed automatically without manual intervention
    • Broad network access - Capabilities are available over network and accessed through standard mechanisms that promote use by heterogeneous thin or thick client platforms(eg: mobiles, tablets, laptops and workstations)
    • Resource Pooling -  The provider's computing resources are pooled to serve multiple consumers using a multi-tenant model, with different physical and virtual resources dynamically assigned and reassigned according to consumer demand. There is a sense of location independence in that the costomer generally has no control or knowledge over the exact location of the provided resources but may be able to specify location at a higher level of abstraction. Examples or resources include storage, processing, memory, and network bandwidth
    • Rapid elasticity: Capabilities can be elastically provisioned and released, in some cases automatically, to scale rapidly outward and inward commensurate with demand. To the consumer, the capabilities available for provisioning often appear to be unlimited and can be appropriated in any quantity at any time.
    • Measured service: Cloud systems automatically control and optimize resource use by leveraging a metering capability at some level of abstraction appropriate to the type of service(e.g., storage, processing, bandwidth, and active user accounts). Resource usage can be monitored, controlled, and reported, providing transparency for both the provider and consuer of the utilized service.
  • Deployment Models(Procurement model for cloud)
    • Private cloud: The cloud infrastructure is provisioned for exclusive use by a single organization comprising multiple consumers. It may be owned, managed, and operated by the organization, a thrird party, or some conbination of them, and it may exist on or off premises.
    • Community cloud: The cloud infrastructure is provisioned for exclusive use by a specific community of consumers from organizations that have shared concerns. It may be owned, managed, and operated by one or more of the organizations in the community, a thrid party, or some combination of them, and it may exist on or off premises.
    • Public cloud: The cloud infrastructure is provisioned for open use by the general public. It may be owned, managed, and operated by a business, academic, or government organization, or some combination of them. It exits on the premises of the cloud provider.
    • Hybrid cloud: The cloud infrastruture is a composition of two or more distinct cloud infrastrucres(private, community, or public) that remain unique entities, but are bound together by standardized or proprietary technology that enables data and application portability.

Saturday, 6 August 2016

Java Design Patterns

Design Pattern: Solution for known  design problems.
Creational Design Pattern
Singleton Design Pattern - One and ONLY copy of an Object

  • Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
  • To make an instance of an object globally available and guarantee that only one instance of the class is created.
  • Singleton provides a global, single instance.
  • Steps to create
    • Make the constructor as private(so that object can be created from the same class only)
    • Maintain a private static variable to hold the instance reference
    • Create a public static method to create instance if the static variable is NULL. Otherwise just return the instance from the static variable reference.
    • Make sure the method is thread safe
Advantage of Singleton Pattern over Static Class in Java: Main advantage of Singleton over static is that former is more object oriented than later. With Singleton, you can use Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different implementations.
  • If your requirements needs to maintain state than Singleton pattern is better choice than static class, because maintaining  state in later case is nightmare and leads to subtle bugs. 
  • Singleton classes can be lazy loaded if its an heavy object, but static class doesn't have such advantages and always eagerly loaded.
Factory Design Pattern
  • In factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface
  • In simple words, if we have a super class and sub-classes, based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern. 
  • Factory design pattern is used when we have a super class with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern take out the responsibility of instantiation of a class from client program to the factory class. We can apply Singleton pattern on Factory class or make the factory method static
  •  If object creation code is spread in whole application, and if you need to change the process of object creation then you need to go in each and every place and make necessary changes.
  • Lot of Scattered new keyword(Avoid it by introducing factory class)
  • Client is aware of all implementation types.(avoid it by interfaces)
  • It is to break link between client and concrete classes
  • low coupling
Abstract Design Pattern
  • Abstract factory pattern is a super factory. It is a factory which creates other factories. This factory is also called as factory of factories
  • Abstract Factory pattern is similar to Factory pattern and it’s factory of factories. In Factory design pattern, we have a single Factory class that returns the different sub-classes based on the input provided and factory class uses if-else or switch statement to achieve this.

    In Abstract Factory pattern, we get rid of if-else block and have a factory class for each sub-class and then an Abstract Factory class that will return the sub-class based on the input factory class. 
Builder Pattern

  • This pattern was introduced to solve some of the problems with Factory and Abstract Factory design patterns when the Object contains a lot of attributes. Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object. Check out Builder Pattern for example program and classes used in JDK.
    • This is used when Class constructor has too many arguments & user doesn't want to provide values at once
    • Builder class will have same set of parameters and returns object with NULL values. 
    • All setters will set the value and return the builder object
    •  

Prototype Pattern

  • Prototype pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing. So this pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. This pattern uses java cloning to copy the object.

    Prototype design pattern mandates that the Object which you are copying should provide the copying feature. It should not be done by any other class. However whether to use shallow or deep copy of the Object properties depends on the requirements and its a design decision. Check out Prototype Pattern for sample program. 
Marker Interface Design Pattern
public interface DemoMarkerInterface{}
public class DemoClass implements DemoMarkerInterface{}
public class Driver {
    DemoClass democlass=new DemoClass();
    if (democlass instanceof DemoMarkerInterface)
        System.out.println("DemoClass is a DemoMarkerinterface");

}

Data Access Object Pattern
  • DAO pattern is used to separate low level data accessing API or operations from high level business services
  • DAO layer is responsible for Data Access from the persistence storage and manipulation of data in the persistence storate
  • Decouple the persistent storage implementation from the rest of your application
  • Intermediate layer between business and database layer. It just contains methods for CRUD operations. No business logic is present.
  • Main Use of DAO Layer
    • Used to perform the CRUD operations
DAO
  • Class that contains the basic CRUD operations for one entity class. It has the necessary code to get or retrieve things of the underlying persistent storage system
Repositories
  • In a higher level of abstraction.. as generally I have read is a kind of place where put code that handle operations over aggregate objects (objects that have child objects). 
DDD: Repository Implementation Patterns

https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design

 

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;

Friday, 11 March 2016

REST webservice - Representational State Transfer(by Roy Fielding)

Initial Setup - jaxrs 1.9
  • Download Jersey 1.x jars from https://jersey.java.net/download.html
  • Create Dynamic web project in Eclipse EE version
  • Copy Jersey 1.x jars to eclipse lib folder in  
  • Add the Jersey sevelet & init param details to web.xml
        <servlet>
            <servlet-name>ServletAdaptor</servlet-name>
            <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
            <init-param>
                <param-name>jersey.config.server.provider.packages</param-name>
                <param-value>com.venkat.rest</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>ServletAdaptor</servlet-name>
            <url-pattern>/resources/*</url-pattern>
        </servlet-mapping>
  • Make sure that the init Param name value is the package where the resources are placed. Which means if you want to make something a resource it should belong to that PACKAGE. (jersey.config.server.provider.packages is the param name for jax rs 2?)
  • Sample resource code
    package com.venkat.rest;

    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.core.MediaType;


    @Path("/weatherService")
    public class WeatherService {

        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public String findWeather() {
            return "Hyderabad 25 40";
        }


        @GET
        @Path("/findWetherBy")
        public String findWeatherByZip() {
            return "Bangalore 30 40";
        }

        @GET
        @Path(value = "findWeatherByZip/{zip}")
        public String findWeatherByZip(@PathParam("zip") int zip) {
            return "Hyd 30,40";
        }
  • index.jsp

    <html>
    <head>
    <title>Rest Services</title>
    </head>
    <body>
    <a href="resources/weatherService">Weather Service</a><br/>
    <a href="resources/weatherService/findWetherBy">findWetherBy</a><br/>
    <a href="resources/weatherService/findWeatherByZip/3">findWeatherByZip3</a>
    </body>
    </html>

Jersey Rest Client:

public class MyRestClient{
    public static void main (String[] args){
        Client client = ClientBuilder.newClient();
        String result = client.target("....restapi/myresource").request().get(String.class);
        Sysout(result)
}
}


What are webservices:
  Services that are exposed to internet for programatic access and can be called by your code. They are online apis.

What is difference between website and webservice
  website are for human consumption. HTML data (twitter.com)
  xml/json bare bone data. No fancy html/css required(api.twitter.com)

Restful webservices:
  Restful apis are type of webservices that are modern, light weight and use lot of concepts behind HTTP(technology that drives the web).

Characteristics of Web Services
   Exchange of data happens over the web over http. Client sends HTTP request, and server responds again with HTTP response.

Protocol(format in which data moves from server and client):  None for REST services.

Method: None, use any http methods

Service Definition(WSDL): Document which defines what the web service does. NONE for REST service

Restful webservice do not have any SPECIFICATION. Its an idea / an architectural style.