Saturday, May 25, 2013

Assignment 3 Event Handling without GUI components

You extended the Assignment 2 submission date. So Assignment 3 got delayed too. But do worry, its easy task, specifically if you visit the link given below.

The objective of this assignment is to understand events handling in abstract way. We have used events with GUI components, but events are not only associated with GUI components. You can define events and fire them even when there is no GUI of your application.


In this assignment you are supposed to create ResultAnnouncedEvent which is fired by ExaminationCenter. Different entities (or classes) can register themselves as listeners so that when result is announced they are notified, for example Student, Teacher and Administrator. So these classes are event listeners. These classes should just receive the event and print the event attributes. The ResultAnnouncedEvent class should be composed of class, section, and date attributes. Also create ExaminationCenterTest class that fires the event.

Before doing this assignment, it is recommended you read API docs of java.util.EventObject, java.util.EventListener.

Also See: 
http://www.jguru.com/faq/view.jsp?EID=98547


Submission Deadline: 30 May 2013

Saturday, May 11, 2013

OOCP - JDBC and Exception Handling Assignemt for Spring 2013


Objective of this assignment is to get familiar with JDBC basic operations i.e. Insert, select, update and delete queries. and to see, how we exception handling helps in real projects.

Submission deadline is: 15 May 2013.

A Student class is consists of id, name, phone, and age attributes.

Write a StudentService class that insert, update, and delete records in/from students table using JDBC API.
It should have following methods:
 public boolean add(Student s)
 public boolean update(Student s)  - it should update record based on id
 public boolean delete(int id) - it woud delete the student record from table, based on passed ID.

If invalid student id is passed to update and delete methods. Both should throw and checked exception, StudentNotFoundException. If the student ID is found, they should perform their function.

All JDBC interaction related code should be only in StudentService class. No JDBC related code should be in Student and StudentTest classes. To interact with database, the StudentTest class would use methods defined in StudentService class.

Write a StudentTest class to demonstate the above functionality. 
It should work something like this:

Press 1, to add new record in students table
Press 2, to remove a student
Press 3, to view list of all students
Press 4: to update

When user choose 1, it should take values of all fields (except ID, ID would be auto generated) as input and then insert a record in students table.
When user choose 2, it should take ID from user, and delete that record in database using delete(int). method of StudentService class.
When user choose 3, it should display all records of students table.
When user choosed 4, it should take student ID of the record that needs to be updated. and then it should take new name, phone, age. It should update the 3 values for the selected user in database.

Please note, StudentTest class must handle the StudentNotFoundException if its thrown by update or delete method of StudentService class.

Database name = academics-db
Table name = students
The fields and data-types of students table are as follows:
id INT AUTO-INCREMENT, and PRIMARY KEY
full_name VARCHAR(40)
phone VARCHAR(20)
age INT

If something is not clear, discuss it with your CRs/fellows or post your questions as comment below.

There is both sections' quiz from JDBC and Exception Handling on 15 May, in last slot.

Tuesday, May 7, 2013

JDBCExample


//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {

    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/students";

    //  Database credentials
    static final String USER = "root";
    static final String PASS = "asdf";

    public static void main(String[] args) {
        Connection con = null;
        Statement stmt = null;

        try {
            //STEP 2: Register JDBC driver
            Class.forName(JDBC_DRIVER);

            //STEP 3: Open a connection
            System.out.println("Connecting to a selected database ... ");
            con = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Connected database successfully.");

            //STEP 4: Execute a query
            System.out.println("Creating statement.");
            stmt = con.createStatement();

            String sql = "SELECT id, first_name, last_name, age FROM registration";
            ResultSet rs = stmt.executeQuery(sql);

            //STEP 5: Extract data from result set
            while(rs.next()){
                //Retrieve by column name
                int id  = rs.getInt("id");
                String firstName = rs.getString("first_name");
                String lastName = rs.getString("last_name");
                int age = rs.getInt("age");

                //Display values
                System.out.print("ID: " + id);
                System.out.print(", Age: " + age);
                System.out.print(", First: " + firstName);
                System.out.println(", Last: " + lastName);
            }
            rs.close();
        }catch(SQLException se){

            //Handle errors for JDBC
            se.printStackTrace();

        }catch(Exception e){

            //Handle errors for Class.forName
            e.printStackTrace();

        }finally{
            //finally block used to close resources
            try{
                if(stmt!=null)
                    con.close();
            }catch(SQLException se){  /* do noting if still some exception */ }

            try{
                if(con!=null)
                    con.close();
            }catch(SQLException se){
                se.printStackTrace();
            }//end finally try
        } //end try

        System.out.println("Goodbye!");

    }//end main

}//end JDBCExample

Sunday, April 14, 2013

OOCP Lab Assignment 1 - Due on April 19

Mr. Junaid has decided to open a new bank that would encourage savings and discourage expenses or spending; his target is to attract younger people. Further assume Mr. Junaid has huge seed/surplus money to spend to gain customers. He has made some policies for the bank accounts. These policies are given in assignment description:


1.      Write an Account class that satisfied following requirements. Name (String), CNIC (String) and age (int) must be provided when creating a new Account. If the age is greater than 35, the balance (double) should be set to 0. (So, he doesn’t give any amount to people greater than 35). For rest, Junaid want to apply following formula on initial balance: 50000PKR initial balance for customers who have age between [20-25} years, 25000PKR for age between [25-30} years and only 10,000 for age between [30-35] years. Assume there would be no customer less than 20 years old. He further want to encourage deposits and discourage withdraws. So whenever a customer deposit an amount, Junaid pays 5% of that amount from his own pocket (e.g. if customer deposit 500 PKR, the balance should be increased by 525PKR). And whenever, someone with-draw an amount, Junaid wants to decrease his balance by 10% more (for example, if customer withdraws 200 PKR, Junaid want to decrease 220PKR from customer account). (5 Marks)

2.      Make a Bank class which is composed of bankName (String) and accounts (Account Array). (5 Marks)

3.   Create BankTest class, implement main method to demonstrate the above functionality. (5 Marks)

The main method should work like this:
Write the bank name:
>The Youngster’s Bank
Enter a number:
1.      Open a new account
2.      Deposit money to an account
3.      Withdraw money from an account
4.      Check current balance
1
Enter name, cnic, and age:
> Shahzad
>5487-8754-1
>30

Account has been created!

(Show main menu again, say user chosen: 2)
Enter Account Number and Amount to deposit:
>5487-8754-1
>20000

(Show main menu again, say user chosen: 3)
Enter account number and an amount to withdraw:
>5487-8754-1
>10000

(Show main menu again, say user chosen: 4)
Enter account number:
>5487-8754-1
Your account balance is: 20,000

Thursday, March 28, 2013

Profiling PHP Connections - Pool vs No Pool

Creating connection in efficient way is important, specifically if you are writing a consumber website that targets thousands of concurrent visitors. In this post I would share some performance statistics of creating connections using connection pool and without using connection pool.

To see the performance difference, I created 100 connections without using connection pool and another 100 connections using connection pool. Here I show you the average time of creating one connection. 

I repeated same process 10 times, here are the states:

Time to get one connection at localhost, in milliseconds.
Without Connection Pool   |   With Connection Pool 
                                 9.37    |    0.99       ms 
                               11.06    |    1.02       ms 
                               10.48    |    0.77       ms 
                               10.82    |    0.81       ms 
                               10.13    |    0.81       ms 
                               11.49    |    0.83       ms 
                               10.82    |    0.83       ms 
                               10.44    |    0.84       ms 
                               10.67    |    1.07       ms 
                               10.71    |    0.84       ms 

There is approximately 10 times performance improvement when connection is created using from connection pool. Here is the PHP code:

define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "mypassword");
define("DEFAULT_DB_NAME", "test_db");

echo "Time to get one connection at localhost, in milliseconds \n ";
echo "Without Connection Pool   |   With Connection Pool \n ";

for ($index = 0; $index < 10; $index++) {
    $t1 = round(microtime(true) * 1000);
    for ($i = 0; $i < 100; $i++) {
        $con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
    }
    echo "             " . ((round(microtime(true) * 1000)) - $t1) / 100 ;

    /******************** USING CONNECTION POOL ****************************/

    $t1 = round(microtime(true) * 1000);
    for ($i = 0; $i < 100; $i++) {
        $con = new mysqli("p:" . DB_HOST, DB_USER, DB_PASSWORD);
    }
    echo "    |    " . ((round(microtime(true) * 1000)) - $t1) / 100 . "       ms ";
    echo "\n";
}

Monday, March 11, 2013

Best Web Based Mockups Creation Tool

In last few days I spent couple of hours searching and trying different mockups creations tools/solutions. Some were only desktop based, otherwise were web based by paid. I was searching for great mockup tool that must be web based and free.

Why web based, I wanted to share my created mockups with my team members.

Here is the tool I finally have decided to pick. Hope you would like it too. https://moqups.com

Saturday, March 9, 2013

PHP Update Form

In PHP Update Form post, I would explain how you can display an HTML form that is already filled or populated. We often need it to update some previous data. Lets first see the code, then we would move to some points that you must understand about creating update form in php:



Analyse following points:
  • For text, password and textarea fields, we only need to set 'value' attribute of form input tag to display it as populated. In above code, we did it for 'name' and 'passowrd' field. (Its not good practice to display password as populated in real applications.)
  • The case differs for radio buttons, checkboxes, and option list. To display a radio button or checkbox already selected, we must write 'checked="checked"' attribute. So to display an earlier data, we must add some PHP code with each radio button to determine what was the previous value e.g. Visa, so that we can render 'checked="checked"' for that radio button. In case of checkboxes, as multiple selection is allowed, so we have used an array to check whether a particular element exist inside the array. The 'subjects' array contains two elements 'Algorithms' and 'OOP'. So these two checkboxes would be displayed as checked.
Here is the output generated by above HTML/PHP code:

Friday, March 8, 2013

PHP Full Form

In this post I would explain how to process a form using PHP. Before we move to PHP code, lets see how our HTML code looks like which creates the form. I have included all possible basic controls (text, checkbox, radio, option list, etc) to demonstrate how fetching values for different type of controls differ when we write PHP code.


If you know HTML, you know there is nothing special in above file. Its just plain HTML. Notice, action value is full-form-handler.php. It means, when the user submit this form, full-form-handler.php would be executed to process the form data.
In our full-form-handler.php, we just want to retrieve each submitted value and show it on the next page. Lets see, how the php file looks like:


There are following points, you must understand about above code snippet:
  • Input type text and password are handled just normally. $_REQUEST['name'] return the string value.
  • In case of check boxes, only those check boxes values are submitted, which were selected/checked by user. Other check boxes are not submited. So we must have to check, which check boxes were received by server to know what user checked.
  • By defult, 'on' value is submitted by the browser for the checked checkbox. But if you want to receive a particular value, you must use the value attribute of checbox when you write HTML. For know, lets just proceed with default valu i.e. 'on'
  • About the radio button, you see we given same name to multiple radio buttons, why? because by doing so, we declare that only one radio button should be active at a time. For example, user credit card would belong to a single company. From same name, the web browser automatically deselect the previous crdit card of we choose another one.
  • We are only left with languages list. We know, we have allowed user to select multiple values. So PHP automatically create an array of all selected and submitted values and return us just that array. We just need to iterate that array to retrieve those values

Lets see, how our form looks like:


Here is the output generated by above PHP code:

Thursday, March 7, 2013

PHP Form

In this post I would create a simple form in HTML (with just two input boxes) and then write PHP code to retrieve the form values a user submit using PHP.

So in our sample project there are only two files:
  1. form.html
  2. form-handler.php
Let see the form.html code:
This form will generate following output:












There are following points to note:

  1. The action attribute value is form-handler.php. It shows, when the form is submitted form-handler.php would process the form. Processing includes, retrieving form data and storing it somewhere if you want to.
  2. The input text boxes names are first-name and last-name. On PHP page, we would use these  names to retrieve the values user entered in the PHP form.

The Server Side

The form-handler.php code retrieves the both input values and display on the next page. Lets first look at the form-handler.php code.

Please note following points regarding we process the form values at server side:

  1. The PHP receives the submitted values and put them into global associatve array $_REQUEST. We can retrieve values using the input text field names.
  2. In the code above, we have retrieved the values from $_REQUEST array, store them into our local variable and then printed those values inside the HTML BODY element.
When we submit the form, following output is displayed:

Tuesday, January 8, 2013

Mobile Application Development - Equip IT Grads With What Market is Demanding

Most Pakistani universities' BSCS / BSSE / BSIT programs contain Web Engineering course. Web Engineering primarily cover concepts and lab work related to web applications development. But in last 4-5 years, the demand of mobile applications has increased exponentially. In just 4 years of Android launch, Android store is touching 6,75000 number of total apps ( September 2012), and these are increasing day by day. In only December 2012, almost 37,500 new apps were released. Almost same or better is the situation at Apple App Store (that hosts apps for iPhone, iPad, etc.).

                                          Ref: http://www.appbrain.com/stats/number-of-android-apps

One may argue that CS or other degree programs focus on theoretical underpinning of computer science, instead particular type of development skill. But I believe, in countries (like Pakistan), not much grads join research career, but industry. So we should skill them in something that could greatly help them in development career. I believe, If they would be skilled in such technologies, they can also do freelancing projects during their study, as huge number of mobile apps development projects are open for bidding.

So from my experience and study of current market demand of mobile apps development. I have some suggestions or ideas:
  1. Just like web application development (aka Web Engineering), universities may offer Mobile Apps Development course, might be as an elective.
  2. If separate course is not possible, mobile app development can be integrated in some other course (e.g. Web Engineering, Software Engineering, etc.). all what is needed is 5-8 weeks of teaching with labs.
  3. University may offer it as workshop style course. Just 3 to 4, two hours workshops should be enough, followed by a project.
All what it need is willingness and very little resources i.e. a non conflicting time slot and arranging a trainer who have mobile apps development experience of 3-4 years.

My whole motivation is, we should equip our youth (specially IT grads) with skills so that they can compete in freelance market, which is open for every body. Current Pakistan share is very less compared to other countries, which can be improved a lot by such efforts.