Monday, February 20, 2017

IOT - Internet of Things


  • It is a system of interrelated computing devices, mechanical and digital machines, objects, animals or people that are provided with unique identifiers and the ability to transfer data over a network without requiring human-to-human or human-to-computer interaction.
  • This is the concept of basically connecting any device with an on and off switch to the Internet (and/or to each other)
  • IoT allows for virtually endless opportunities and connections to take place
  • A typical IoT Architecture would be as follows (Extract - docs.microsoft.com - Microsoft Azure IoT Suite)

Friday, February 17, 2017

Java SE – Concurrency (Docs.Oracle.com)

  • Package – java.util.concurrent
  • Concerns two topics – processes & threads
  • Processes is based on computer hardware processor (runtime resources)
  • Each process has its own memory space
  • Threads exist within a process
There are two methods for starting a thread
  • Implement Runnable interface and provide code for "run" method













  • Subclass the Thread class













  • Thread.sleep causes the current thread to pause execution for a specific period (note that neither the Runnable interface is implemented nor the Thread class is extended. Just call Thread.sleep with time)











  • Supporting thread interruption
For a thread "A" to interrupt thread "B", thread "B" should be supporting its own interruption (i.e. the thread should be returning immediately when an interruption is received)

Below class supports interruption since immediately the exception is received the thread returns













If a thread continues to run without any InterruptedException then the thread should frequently call interrupt method to check if an interruption is available. If yes then should return immediately. Code snippet is as below.

for (int i = 0; i < inputs.length; i++) {
    heavyCrunch(inputs[i]);
    if (Thread.interrupted()) {
        // We've been interrupted: no more crunching.
        return;
    }
}
  • To tell thread "A" to resume execution after thread "B" completes (in other words, to tell thread "A" to
wait until thread B" completes, you can call the below method
B.join(); // within thread "A", we are telling A to join B

Thread interference Thread interference occurs when multiple threads run on 2 operations but act on same data (interleave)
See below sample code
class Counter {
    private int c = 0;

    public void increment() {
        c++;
    }

    public void decrement() {
        c--;
    }

    public int value() {
        return c;
    }

}
<CONTINUES FROM https://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html>

Thursday, February 16, 2017

Databases : Normalization vs De normalization (studytonight.com)

Normalization – a systematic approach of decomposing tables to eliminate data redundancy and undesirable characteristics

Normalization forms
  • 1st Normal Form
  • 2nd Normal Form
  • 3rd Normal Form
  • BCNF (Boyce-Codd Normal Form)


Possible Database Anomalies
  • Update anomaly
Ex: Both Employee and EmployeeContact tables have address columns. When updating the contact information, one table is not updated so the same employee has 2 different address values when queried
  • Insertion anomaly
Ex: Course table contains fields CourseID, teacherID,
A teacher who is not yet assigned to a course is added to table with CourseID as null
  • Deletion anomaly
Ex: “Faculty and Courses” table has both lecturer and faculty. If “MEDICAL” faculty is closed, and if we delete all records belonging to “MEDICAL” faculty, all the lecturers in the same faculty will also get deleted (will cease to exist)


Normalization explained

1st Normal Form
No 2 rows of the table should contain repeating information

Each set of column must have a unique value (columns should not have comma-separated / list of values)
Before normalization
Adam
15
Biology, Maths
After normalization
Adam
15
Biology
Adam
15
Maths

Cons – Data redundancy increases
2nd normal form
For a table that has concatenated primary key, each column in the table that is not part of the primary key must depend upon the entire concatenated key for its existence. If any column depends only on one part of the concatenated key, then the table fails Second normal form.
Ex:
Name      Age        Subject
Mike        15           Maths
Mike        15           Science
Andrew   20           History

Above table has a concatenated primary key (i.e. to search a unique value the concatenated value has to be considered.
The field “Age” is not dependent on Name + Age + Subject. It depends only on the name. So Age should be separated out with a primary key

Above table will be decomposed into 2 tables
One has columns Name, Age & the other has columns Name, Subject where name will be the primary key of both tables

3rd normal form
There should not be the case that a non-prime attribute is determined by another non-prime attribute

Ex:
Student_id
Student_name
DOB
Street
city
State
Zip
Street, City & State depends on Zip. So the 3 fields should be moved to a different table as follows (decomposed into 2 tables)

Student_id
Student_name
DOB
Zip


Zip
city
State
Street


BCNF - <TO BE INCLUDED>



Normalization vs De-normalizations
Normalization

  • Writing operations (insert, update) are easy to perform (since no duplicate columns need to be updated)
  • Reading operations are difficult to perform (since data span across multiple tables so joint statements should be used)
De-normalization
  • Writing operations (insert, update) are difficult to perform since more than 1 columns need to be updated
  • Reading operations are easy to perform since data is contained in same table so no need to use joint statements

Micro services architecture (Mammatustech.com)


  • Focuses on distributed, componentized, SOA applications
  • Each service performs a single function
  • Is NOT same as SOA (SOA is often based on WSDLs, SOAP & XML schemas while MS is based on JSON, REST & HTTP)
  • Attempt to deploy independent services
  • Tries to keep business logic and data together
  • Results in continuous integration & delivery
  • JSON is the minimum requirement for micro services
  • Micro services are note stateless (they should own their data)
  • Is about going back to OOP basics (Data, Data storage is specific for its service)
  • Uses Docker or an Amazon AMI
  • You don’t use EAR/ WAR files in MS

Tuesday, February 14, 2017

Design Patterns - Demo


Factory Method


Factory class would look like below












<EDITING>

Atlassian BitBucket - Cloud version

Atlassian Bitbucket is a Repository Management solution
Cloud version is also available

History of commits for a Source code can be compared in different views





Branches 



Sunday, February 12, 2017

Java Garbage Collection (JavaTPoint.com)

In java, garbage means un-referenced objects.

Garbage Collection is process of reclaiming the run time unused memory automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

  • It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
  • It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

Java Persistence API (JPA)

Provides ORM facility for managing relational data in Java applications


  • Entity (equals to a table in a relational DB)
    • Must have a public/ protected no-arg constructor
    • Must not be declared final
  • Entity instance (equals to a table row in a relational DB)
  • Entity Manager Interface 
The EntityManager API creates and removes persistent entity instances, finds entities by the entity’s primary key, and allows queries to be run on entities.


A sample relational mapping is as follows


@OneToOne
@JoinColumns({
    @JoinColumn(name="PARTNUMBER",
        referencedColumnName="PARTNUMBER"),
    @JoinColumn(name="PARTREVISION",
        referencedColumnName="REVISION")
})
public Part getPart() {
    return part;
}

Message Queuing - RabbitMQ






RabbitMQ


  • Accepts and forwards messages.
  • Components are
    • Producer (Forwards the messages)
    • Consumer (Receiver)
    • Queue (an infinite buffer of messages)
  • Confirms to AMQP (Advanced Message Queuing Protocol)


Steps of the Producer (Pyhthon code)
1. Establish the connenction

import pika connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) channel = connection.channel()

2. Create a Queue

channel.queue_declare(queue='hello')

3. Send the message to the queue (Using an exchange method)

channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')
print(" [x] Sent 'Hello World!'")


4. Close the connection
connection.close()

Steps of the Consumer 

1. Declare the Queue

channel.queue_declare(queue='hello')

2. Define the callback methodw which prints the message to be received

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)


3. Define the Producer queue from which the messages should be received

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

4. Never ending loop which consumes messages continuously
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

Tuesday, February 7, 2017

WSO2 ESB - Configuring an ESB service

Get a command prompt
Go to WSO2 ESB installation directory
Invoke wso2server.bat

ESB Server will start and will display the ESB server URL as follows


Open a web browser page and goto the above URL
Login using “admin”, “admin”


Once logged in, you can see the following page



Friday, February 3, 2017

SOFTWARE ENGINEERING BEST PRACTICES


  •  SOLID
    • Single responsibility (Each class will handle only one responsibility)

    • Open-closed (A class is Open for extentions but closed for modifications)
    • Liskov substitution (A reference to a class can be replaced by a sub class of same hierarchy)
    • Interface segregation (Segregating functionality to different interfaces so the user is not forced to implement unwanted methods in the interface)
    • Dependency inversion (Desinging high level functionality first and then go into detailed level implementations)
  • Automated Unit Testing
  • CI (Continuous Integration) (integrate code into a shared repository several times a day)

Monday, January 30, 2017

Hibernate Application Architecture

Components of Hibernate Application Architecture


  • Configuration Object                               
Defines the Database connection and the Class mapping setup hibernate.properties and hibernate.cfg.xml.)
  • SessionFactory Object
This heavy-weight object is created at the application startup.  Creates the Session objects using the configurations defined in configuration object
  • Session Object
Physical connection with the database. Gets  instantiated each time an interaction is needed with the database. These objects are not thread safe so not good to keep open for a long time. Should be destroyed after the session 
  • Transaction Object
A unit of work (Commit or Rollback)
  • Query Object
Is used to query the database
  • Criteria Object
Is this used to keep the conditions used in the query ??? (WHERE condition criteria???)


Generally, In a session-managed environment,  an instance of a class is in one of the following statuses

  • transient: A new instance of a persistent class which is not associated with a Session and has no representation in the database and no identifier value is considered transient by Hibernate.
  • persistent: You can make a transient instance persistent by associating it with a Session. A persistent instance has a representation in the database, an identifier value and is associated with a Session.
  • detached: Once we close the Hibernate Session, the persistent instance will become a detached instance.

sample hibernate configuration file
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

sample file using the hibernate session for CRUD operations


import java.util.List; 
import java.util.Date;
import java.util.Iterator; 
 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class ManageEmployee {
   private static SessionFactory factory; 
   public static void main(String[] args) {
      try{
         factory = new Configuration().configure().buildSessionFactory();
      }catch (Throwable ex) { 
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }
      ManageEmployee ME = new ManageEmployee();

      /* Add few employee records in database */
      Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
      Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
      Integer empID3 = ME.addEmployee("John", "Paul", 10000);

      /* List down all the employees */
      ME.listEmployees();

      /* Update employee's records */
      ME.updateEmployee(empID1, 5000);

      /* Delete an employee from the database */
      ME.deleteEmployee(empID2);

      /* List down new list of the employees */
      ME.listEmployees();
   }
   /* Method to CREATE an employee in the database */
   public Integer addEmployee(String fname, String lname, int salary){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      try{
         tx = session.beginTransaction();
         Employee employee = new Employee(fname, lname, salary);
         employeeID = (Integer) session.save(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
      return employeeID;
   }
   /* Method to  READ all the employees */
   public void listEmployees( ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         List employees = session.createQuery("FROM Employee").list(); 
         for (Iterator iterator = 
                           employees.iterator(); iterator.hasNext();){
            Employee employee = (Employee) iterator.next(); 
            System.out.print("First Name: " + employee.getFirstName()); 
            System.out.print("  Last Name: " + employee.getLastName()); 
            System.out.println("  Salary: " + employee.getSalary()); 
         }
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
   /* Method to UPDATE salary for an employee */
   public void updateEmployee(Integer EmployeeID, int salary ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employee = 
                    (Employee)session.get(Employee.class, EmployeeID); 
         employee.setSalary( salary );
   session.update(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
   /* Method to DELETE an employee from the records */
   public void deleteEmployee(Integer EmployeeID){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employee = 
                   (Employee)session.get(Employee.class, EmployeeID); 
         session.delete(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
}