About Me

My photo
"Enoughtheory.com" had its humble beginning in the year 2011 by ( Founder of Enoughtheory.com ) Mr Ravi Kant Soni , an Enterprise Java and Spring Framework Specialist, with a bachelor degree (B.E) in Information Science and Engineering from Reva Institute of Technology at Bangalore. He has been into the software development discipline for many years now. Ravi has worn many hats throughout his tenure, ranging from software development, designing multi-tenant applications, integration of new technology into an existing system, to his current love of writing a Spring Framework book. Currently, he is a lead engineer at HCL Technology. Ravi has focused on Web and Enterprise development using Spring Framework for most of his career and has been extensively involved in application design and implementation. He has developed applications for Core-Bank, HR and Payroll System, and e-Commerce systems using Spring Framework. Ravi Kant Soni is author of book "Learning Spring Application development" http://learningspringapplicationdevelopment.com

Wednesday 28 November 2012

J2EE Scheduler

Schedule-based execution in a J2EE Web Application

 
Schedule-based execution in a J2EE Web Application.
 
Scheduled tasks fall into two categories:
  • System level task, such as system backup. Usually, it is done by system administrators or operators at data center.
  • Application level, such as business report. Usually, this is the responsibilities of business units.
Usually, your application server is in your data center or at a hosting company. You want to control application tasks at your office on a client machine. Different departments want to manage their own tasks. For example, warehouses run inventory checking tasks while sales run sale analysis tasks. If anything goes wrong at the system level (for example database is down), the scheduler should send alert notifications to the administrator on duty. If you run scheduled business patrol tasks and find an abnormal condition at business level, the scheduler should send alarm notifications to the people in charge. All notifications should be handled by the scheduler automatically.

All the above issues require scheduler to support distributed computing environment with the following features:
  • The scheduler can run on any machine in the network at any time.
  • The scheduler can be run from data center and offices simultaneously.
  • The scheduled task should run once and only once at the scheduled time, regardless of how many of the schedulers are running.
  • Missed tasks can be detected and alerted. 

 

Vertical Partitioning in DataBase -- Benifits

Vertical partitioning

 
Suppose we have a table with many columns and also millions of rows. Some of the columns in the table are very frequently accessed in some queries, and most of the columns in the table are less frequently accessed in some other queries.

As the table size is huge (in terms of number of columns and rows), any data retrieval query from the table performs slowly. So, this table could be portioned based on the frequency of access of the columns. That is, we can split the table into two or more tables (partitions) where each table would contain a few columns from the original tables.

 In our case, a partition of this table should contain the columns that are frequently accessed by queries, and another partition of this table should contain the columns that are less frequently accessed by other queries. Splitting the columns vertically and putting them in different thinner partitions is called vertical partitioning.

Another good way for applying vertical partitioning could be to partition the indexed columns and non-indexed columns into separate tables. Also, vertical partitioning could be done by splitting LOB or VARCHARMAX columns into separate tables.

Like horizontal partitioning, vertical partitioning also allows to improve query performance (because queries now have to scan less data pages internally, as the other column values from the rows have been moved to another table), but this type of partitioning is to be done carefully, because if there is any query that involves columns from both partitions, then the query processing engine would require joining two partitions of the tables to retrieve data, which in turn would degrade performance.

Tuesday 27 November 2012

Working With Time Zones

my server's 9PM is probably not your 9PM

ColdFusion And Java

JRE (Java Runtime Environment) that powers ColdFusion has the latest version of the Olson Timezone Database. This database provides encapsulated logic for each timezone such that we don't have to kill ourselves trying to manage all the rules and applications.
 
This timezone database can be accessed using the java.util.TimeZone class. Each timezone is referenced by an ID that is specific to a location, timezone, and daylight savings time (DST) combination.
 
The java.util.TimeZone class encapsulates the logic surrounding the GMT (Greenwich Mean Time) and DST (Daylight Savings Time) rules while the java.util.GregorianCalendar class allows us to navigate through dates and times in the given timezone.
 
Mapping date/time to a database when using different time zones, requires some thought. It all looks very simple to begin with but I've seen a lot of silly mistakes being made...  
 
There are basically two distinct kind of requirements when working with time zones:
  • Normalize to a common time - preferably UTC.
  • Keep the original time and time zone information.
The first case can be applied in most situations. As an example consider that we want to create visibility of the whereabouts of a mailed parcel on a global trip. It is sufficient to register each event in UTC and show it to users in their own local time.
  
The second case applies for example when we want to preserve the time and time zone as communicated by someone. E.g. a customer in New York talking to support in London for a Service hosted in Brussels. The support person should communicate with the customer relative to his time zone: "You reported a service error today at 9:30 AM and yesterday at 9:15 AM". We could deduce the customer's time zone from his location - but perhaps he normally works from Los Angeles instead of New York. A conversation a few weeks later reminding him of the problem he reported as "the 6:15 AM incident" would be utterly confusing.

Time in different time zones
Date   Europe/Brussels   America/New York   London
March 13, 2009   15:46   10:46   14:46
  

 Practical Solution

What I propose is to keep all the time data in your database in UTC instead. This has a few advantages:
  • The times in the database can be compared, visually and in SQL WHERE clauses.
  • Using Java, you don't have to do any conversions when reading or writing to the database.
  • When changing DST , values don't jump when transitioning to summer or winter time.
manual interventions (mainly INSERT and UDPDATE) should take into account that UTC must be used, not local time

 Let's illustrate that with a concrete example:
Mapping dates normalized to UTC (using java.util.Date)
Mapping dates normalized to UTC (using java.util.Date) 
 
A user John in New York enters a date/time for a planned teleconference with his colleague Mark in Brussels. He types 2009-07-06 09:30 , the application parses that to a Date - containing a long value of 1246887000000. This Date represents 14:30 UTC . It is inserted as such in the database.
 
On the other side of the Atlantic ocean, Mark checks the date of the planned meeting, the application reads the date from the database - it still represents 14:30 UTC and contains the same long value of 1246887000000. Mark's session contains a formatter that formats this date to 2009-07-06 15:30
 
 
The basic point is that each user's session contains a SimpleDateFormat , configured to the time zone of that particular user and parses or formats localized string representations of the actual (UTC) date in the database.
 
 Library Classes
The java.util package has a few classes for working with time.
 
Date
java.util.Date is a wrapper for a long value that corresponds with the number of milliseconds since January 1, 1970, 00:00:00 UTC. You can obtain the current time using new Date() or System.out.currentTimeMillis() .  
 
We make one Date, and use SimpleDateFormat to render the date in the context of a particular time zone.
  
long time = 1000*60*60*24*23;
Date date = new Date(time);

TimeZone brusselsTZ = TimeZone.getTimeZone("Europe/Brussels");
TimeZone newYorkTZ = TimeZone.getTimeZone("America/New_York");

SimpleDateFormat formatterNY = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat formatterBR = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

formatterNY.setTimeZone(newYorkTZ);
formatterBR.setTimeZone(brusselsTZ);

System.out.print("New York: ");
System.out.println(formatterNY.format(date));
//New York: 1970-01-23 19:00:00.000
System.out.print("Brussels: ");
System.out.println(formatterBR.format(date));
//Brussels: 1970-01-24 01:00:00.000
 

TimeZone   

A standard Java install contains all time zone information, it is maintained for all timezones and gets updates - as long as you apply them.
 

Calendar   

GregorianCalendar.
 
Calendar calendar = new GregorianCalendar();
//calendar.setTime(date);
//calendar.setTimeInMillis(time);

calendar.set(2009, Calendar.AUGUST, 21);//Gotcha: months are 0-based, January == 0, December == 11
calendar.add(Calendar.DATE, 28);
System.out.println(formatterBR.format(calendar.getTime()));

//The time part was the time when new GregorianCalendar() was executed
//2009-09-18 13:12:53.341

 Database support for timezones

Databases have some support for working with date/time values taking into account the existence of timezones. Most support is focused on interpreting and showing date/time in the timezone of the 'user' or connection. The fact that in a typical architecture, database connections are shared between application users, changing timezones per connection is not a feasible approach
 
PostgreSQL has one datatype, TIMESTAMP , that contains date and time data. Two datatypes can be combined with timezone data: TIMESTAMP and TIME, but in accordance with the first remark above, this last one is rather problematic.
 
Oracle supports TIMESTAMP WITH TIME ZONE and TIMESTAMP WITH LOCAL TIME ZONE that enable input and output taking time zones into consideration.
TIMESTAMP WITH TIME ZONE includes a time zone offset in its - literal - value. The data is stored as UTC with an offset. Someone in Brussels or New York will see the same date/time/time zone information.
 '2009-07-15 8:27:00 US/Pacific'
 '2009-12-15 15:33:00 -6:00'
TIMESTAMP WITH LOCAL TIME ZONE includes an implicit time zone offset in its value . The data stored in the database is normalized to the database time zone, the offset is not stored
 
MySQL stores date/time data in UTC and interpretes input depending on the current timezone of the host, server or connection depending on configurations.
    
MySQL has two built in datatypes that contain date and time data: DATETIME and TIMESTAMP. Neither contains timezone information.
Conversions between timezones can be done with the function CONVERT_TZ
 SELECT CONVERT_TZ('2009-12-01 10:25','+00:00','-6:00')
 SELECT CONVERT_TZ('2009-12-01 10:25','UTC','Europe/Brussels')
 

MySQL Timezone Create Table SQL Script

MySQL Timezone Create Table SQL Script

 
CREATE TABLE `timezones` (
`id` tinyint(3) unsigned NOT NULL auto_increment,
`timezone_location` varchar(30) NOT NULL default '',
`gmt` varchar(11) NOT NULL default '',
`offset` tinyint(2) NOT NULL default '0',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=143 ;


--
-- Dumping data for table `timezones`
--


INSERT INTO `timezones` VALUES (1, 'International Date Line West', '(GMT-12:00)', -12),
(2, 'Midway Island', '(GMT-11:00)', -11),
(3, 'Samoa', '(GMT-11:00)', -11),
(4, 'Hawaii', '(GMT-10:00)', -10),
(5, 'Alaska', '(GMT-09:00)', -9),
(6, 'Pacific Time (US & Canada)', '(GMT-08:00)', -8),
(7, 'Tijuana', '(GMT-08:00)', -8),
(8, 'Arizona', '(GMT-07:00)', -7),
(9, 'Mountain Time (US & Canada)', '(GMT-07:00)', -7),
(10, 'Chihuahua', '(GMT-07:00)', -7),
(11, 'La Paz', '(GMT-07:00)', -7),
(12, 'Mazatlan', '(GMT-07:00)', -7),
(13, 'Central Time (US & Canada)', '(GMT-06:00)', -6),
(14, 'Central America', '(GMT-06:00)', -6),
(15, 'Guadalajara', '(GMT-06:00)', -6),
(16, 'Mexico City', '(GMT-06:00)', -6),
(17, 'Monterrey', '(GMT-06:00)', -6),
(18, 'Saskatchewan', '(GMT-06:00)', -6),
(19, 'Eastern Time (US & Canada)', '(GMT-05:00)', -5),
(20, 'Indiana (East)', '(GMT-05:00)', -5),
(21, 'Bogota', '(GMT-05:00)', -5),
(22, 'Lima', '(GMT-05:00)', -5),
(23, 'Quito', '(GMT-05:00)', -5),
(24, 'Atlantic Time (Canada)', '(GMT-04:00)', -4),
(25, 'Caracas', '(GMT-04:00)', -4),
(26, 'La Paz', '(GMT-04:00)', -4),
(27, 'Santiago', '(GMT-04:00)', -4),
(28, 'Newfoundland', '(GMT-03:30)', -3),
(29, 'Brasilia', '(GMT-03:00)', -3),
(30, 'Buenos Aires', '(GMT-03:00)', -3),
(31, 'Georgetown', '(GMT-03:00)', -3),
(32, 'Greenland', '(GMT-03:00)', -3),
(33, 'Mid-Atlantic', '(GMT-02:00)', -2),
(34, 'Azores', '(GMT-01:00)', -1),
(35, 'Cape Verde Is.', '(GMT-01:00)', -1),
(36, 'Casablanca', '(GMT)', 0),
(37, 'Dublin', '(GMT)', 0),
(38, 'Edinburgh', '(GMT)', 0),
(39, 'Lisbon', '(GMT)', 0),
(40, 'London', '(GMT)', 0),
(41, 'Monrovia', '(GMT)', 0),
(42, 'Amsterdam', '(GMT+01:00)', 1),
(43, 'Belgrade', '(GMT+01:00)', 1),
(44, 'Berlin', '(GMT+01:00)', 1),
(45, 'Bern', '(GMT+01:00)', 1),
(46, 'Bratislava', '(GMT+01:00)', 1),
(47, 'Brussels', '(GMT+01:00)', 1),
(48, 'Budapest', '(GMT+01:00)', 1),
(49, 'Copenhagen', '(GMT+01:00)', 1),
(50, 'Ljubljana', '(GMT+01:00)', 1),
(51, 'Madrid', '(GMT+01:00)', 1),
(52, 'Paris', '(GMT+01:00)', 1),
(53, 'Prague', '(GMT+01:00)', 1),
(54, 'Rome', '(GMT+01:00)', 1),
(55, 'Sarajevo', '(GMT+01:00)', 1),
(56, 'Skopje', '(GMT+01:00)', 1),
(57, 'Stockholm', '(GMT+01:00)', 1),
(58, 'Vienna', '(GMT+01:00)', 1),
(59, 'Warsaw', '(GMT+01:00)', 1),
(60, 'West Central Africa', '(GMT+01:00)', 1),
(61, 'Zagreb', '(GMT+01:00)', 1),
(62, 'Athens', '(GMT+02:00)', 2),
(63, 'Bucharest', '(GMT+02:00)', 2),
(64, 'Cairo', '(GMT+02:00)', 2),
(65, 'Harare', '(GMT+02:00)', 2),
(66, 'Helsinki', '(GMT+02:00)', 2),
(67, 'Istanbul', '(GMT+02:00)', 2),
(68, 'Jerusalem', '(GMT+02:00)', 2),
(69, 'Kyev', '(GMT+02:00)', 2),
(70, 'Minsk', '(GMT+02:00)', 2),
(71, 'Pretoria', '(GMT+02:00)', 2),
(72, 'Riga', '(GMT+02:00)', 2),
(73, 'Sofia', '(GMT+02:00)', 2),
(74, 'Tallinn', '(GMT+02:00)', 2),
(75, 'Vilnius', '(GMT+02:00)', 2),
(76, 'Baghdad', '(GMT+03:00)', 3),
(77, 'Kuwait', '(GMT+03:00)', 3),
(78, 'Moscow', '(GMT+03:00)', 3),
(79, 'Nairobi', '(GMT+03:00)', 3),
(80, 'Riyadh', '(GMT+03:00)', 3),
(81, 'St. Petersburg', '(GMT+03:00)', 3),
(82, 'Volgograd', '(GMT+03:00)', 3),
(83, 'Tehran', '(GMT+03:30)', 3),
(84, 'Abu Dhabi', '(GMT+04:00)', 4),
(85, 'Baku', '(GMT+04:00)', 4),
(86, 'Muscat', '(GMT+04:00)', 4),
(87, 'Tbilisi', '(GMT+04:00)', 4),
(88, 'Yerevan', '(GMT+04:00)', 4),
(89, 'Kabul', '(GMT+04:30)', 4),
(90, 'Ekaterinburg', '(GMT+05:00)', 5),
(91, 'Islamabad', '(GMT+05:00)', 5),
(92, 'Karachi', '(GMT+05:00)', 5),
(93, 'Tashkent', '(GMT+05:00)', 5),
(94, 'Chennai', '(GMT+05:30)', 5),
(95, 'Kolkata', '(GMT+05:30)', 5),
(96, 'Mumbai', '(GMT+05:30)', 5),
(97, 'New Delhi', '(GMT+05:30)', 5),
(98, 'Kathmandu', '(GMT+05:45)', 5),
(99, 'Almaty', '(GMT+06:00)', 6),
(100, 'Astana', '(GMT+06:00)', 6),
(101, 'Dhaka', '(GMT+06:00)', 6),
(102, 'Novosibirsk', '(GMT+06:00)', 6),
(103, 'Sri Jayawardenepura', '(GMT+06:00)', 6),
(104, 'Rangoon', '(GMT+06:30)', 6),
(105, 'Bangkok', '(GMT+07:00)', 7),
(106, 'Hanoi', '(GMT+07:00)', 7),
(107, 'Jakarta', '(GMT+07:00)', 7),
(108, 'Krasnoyarsk', '(GMT+07:00)', 7),
(109, 'Beijing', '(GMT+08:00)', 8),
(110, 'Chongqing', '(GMT+08:00)', 8),
(111, 'Hong Kong', '(GMT+08:00)', 8),
(112, 'Irkutsk', '(GMT+08:00)', 8),
(113, 'Kuala Lumpur', '(GMT+08:00)', 8),
(114, 'Perth', '(GMT+08:00)', 8),
(115, 'Singapore', '(GMT+08:00)', 8),
(116, 'Taipei', '(GMT+08:00)', 8),
(117, 'Ulaan Bataar', '(GMT+08:00)', 8),
(118, 'Urumqi', '(GMT+08:00)', 8),
(119, 'Osaka', '(GMT+09:00)', 9),
(120, 'Sapporo', '(GMT+09:00)', 9),
(121, 'Seoul', '(GMT+09:00)', 9),
(122, 'Tokyo', '(GMT+09:00)', 9),
(123, 'Yakutsk', '(GMT+09:00)', 9),
(124, 'Adelaide', '(GMT+09:30)', 9),
(125, 'Darwin', '(GMT+09:30)', 9),
(126, 'Brisbane', '(GMT+10:00)', 10),
(127, 'Canberra', '(GMT+10:00)', 10),
(128, 'Guam', '(GMT+10:00)', 10),
(129, 'Hobart', '(GMT+10:00)', 10),
(130, 'Melbourne', '(GMT+10:00)', 10),
(131, 'Port Moresby', '(GMT+10:00)', 10),
(132, 'Sydney', '(GMT+10:00)', 10),
(133, 'Vladivostok', '(GMT+10:00)', 10),
(134, 'Magadan', '(GMT+11:00)', 11),
(135, 'New Caledonia', '(GMT+11:00)', 11),
(136, 'Solomon Is.', '(GMT+11:00)', 11),
(137, 'Auckland', '(GMT+12:00)', 12),
(138, 'Fiji', '(GMT+12:00)', 12),
(139, 'Kamchatka', '(GMT+12:00)', 12),
(140, 'Marshall Is.', '(GMT+12:00)', 12),
(141, 'Wellington', '(GMT+12:00)', 12),
(142, 'Nuku''alofa', '(GMT+13:00)', 13);

Monday 22 October 2012

Eclipse - unit testing with JUnit in Java

JUnit is a simple Java testing framework to write tests for you Java application. 

What is JUnit

JUnit is a simple open source Java testing
framework used to write and run repeatable automated tests. It is an
instance of the xUnit architecture for unit testing framework.
Eclipse supports creating test cases and running test suites, so it
is easy to use for your Java applications.

JUnit features include:
  • Assertions for testing expected results
  • Test fixtures for sharing common test
    data
  • Test suites for easily organizing and
    running tests
  • Graphical and textual test runners

    What is a test case

    A test case is a class which holds a number
    of test methods. For example if you want to test some methods of a
    class Book you create a class BookTest which extends
    the JUnit TestCase class and place your test methods in there.

    How you write and run a simple test


  • Create
    a subclass of TestCase:



public class BookTest extends TestCase{ 
 //..
}





  1. Write
    a test method to assert expected results on the object under test:

Note: The naming convention for a test
method is testXXX()

public void testCollection() {
 Collection collection = new ArrayList();
 assertTrue(collection.isEmpty());
} 





  1. Write
    a suite() method that uses reflection to dynamically create a
    test suite containing all the testXXX() methods:



public static Test suite(){
 return new TestSuite(BookTest.class);
}






  1. Activate the JUnit view in Eclipse
    (Window > Show View > Other.. > Java > JUnit).





You
find the JUnit tab near the Package Explorer tab. You
can change the position of the tab by drag and drop it.





  1. Right click on the subclass of
    TestCase and choose Run > JUnit Test to run the
    test.

Using a test fixture


A test fixture is useful if you have two or
more tests for a common set of objects. Using a test fixture avoids
duplicating the test code necessary to initialize and cleanup those
common objects for each test.

To create a test fixture, define a setUp()
method that initializes common object and a tearDown() method
to cleanup those objects. The JUnit framework automatically invokes
the setUp() method before a each test is run and the
tearDown() method after each test is run.

The following test uses a test fixture:

public class BookTest2 extends TestCase {

    private Collection collection;

    protected void setUp() {
       collection = new ArrayList();
    }

    protected void tearDown() {
  collection.clear(); 
    }

    public void testEmptyCollection(){
  assertTrue(collection.isEmpty());
    }
}


Dynamic and static way of running single tests


JUnit supports two ways (static and dynamic)
of running single tests.
In static way you override the runTest()
method inherited form TestCase class and call the desired test case.
A convenient way to do this is with an anonymous inner class.
Note: Each test must be given a name, so
you can identify it if it fails.
TestCase test = new BookTest("equals test") {<br> public void runTest() {<br>       testEquals();<br>      }<br>};



The dynamic way to create a test case to be
run uses reflection to implement runTest. It assumes the name
of the test is the name of the test case method to invoke. It
dynamically finds and invokes the test method. The dynamic way is
more compact to write but it is less static type safe. An error in
the name of the test case goes unnoticed until you run it and get a
NoSuchMethodException. We leave the choice of which to use up
to you.

TestCast test = new BookTest(“testEquals”);


What is a TestSuite


If you have two tests and you’ll run them
together you could run the tests one at a time yourself, but you
would quickly grow tired of that. Instead, JUnit provides an object
TestSuite which runs any number of test cases together. The
suite method is like a main method that is specialized to run tests.
Create a suite and add each test case you
want to execute:
public static void suite(){<br> TestSuite suite = new TestSuite();<br> suite.addTest(new BookTest("testEquals"));<br> suite.addTest(new BookTest("testBookAdd"));<br> return suite;<br>}



Since JUnit 2.0 there is an even simpler way
to create a test suite, which holds all testXXX() methods. You only
pass the class with the tests to a TestSuite and it extracts the test
methods automatically.

Note: If you use this way to create a
TestSuite all test methods will be added. If you do not want all test
methods in the TestSuite use the normal way to create it.

Example:

public static void suite(){
 return new TestSuite(BookTest.class);
}


A little example


Create a new Java project named
JUnitExample.
Add a package
de.laliluna.tutorial.junitexample where you place the example
classes and a package test.laliluna.tutorial.junitexample
where you place your test classes.

The class Book

Create a new class Book in the
package de.laliluna.tutorial.junitexample.
Add two properties title of type
String and price of type double.
Add a constructor to set the two properties.
Provide a getter- and setter-method for each
of them.
Add a method trunk for a method
equals(Object object) which checks if the object is an
instance of the class Book and the values of the object are equal.
The method return a boolean value.
Note: Do not write the logic of the
equals(..) method, we do it after finish creating the test
method.
The following source code shows the class
Book.
public class Book {<br><br>    private String title;<br>    private double price;<br><br>    /**<br>     * Constructor <br>     * <br>     * @param title<br>     * @param price<br>     */<br>    public Book(String title,<br>                double price) {<br>        this.title = title;<br>        this.price = price;<br>    }<br><br>    /**<br>     * Check if an object is an instance of book<br>     * and the values of title and price are equal<br>     * then return true, otherwise return false<br>     */<br>    public boolean equals(Object object) {<br><br>        return false;<br>    }<br><br>    public double getPrice() {<br>        return price;<br>    }<br><br>    public void setPrice(double price) {<br>        this.price = price;<br>    }<br><br>    public String getTitle() {<br>        return title;<br>    }<br><br>    public void setTitle(String title) {<br>        this.title = title;<br>    }<br>}

The test case BookTest


Create a new test case BookTest in
the package test.laliluna.tutorial.junitexample
Right click on the package and choose
New > JUnit Test
Case
.
In the wizard
choose the methods stubs setUp(), tearDown() and
constructor().





The
following source code shows the class BookTest
public class BookTest extends TestCase {<br><br>    /**<br>     * setUp() method that initializes common objects<br>     */<br>    protected void setUp() throws Exception {<br>        super.setUp();<br>    }<br><br>    /**<br>     * tearDown() method that cleanup the common objects<br>     */<br>    protected void tearDown() throws Exception {<br>        super.tearDown();<br>    }<br><br>    /**<br>     * Constructor for BookTest.<br>     * @param name<br>     */<br>    public BookTest(String name) {<br>        super(name);<br>    }<br><br>}



Now we want to write a test for the
equals(..) method of the class Book. We provide three
private properties, book1, book2 and book3 of type Book.
private Book book1;<br>private Book book2;<br>private Book book3;



Within the setUp() method we
initializes the three properties with some values. Property book1 and
book3 are the same.

protected void setUp() throws Exception {
 super.setUp();
      book1 = new Book(“ES”, 12.99);
      book2 = new Book(“The Gate”, 11.99);
 book3 = new Book(“ES”, 12.99);
}





Within the tearDown() method we cleanup the
properties:

protected void tearDown() throws Exception {
 super.tearDown();
      book1 = null;
      book2 = null;
 book3 = null;
}





Now, add a test method testEquals()
to the test case. Within the method we use the assertFalse()
method of the JUnit framework to test if the return-value of the
equals(..) method is false, because book1 and book2 are not the same.
If the return-value is false the logic of the equals() method is
correct, otherwise there is a logical problem while comparing the
objects. We want to test if the method compares the objects correctly
by using the assertTrue() method. Book1 and Book3 are the same,
because both are an instance of the class Book and have the same
values.

The following source code shows the
testEquals() method:

public void testEquals(){
        assertFalse(book2.equals(book1));
        assertTrue(book1.equals(book1));
}





Writing the logic of the equals() method


We have finished the test and now we can add
the logic to the equals() method stub. Open the class Book and
add the logic to the equals() method. First we check if the
object given by the method is an instance of Book. Then
compare the properties title and price,
if they are equal return true.

public boolean equals(Object object) {<br> if (object instanceof Book) {<br>           Book book = (Book) object;<br>           return getTitle().equals(book.getTitle())<br>                   &amp;&amp; getPrice() == book.getPrice();<br>      }<br>      return false;<br>}


Create the suite() method


In order to run the test method testEquals()
add a method suite() to the class BookTest.
Note: You can also create a separate class
where you add the suite() method.
Within the method create a new instance of
TestSuite and use the method addTest(..) to add a test.
Here we use the dynamically way to add a test to a TestSuite.
The method looks like the follows:
public static Test suite(){<br>      TestSuite suite = new TestSuite();<br>      suite.addTest(new BookTest("testEquals"));<br> return suite;<br>}



Run the test


After finishing all test methods we want to
run the JUnit test case. Right mouse button on the class BookTest and
choose Run As > JUnit Test.
On the JUnit view (Menu Windows -> show
view) of Eclipse you can see how many runs, errors and failures
occurred.






Thursday 30 August 2012

Pass by Reference vs. Pass by Value

Say there is a variable at location 1200 with a value 123.

First we'll do call by value.

If we call a method and pass that variable as an argument, the compiler will find another location in memory, say 1700 and copy the contents/value of location 1200(123) to location 1700.
When the method starts executing it is given the location 1700 to work with. It can change the contents of location 1700 and never change the contents of 1200 where the variable's data started from. When the method returns, the contents of 1700 is destroyed to be used again by another method. The contents of 1200 is unchanged. It is still 123.

Now call by reference:

When the method is called it is given the location 1200 to work with. Now if the method changes the contents of location 1200, the original contents are changed. When the method returns the contents of 1200 will be as the method left it. The original value can be changed




Pass by Reference vs. Pass by Value

Most methods are passed arguments when they are called. An argument may be a constant or a
variable. For example, in the expression
Math.sqrt(33)
the constant 33 is passed to the sqrt() method of the Math class. In the expression
Math.sqrt(x)
the variable x is passed. This is simple enough, however there is an important but simple
principle at work here. If a variable is passed, the method receives a copy of the variable's value.
The value of the original variable cannot be changed within the method. This seems reasonable
because the method only has a copy of the value; it does not have access to the original variable.
This process is called pass by value.
However, if the variable passed is an object, then the effect is different. This idea is explored in
detail in this section. But first, let's clarify the terminology. For brevity, we often say things like,
"this method returns an object ...", or "this method is passed an object as an argument ...". As
noted earlier, this not quite true. More precisely, we should say,
this method returns a reference to an object ...
or
this method is passed a reference to an object as an argument ...
In fact, objects, per se, are never passed to methods or returned by methods. It is always "a
reference to an object" that is passed or returned.
The term "variable" also deserves clarification. There are two types of variables in Java: those
that hold the value of a primitive data type and those that hold a reference to an object. A
variable that holds a reference to an object is an "object variable" — although, again, the prefix
"object" is often dropped for brevity.
Returning to the topic of this section, pass by value refers to passing a constant or a variable
holding a primitive data type to a method, and pass by reference refers to passing an object
variable to a method. In both cases a copy of the variable is passed to the method. It is a copy of
the "value" for a primitive data type variable; it is a copy of the "reference" for an object variable.
So, a method receiving an object variable as an argument receives a copy of the reference to the
original object. Here's the clincher: If the method uses that reference to make changes to the
object, then the original object is changed. This is reasonable because both the original reference
and the copy of the reference "refer to" to same thing — the original object.
There is one exception: strings. Since String objects are immutable in Java, a method that is
passed a reference to a String object cannot change the original object. This distinction is also
brought out in this section.
Let's explore pass by reference and pass by value through a demo program (see Figure 1). As a
self-test, try to determine the output of this program on your own before proceeding. If
understood the preceding discussion and if you guessed the correct output, you can confidently
skip the rest of this section. The print statement comments include numbers to show the order of
printing.

1 public class DemoPassByReference
2 {
3 public static void main(String[] args)
4 {
5 // Part I - primitive data types
6 int i = 25;
7 System.out.println(i); // print it (1)
8 iMethod(i);
9 System.out.println(i); // print it (3)
10 System.out.println("-----------------");
11
12 // Part II - objects and object references
13 StringBuffer sb = new StringBuffer("Hello, world");
14 System.out.println(sb); // print it (4)
15 sbMethod(sb);
16 System.out.println(sb); // print it (6)
17 System.out.println("-----------------");
18
19 // Part III - strings
20 String s = "Java is fun!";
21 System.out.println(s); // print it (7)
22 sMethod(s);
23 System.out.println(s); // print it (9)
24 }
25
26 public static void iMethod(int iTest)
27 {
28 iTest = 9; // change it
29 System.out.println(iTest); // print it (2)
30 }
31
32 public static void sbMethod(StringBuffer sbTest)
33 {
34 sbTest = sbTest.insert(7, "Java "); // change it
35 System.out.println(sbTest); // print it (5)
36 }
37
38 public static void sMethod(String sTest)
39 {
40 sTest = sTest.substring(8, 11); // change it
41 System.out.println(sTest); // print it (8)
42 }
43 }
Figure 1. DemoPassByReference.java
This program generates the following output:
25
9
25
-----------------
Hello, world
Hello, Java world
Hello, Java world
-----------------
Java is fun!
fun
Java is fun!

DemoPassByReference is organized in three parts. The first deals with primitive data types,
which are passed by value. The program begins by declaring and int variable named i and
initializing it with the value 25 (line 6). The memory assignment just after line 6 is illustrated in
Figure 2a. The value of i is printed in line 7.
(a) (c)
25
i
25
i
9
iTest
(b)
25
i
25
iTest
(d)
25
i
Figure 2. Memory assignments for call-by-value example (int variables)
Then, the int variable is passed as an argument to a method called iMethod() (line 8). The
method is defined in lines 26-30. Within the method, a copy of i exists as a local variable named
iTest. The memory assignments just after iMethod() begins execution are shown in Figure
2b. Note that i and iTest are distinct: They are two separate variables that happen to hold the
same value. Within the method, the value is changed to 9 (line 28) and then printed again. Back
in the main() method the original variable is also printed again (line 9). Changing the passed
value in iMethod() had no effect on the original variable, and, so, the third value printed is the
same as the first.
Part II of the program deals with objects and object references. The pass-by-reference concept is
illustrated by the object variables sb and sbTest. In the main() method, a StringBuffer
object is instantiated and initialized with "Hello, world" and a reference to it is assigned to
the StringBuffer object variable sb (line 13).
The memory assignments for the object and the object variable are illustrated in Figure 3a. This
corresponds to the state of the sb just after line 13 in Figure 1. The object is printed in line 14. In
line 15, the sbMethod() method is called with sb as an argument. The method is defined in
lines 32-36. Within the method, a copy of sb exists as a local variable named sbTest. The
memory assignments just after the sbMethod() begins execution are shown in Figure 3b. Note
that sb and sbTest refer to the same object.

(a)
(c)
sb
Hello, world
sb
Hello, Java world
sbTest
(b)
sb
Hello, world
sbTest
(d)
sb
Hello, Java world
Figure 3. Memory assignments for call-by-reference example (StringBuffer objects)
In line 34, the object is modified using the insert() method of the StringBuffer class.
The method is called through the instance variable sbTest. The memory assignments just after
line 34 executes are shown in Figure 3c. After the sbMethod() finishes execution, control
passes back to the main() method and sbTest ceases to exist. The memory assignments just
after line 15 in Figure 1 are shown in Figure 3d. Note that the original object has changed, and
that the original object variable, sb, now refers to the updated object.
The scenario played out above, is a typical example of pass by reference. It demonstrates that
methods can change the objects instantiated in other methods when they are passed a reference to
the object as an argument. A similar scenario could be crafted for objects of any of Java's
numerous classes. The StringBuffer class is a good choice for the example, because
StringBuffer objects are tangible, printable entities. Other objects are less tangible (e.g.,
objects of the Random class); however, the same rules apply.
Part III of the program deals with strings. The String class is unlike other classes in Java
because String objects, once instantiated, cannot change. For completeness, let's walk through
the memory assignments for the String objects in the DemoPassByReferernce program.
A String object is instantiated in line 20 and a reference to it is assigned to the String object
variable s. The memory assignments at this point are shown in Figure 4a.

(a)
(c)
s
Java is fun!
s
sTest
(b)
s
Java is fun!
sTest
(d)
s
fun fun
Java is fun! Java is fun!
Figure 4. Memory assignments for call-by-reference example (String objects)
In line 22 the sMethod() is called with s as an argument. The method is defined in lines 38-
42. Within the method, a copy of s exists as a local variable named sTest. The memory
assignments just after the sMethod() begins execution are shown in Figure 4b. Note that s and
sTest refer to the same object. At this point, there is no difference in how memory was
assigned for the String or StringBuffer objects. However, in line 40, Java's unique
treatment of String objects surfaces. The substring() method of the String class is
called to extract the string "fun" from the original string. The result is the instantiation of a new
String object. A reference to the new object is assigned to sTest. The memory assignments
just after line 37 executes are shown in Figure 4c.
After the sMethod() finishes execution, control passes back to the main() method and
sTest ceases to exist. The memory assignments just after line 22 in Figure 1 are shown in
Figure 4d. Note that the original object did not change. The String object containing "fun" is
now redundant and its space is eventually reclaimed.

Friday 3 August 2012

Java v/s JavaScript

Here are some differences between the two languages:
  • Java is a statically typed language; JavaScript is dynamic.
  • Java is class-based; JavaScript is prototype-based.
  • Java constructors are special functions that can only be called at object creation; JavaScript "constructors" are just standard functions.
  • Java requires all non-block statements to end with a semicolon; JavaScript inserts semicolons at the ends of certain lines.
  • Java uses block-based scoping; JavaScript uses function-based scoping.
  • Java has an implicit this scope for non-static methods, and implicit class scope; JavaScript has implicit global scope.
Here are some features that I think are particular strengths of JavaScript:
  • JavaScript supports closures; Java can simulate sort-of "closures" using anonymous classes. (Real closures may be supported in a future version of Java.)
  • All JavaScript functions are variadic; Java functions are only variadic if explicitly marked.
  • JavaScript prototypes can be redefined at runtime, and has immediate effect for all referring objects. Java classes cannot be redefined in a way that affects any existing object instances.
  • JavaScript allows methods in an object to be redefined independently of its prototype (think eigenclasses in Ruby, but on steroids); methods in a Java object are tied to its class, and cannot be redefined at runtime.

Wednesday 25 July 2012

GROUP BY, HAVING, SUM, AVG, and COUNT(*)


Aggregation

You can use a SQL SELECT to aggregate data. Aggregation combines rows together and performs some operation on their combined values. Very common aggregations are COUNT, SUM, and AVG.
The simplest use of aggregations is to examine an entire table and pull out only the aggregations, with no other columns specified. Consider this SQL:
SELECT COUNT(*) as cnt
      ,SUM(sale_amount) as sumSales
      ,AVG(sale_amount) as avgSales
  FROM orders
If you have a very small sales order table, say about 7 rows, like this:
ORDER |  DATE      | STATE | SALE_AMOUNT
------+------------+-------+-------------
 1234 | 2007-11-01 | NY    |       10.00
 1235 | 2007-12-01 | TX    |       15.00
 1236 | 2008-01-01 | CA    |       20.00
 1237 | 2008-02-01 | TX    |       25.00
 1238 | 2008-03-01 | CA    |       30.00
 1237 | 2008-04-01 | NY    |       35.00
 1238 | 2008-05-01 | NY    |       40.00
Then the simple query above produces a one-row output:
CNT  | SUM  | AVG
-----+------+-----
  7  | 175  |  25

Some Notes on The Syntax

When we use COUNT(*) we always put the asterisk inside.
Note that the example names the output columns by saying "as sumSales" and "as avgSales". This is important because without it we will get whatever the database server decides to call it, which will vary from platform to platform, so it is a good idea to learn to use the "AS" clause.

The WHERE Clause Filters BEFORE the Aggregation

If you want to get just the sales from New York state, you can put a WHERE clause in:
SELECT COUNT(*) as cnt
      ,SUM(sale_amount) as sumSales
      ,AVG(sale_amount) as avgSales
  FROM orders
 WHERE state = 'NY'
...and you will get only the results for NY:
CNT | SUM  | AVG
----+------+----------
  3 |  85  |  28.33333
Notice of course that the average has a repeating decimal. Most databases have a ROUND function of some sort, so I can correct that with:
SELECT COUNT(*) as cnt
      ,SUM(sale_amount) as sum
      ,ROUND(AVG(sale_amount),2) as avg
  FROM orders
 WHERE state = 'NY'
...and get:
CNT | SUM  | AVG
----+------+----------
  3 |  85  |  28.33

The Fun Begins With GROUP BY

The query above is fine, but it would be very laborious if you had to issue the query (or write a program to do it) for every possible state. The answer is the GROUP BY clause. The GROUP BY clause causes aggregations to occur in groups (naturally) for the columns you name.
SELECT state,
      ,COUNT(*) as cnt
      ,SUM(sale_amount)          as sumSales
      ,ROUND(AVG(sale_amount),0) as avgSales
  FROM orders
 GROUP BY state
Which gives us this result:
STATE | CNT | SUM  | AVG
------+-----+------+----
NY    |  3  |  85  |  28
TX    |  2  |  40  |  20
CA    |  2  |  50  |  25  

Every Column a GROUP BY or Aggregate

When you use the GROUP BY column then every column in the output must either be a group by column or must be an aggregate function. To understand this, imagine we put "Date" into the query above:
SELECT state,
     , date -- huh?? which value should we get??
     , COUNT(*) as cnt
     , SUM(sale_amount)          as sumSales
     , ROUND(AVG(sale_amount),0) as avgSales
  FROM orders
 GROUP BY state
Several states have more than one row in the database, so the database server has to decide which value of DATE to give you. Since it cannot know which one you want, it throws an error and says in short, "don't confuse me!"

Two More Aggregations, MIN and MAX

If we think again about the DATE column, in most practical situations we usually want to know the smallest or largest value, or both, so this query is not uncommon:
SELECT state,
     , MIN(date)                 as minDate
     , MAX(date)                 as maxDate
     , COUNT(*)                  as cnt
     , SUM(sale_amount)          as sumSales
     , ROUND(AVG(sale_amount),0) as avgSales
  FROM orders
 GROUP BY state
which yields:
STATE | minDate    | maxDate    |CNT | SUM  | AVG
------+------------+------------+----+------+-----
NY    | 2007-11-01 | 2008-05-01 | 3  |  85  |  28
TX    | 2007-12-01 | 2008-02-01 | 2  |  40  |  20
CA    | 2008-01-01 | 2008-03-01 | 2  |  50  |  25  

HAVING Clause is Like WHERE after GROUP BY

The HAVING clause lets us put a filter on the results after the aggregation has taken place. If your Sales Manager wants to know which states have an average sale amount of $25.00 or more, then the query would look like this:
SELECT state,
      ,COUNT(*) as cnt
      ,SUM(sale_amount)          as sumSales
      ,ROUND(AVG(sale_amount),0) as avgSales
  FROM orders
 GROUP BY state
HAVING AVG(sale_amount) >= 25
Which gives us this result, notice that Texas is now missing, as they were just not selling big enough orders (sorry 'bout that Rhonda).
STATE | CNT | SUM  | AVG
------+-----+------+----
NY    |  3  |  85  |  28
CA    |  2  |  50  |  25  

When to use WHERE, When to use HAVING

Then the Sales Manager might come down and say, 'I don't want the states who have no sales after December 2008'. We might automatically code the following, which is tragically wrong:
SELECT state,
     , MIN(date)                 as minDate
     , MAX(date)                 as maxDate
     , COUNT(*)                  as cnt
     , SUM(sale_amount)          as sumSales
     , ROUND(AVG(sale_amount),0) as avgSales
  FROM orders
 -- WRONG! Will filter out individual rows!
 WHERE date <= '2008-12-31'
 GROUP BY state
The problem here is that individual rows that happened after 2008-12-31 will get filtered out, which will give you all stats for all states on sales before 2009. That is not right. The idea is to completely eliminate all results for states with no sales in 2009 or later, even if they had sales before that time. So we use MAX and the HAVING clause:
SELECT state,
     , MIN(date)                 as minDate
     , MAX(date)                 as maxDate
     , COUNT(*)                  as cnt
     , SUM(sale_amount)          as sumSales
     , ROUND(AVG(sale_amount),0) as avgSales
  FROM orders
 GROUP BY state
HAVING MAX(date) >= '2008-12-31'

Using All Three

You can pull some pretty nice results out of a database in a single query if you know how to combine the WHERE, GROUP BY, and HAVING. If you have ever worked with a Sales Manager, you know they constantly want to know strange numbers, so let's say our Sales Manager says, "Can you tell me the average order size by state for all orders greater than 20? And don't bother with any average less 30.00" We say, "Sure, don't walk away, I'll print it out right now."
SELECT state
      ,COUNT(*)
      ,SUM(sale_amount) as sum
      ,ROUND(AVG(sale_amount) as avg
  FROM orders
 WHERE sale_amount > 20
 GROUP BY state
HAVING avg(sale_amount) >= 30
   AND max(date) >= '2008-12-31'

How to Do a Weighted Average

Consider the case of a table that lists test, homework and quiz scores for the students in a certain course. Each particular score is worth a certain percentage of a student's grade, and the teacher wants the computer to calculate each student's file score. If the table looks like:
STUDENT     | WEIGHT | SCORE
------------+--------+-------
NIRGALAI    |     40 |    90
NIRGALAI    |     35 |    95
NIRGALAI    |     25 |    85
JBOONE      |     40 |    80
JBOONE      |     35 |    95
JBOONE      |     25 |    70
PCLAYBORNE  |     40 |    70
PCLAYBORNE  |     35 |    80
PCLAYBORNE  |     25 |    90
Then we can accomplish this in one pull like so:
SELECT student
      ,SUM(weight * score) / 100 as final
  FROM scores
 GROUP BY student
The nice thing about this query is that it works even if data is missing. If a student missed a test, they automatically get a zero averaged in.

Database Normalization: First, Second, and Third Normal

What is Normalization in SQL ?

 What is normalization ?


Defination : Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored. There are several benefits for using Normalization in Database.
Benefits :
  1. Eliminate data redundancy
  2. Improve performance
  3. Query optimization
  4. Faster update due to less number of columns in one table
  5. Index improvement
There are diff. - diff. types of Normalizations form available in the Database. Lets see one by one.
1. First Normal Form (1NF)
 First normal form (1NF) sets the very basic rules for an organized database:
  • Eliminate duplicative columns from the same table.
  • Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).
    • Remove repetative groups
    • Create Primary Key

           
Name State Country Phone1 Phone2 Phone3
John 101 1 488-511-3258 781-896-9897 425-983-9812
Bob 102 1 861-856-6987    
Rob 201 2 587-963-8425 425-698-9684  
 PK
                 [ Phone Nos ]
   ?


?  
ID Name State Country Phone  
1 John 101 1 488-511-3258  
2 John 101 1 781-896-9897  
3 John 101 1 425-983-9812  
4 Bob 102 1 861-856-6987  
5 Rob 201 2 587-963-8425  
6 Rob 201 2 425-698-9684  
           

2. Second Normal Form (2NF)Second normal form (2NF) further addresses the concept of removing duplicative data:
·         Meet all the requirements of the first normal form.
·         Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
·         Create relationships between these new tables and their predecessors through the use of foreign keys.   
Remove columns which create duplicate data in a table and related a new table with Primary Key – Foreign Key relationship

ID Name State Country Phone


1 John 101 1 488-511-3258


2 John 101 1 781-896-9897


3 John 101 1 425-983-9812


4 Bob 102 1 861-856-6987


5 Rob 201 2 587-963-8425


6 Rob 201 2 425-698-9684


















ID Name State Country
PhoneID ID Phone
1 John 101  
1 1 488-511-3258
2 Bob 102
2 1 781-896-9897
3 Rob 201
3 1 425-983-9812





4 2 587-963-8425





5 3 587-963-8425





6 3 425-698-9684

3. Third Normal Form (3NF)
Third normal form (3NF) goes one large step further:
·         Meet all the requirements of the second normal form.
·         Remove columns that are not dependent upon the primary key.
  Country can be derived from State also… so removing country
  ID   Name   State   Country
  1   John    101       1
  2   Bob    102       1
  3   Rob    201       2

4. Fourth Normal Form (4NF)
Finally, fourth normal form (4NF) has one additional requirement:
·         Meet all the requirements of the third normal form.
·         A relation is in 4NF if it has no multi-valued dependencies.

If PK is composed of multiple columns then all non-key attributes should be derived from FULL PK only. If some non-key attribute can be derived from partial PK then remove it

The 4NF also known as BCNF NF

   TeacherID StudentID SubjectID  StudentName
     101   1001   1   John
     101   1002   2   Rob
     201   1002   3   Bob
     201   1001   2   Rob








   TeacherID    StudentID   SubjectID   StudentName
  101   1001   1          X
  101   1002   2          X
  201   1001   3          X
  201   1002   2         X