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(); 
      }
   }
}

Object Relational Mapping (ORM)

Object Relational Mapping (ORM)

Consider a scenario where there is an object in a POJO and the relevant table which stores the object's attribute values (EX. An Employee class and an employee table)

Employee class would have the following format

Class Employee {

private int EmpId;
private String name;
private String companyName;
private double salary;
..
..
..
}

Employee table in the Database would have the following format

EmpId | name | companyName | salary


Since the table and object structures are different, it is difficult to do the CRUD operations with minimal dependency. So a middle layer is introduced (which is called Object Relational Mapping) so that the link between table and ORM, and the link between the ORM and the class can be seperately defined

Hibernate is an example of an ORM

Log file processing with Logstash and Elastic Search

In an environment where log files are need to be read and analysed frequently to monitor network related errors, Logstash (OPEN SOURCE) is used in conjunction with Elastic search

Logstash is a software which helps keep reading log files from different sources and transform them (with pipe lining) and send it to a store (with indexes) so that from the store the data can be read and analysed

Elastic search is an example of a store to which the pipelined data can be transferred and from which the data can be read using indexes 

Thursday, January 26, 2017

BCS - Short Note - 05092015.docx
Searching
·       Linear/ Sequential Search
·       Binary Search (Binary Chop)

·       Linear/ Sequential Search
In computer science, linear search or sequential search is a method for finding a particular value in a list that checks each element in sequence until the desired element is found or the list is exhausted.
·       Binary Search (Binary Chop)
In computer science, a binary search or half-interval search algorithm finds the position of a target value within a sorted array.
The binary search algorithm begins by comparing the target value to the value of the middle element of the sorted array. If the target value is equal to the middle element's value, then the position is returned and the search is finished. If the target value is less than the middle element's value, then the search continues on the lower half of the array; or if the target value is greater than the middle element's value, then the search continues on the upper half of the array. This process continues, eliminating half of the elements, and comparing the target value to the value of the middle element of the remaining elements - until the target value is either found (and its associated element position is returned), or until the entire array has been searched (and "not found" is returned).
Binary Search Java Code
1    int[] data;
2    int size;
3
4    public boolean binarySearch(int key)
5    {
6         int low = 0;
7         int high = size - 1;
8         
9         while(high >= low) {
10             int middle = (low + high) / 2;
11             if(data[middle] == key) {
12                 return true;
13             }
14             if(data[middle] < key) {
15                 low = middle + 1;
16             }
17             if(data[middle] > key) {
18                 high = middle - 1;
19             }
20        }
21        return false;
22   }


3 Control Structures

According to the structure theorem, any computer program can be written using the basic control structures shown in Figure 3-1. They can be combined in any way necessary to deal with a given problem.

Figure 3-1 Control Structures



Stacks and Queues

Stacks

A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only two operations are allowed: push the item into the stack, and pop the item out of the stack. A stack is a limited access data structure - elements can be added and removed from the stack only at the top. push adds an item to the top of the stack, pop removes the item from the top. A helpful analogy is to think of a stack of books; you can remove only the top book, also you can add a new book on the top.

Applications of stack

  • The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter - and then pop letters from the stack.
  • Another application is an "undo" mechanism in text editors; this operation is accomplished by keeping all text changes in a stack.
 http://www.cs.cmu.edu/~adamchik/15-121/lectures/Stacks%20and%20Queues/pix/stack.bmp

Queues

A queue is a container of objects (a linear collection) that are inserted and removed according to the first-in first-out (FIFO) principle. An excellent example of a queue is a line of students in the food court of the UC. New additions to a line made to the back of the queue, while removal (or serving) happens in the front. In the queue only two operations are allowed enqueue and dequeue. Enqueue means to insert an item into the back of the queue, dequeue means removing the front item. The picture demonstrates the FIFO access.
The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.


 http://www.cs.cmu.edu/~adamchik/15-121/lectures/Stacks%20and%20Queues/pix/queue.bmp

Difference between Sequential and Parallel Programming

Parallel programming involves the concurrent computation or simultaneous execution of processes or threads at the same time. While Sequential programming involves a consecutive and ordered execution of processes one after another.
In other words with sequential programming, processes are run one after another in a succession fashion while in parallel computing, you have multiple processes execute at the same time. With sequential programming, computation is modeled after problems with a chronological sequence of events.
The program in such cases will execute a process that will in turn wait for user input, then another process is executed that processes a return according to user input creating a series of cascading events. In contrast to sequential computation, parallel programming, while processes might execute concurrently, yet sub-processes or threads might communicate and exchange signals during execution and therefore programmers have to place measures in place to allow for such transactions.

Software Types

The term 'software' refers to the set of electronic program instructions or data a computer processor reads in order to perform a task or operation. In contrast, the term 'hardware' refers to the physical components that you can see and touch, such as the computer hard drive, mouse, and keyboard.
Software can be categorized according to what it is designed to accomplish. There are two main types of software: systems software and application software.

Systems Software

Systems software includes the programs that are dedicated to managing the computer itself, such as the operating system, file management utilities, and disk operating system (or DOS). The operating system manages the computer hardware resources in addition to applications and data. Without systems software installed in our computers we would have to type the instructions for everything we wanted the computer to do!

Applications Software

Application software, or simply applications, are often called productivity programs or end-user programs because they enable the user to complete tasks such as creating documents, spreadsheets, databases, and publications, doing online research, sending email, designing graphics, running businesses, and even playing games! Application software is specific to the task it is designed for and can be as simple as a calculator application or as complex as a word processing application. When you begin creating a document, the word processing software has already set the margins, font style and size, and the line spacing for you. But you can change these settings, and you have many more formatting options available. For example, the word processor application makes it easy to add color, headings, and pictures or delete, copy, move, and change the document's appearance to suit your needs.


BCS - Software Engineering - Short note04092015.docx
Dry Run
        You can test your program without using a computer by dry running it on paper
        You act as the computer – following the instructions of the program, recording the valves of the variables at each stage
        You can do this with a table
        The table with have column headed with the names of the variables in the program
        Each row in the table will be labelled with a line number form the program.
        The entries of each row in th e table will be values of the variables after the execution of the statement on that line
        You don’t need a row for every line in the program, just those lines where some significant change to the state of the program occurs e.g a variable gets a new value
        In this table you can record all relevant changes to the variables as the program progresses, thereby test the logic of the program / algorithm
        Do a dry run before you code your program on computer this way any logic errors will come to light during the dry run
        L1  Declare two variables , first num second num
        L2  Initialise both variables to 0
        L3  first num = 0 second num = 0
        L4  Ask user to enter first number
        L5  Assign user input to first num variable  
        L6  Ask user to enter second number
        L7  Assign user input to second num variable
        L8  Add first num to second num
        L9  Print result
        Do a Dry run for this program assuming the user enters 17 for first number and 24 for the second
After
execution
First num
Second num
Result
Line 2
0
0
Line 5
17
0
Line 7
17
24
Line 8
17
24
41

White box testing
1.      White-box testing (also known as clear box testing, glass box testing, transparent box testing, and structural testing) is a method of testing software that tests internal structures or workings of an application, as opposed to its functionality (i.e. black-box testing).
2.       
3.      The Differences Between Black Box Testing and White Box Testing are listed below.
4.       
Criteria
Black Box Testing
White Box Testing
Definition
Black Box Testing is a software testing method in which the internal structure/ design/ implementation of the item being tested is NOT known to the tester
White Box Testing is a software testing method in which the internal structure/ design/ implementation of the item being tested is known to the tester.
Levels Applicable To
Mainly applicable to higher levels of testing:Acceptance Testing
Mainly applicable to lower levels of testing:Unit Testing
Responsibility
Generally, independent Software Testers
Generally, Software Developers
Programming Knowledge
Not Required
Required
Implementation Knowledge
Not Required
Required
Basis for Test Cases
Requirement Specifications
Detail Design

Sorting algorithms


Bubble Sort

In the bubble sort, as elements are sorted they gradually "bubble" (or rise) to their proper location in the array, like bubbles rising in a glass of soda. The bubble sort repeatedly compares adjacent elements of an array. The first and second elements are compared and swapped if out of order.  Then the second and third elements are compared and swapped if out of order.  This sorting process continues until the last two elements of the array are compared and swapped if out of order.

When this first pass through the array is complete, the bubble sort returns to elements one and two and starts the process all over again.  So, when does it stop?  The bubble sort knows that it is finished when it examines the entire array and no "swaps" are needed (thus the list is in proper order).  The bubble sort keeps track of the occurring swaps by the use of a flag.

The table below follows an array of numbers before, during, and after a bubble sort fordescending order.  A "pass" is defined as one full trip through the array comparing and if necessary, swapping, adjacent elements.  Several passes have to be made through the array before it is finally sorted. 
 

Array at beginning: 
84
69
76
86
94
91
After Pass #1:
84
76
86
94
91
69
After Pass #2: 
84
86
94
91
76
69
After Pass #3: 
86
94
91
84
76
69
After Pass #4: 
94
91
86
84
76
69
After Pass #5 (done): 
94
91
86
84
76
69
The bubble sort is an easy algorithm to program, but it is slower than many other sorts.  With a bubble sort, it is always necessary to make one final "pass" through the array to check to see that no swaps are made to ensure that the process is finished.  




Exchange Sort
 
The exchange sort is similar to its cousin, the bubble sort, in that it compares elements of the array and swaps those that are out of order.  (Some people refer to the "exchange sort" as a "bubble sort".)  The difference between these two sorts is the manner in which they compare the elements. The exchange sort compares the first element with each following element of the array, making any necessary swaps. 
 
When the first pass through the array is complete, the exchange sort then takes the second element and compares it with each following element of the array swapping elements that are out of order.  This sorting process continues until the entire array is ordered.
Let's examine our same table of elements again using an exchange sort for descending order.  Remember, a "pass" is defined as one full trip through the array comparing and if necessary, swapping elements
Array at beginning: 
84
69
76
86
94
91
After Pass #1:
94
69
76
84
86
91
After Pass #2:
94
91
69
76
84
86
After Pass #3: 
94
91
86
69
76
84
After Pass #4: 
94
91
86
84
69
76
After Pass #5 (done): 
94
91
86
84
76
69



Selection Sort
The selection sort is a combination of searching and sorting.

During each pass, the unsorted element with the smallest (or largest) value is moved to its proper position in the array. 
The number of times the sort passes through the array is one less than the number of items in the array.  In the selection sort, the inner loop finds the next smallest (or largest) value and the outer loop places that value into its proper location.
Let's look at our same table of elements using a selection sort for descending order.  Remember, a "pass" is defined as one full trip through the array comparing and if necessary, swapping  elements.


Array at beginning: 
84
69
76
86
94
91
After Pass #1:
84
91
76
86
94
69
After Pass #2:
84
91
94
86
76
69
After Pass #3: 
86
91
94
84
76
69
After Pass #4: 
94
91
86
84
76
69
After Pass #5 (done): 
94
91
86
84
76
69



Insertion Sort
The insertion sort, unlike the other sorts, passes through the array only once.  The insertion sort is commonly compared to organizing a handful of playing cards.  You pick up the random cards one at a time.  As you pick up each card, you insert it into its correct position in your hand of organized cards. 

The insertion sort splits an array into two sub-arrays. The first sub-array (like the cards in your hand) is always sorted and increases in size as the sort continues. The second sub-array (like the cards to be picked up) is unsorted, contains all the elements yet to be inserted into the first sub-array, and decreases in size as the sort continues.
 
Let's look at our same example using the insertion sort for descending order.
 

Array at beginning: 
84
69
76
86
94
91

= 1st sub-array
84
69
76
86
94
91

= 2nd sub-array
84
69
76
86
94
91

84
76
69
86
94
91

86
84
76
69
94
91

94
86
84
76
69
91
2nd sub-array empty
94
91
86
84
76
69


The insertion sort maintains the two sub-arrays within the same array.  At the beginning of the sort, the first element of the first sub-array is considered the "sorted array".  With each pass through the loop, the next element in the unsorted second sub-array is placed into its proper position in the first sorted sub-array.
The insertion sort can be very fast and efficient when used with smaller arrays.  Unfortunately, it loses this efficiency when dealing with large amounts of data