Monday, October 13, 2008

Object Orientation (Chap-2) goes smoothly as well.

Object Orientation goes smoothly as well.

Cool. It didn't take much time to complete the chapter. It was

interesting. Nothing new was there, but was testing the awareness

around java world. Exam was good i think for chapter 2. I scored 11

out of 14. Chapter 3 looks lenghty but got a week to do it. So

chill out.

Monday, October 6, 2008

Chap1: Declaration and access control

Many of my new book kick off lasted for first chapter only. For example when I started reading “hibernate in action“, “webwork in action“, “ejb in action”, I was hardly able to close first chapter. But this time I’m firm. More determinant than ever. My other blog (http://abhi-java.blogspot.com) is also starving of new article.

As the names suggest the whole chapter was about pretty simple basic java stuff. But guess what? My test was horrible. I could solve only 5 out of 10 questions correctly. Anyways next chapter is due by coming Monday. So I got 2.5 days to finish the chapter. By finish I don’t mean to go through all pages but going through them from top to bottom At least next exam should score at least 80%.

Friday, July 18, 2008

Java refactoring Part-3

The creation of a good mental model is one of the key challenges in developing software. One way to build this model is by giving good names to your code. People should code not only for themselves but also for others as well.

I took interview yesterday for placement in my compnay. A saw the an answer given by a candidate as "Understanding code of others" in reply to the question " what do you hate most about software industry?".

Can you believe it how disgusting it feels when you read a bad code. Anyways not going further i've discussed some smells related names and refactoring for them in below presentation.


Click here to start presentation --> Measured Smells & Names

Java refactoring Part-2

The smells in this chapter are similar. They're dead easy to detect. They're
objective (once you decide on a way to count and a maximum acceptable score).
They're odious.

Click here to start presentation --> Measured Smells

Java Refactoring Part-1

Refactoring-the art of improving the design of existing code safely-provides an
efficient, reliable system for bringing order to the chaos, and one that keeps
the surprises to a minimum!

Click Here to start with first Presentation

Wednesday, May 7, 2008

HSQLDB and Ant

Wohh!! It’s been a long time with my application. I must say i’m too lazy for all these stuff. First think I really hate right now is that I missed my deadlines for Agile Project. But that’s because of some deadlines at office and some at home ;-).

Anyways, getting back to work. I’ve started to realize the power of ANT after starting my database with it as well as creating all tables with it as well. And guess what I was as easy as putting knife on butter.

An Overview of Object-Relational Mapping (ORM)
Majority of software application uses database to store application related information. One way to perform this storage related task is writing EJBs for storage where we map object with our Bean class. But this will only be the choice if I’m asked to work in distributed environment or I need more secure way of storing data.

ORM basically map database field with simple POJO. Although I have to still provide mapping between POJO and database field. This is typically done out side in xml file. Hibernate is one such ORM, which will be used for this project.

HSQLDB
HSQLDB is lightweight java database engine.

I’ve installed db on my workstation and copied hsqldb.jar in my lib folder. Next think

1. I would be doing is to start server.








classname="${hclass}" classpath="${hjar}"
args="${hfile} -dbname.0 ${halias} -port ${hport}"/>


This is from where my view about ANT started getting credited. The execution of above script will start my server on port 9005, which is default port for hsqldb server engine.

2. Now let’s create DB and insert some records with ANT script. I’ve not covered or questioned about DB design as I’m just trying going through sam’s application. I’ll cover all things in my Next application that will be designed and developed by only me.
Below is how my executeddl script looks like,


driver="org.hsqldb.jdbcDriver"
url="jdbc:hsqldb:hsql://localhost:${hport}/${halias}"
userid="sa" password=""
print="yes">
-- SQL script for TimeX
-- Step 1: Drop objects if they exist
DROP TABLE Department IF EXISTS;
DROP TABLE Employee IF EXISTS;
DROP TABLE Timesheet IF EXISTS;
DROP INDEX TimesheetIndex IF EXISTS;
DROP INDEX DepartmentCodeIndex IF EXISTS;
DROP INDEX EmployeeIdIndex IF EXISTS;

-- Step 2: Create tables
CREATE TABLE Department
(
departmentCode CHAR(2) NOT NULL,
name VARCHAR(255) NOT NULL
);

CREATE TABLE Employee
(
employeeId INT NOT NULL,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL,
employeeCode CHAR(1) NOT NULL,
password VARCHAR(10) NOT NULL,
managerEmployeeId INT NULL
);

CREATE TABLE Timesheet
(
timesheetId IDENTITY NOT NULL,
employeeId INT NOT NULL,
statusCode CHAR(1) NOT NULL,
periodEndingDate DATE NOT NULL,
departmentCode CHAR(4) NOT NULL,
minutesMon INT NULL,
minutesTue INT NULL,
minutesWed INT NULL,
minutesThu INT NULL,
minutesFri INT NULL,
minutesSat INT NULL,
minutesSun INT NULL
);

-- Step 3: Create indexes
CREATE UNIQUE INDEX TimesheetIndex ON Timesheet (employeeId, periodEndingDate);
CREATE UNIQUE INDEX DepartmentCodeIndex ON Department (departmentCode);
CREATE UNIQUE INDEX EmployeeIdIndex ON Employee (employeeId);

-- Step 4: Insert some reference and test data
INSERT INTO Department (departmentCode, name)
VALUES ('AC', 'Accounting');
INSERT INTO Department (departmentCode, name)
VALUES ('CS', 'Customer Support');
INSERT INTO Department (departmentCode, name)
VALUES ('HR', 'Human Resources');
INSERT INTO Department (departmentCode, name) VALUES ('IT', 'Information Technology');

INSERT INTO Employee (employeeId, name, employeeCode,
password, email, managerEmployeeId)
VALUES (1, 'Mike Dover', 'H', 'rapidjava', 'mdover@acme.com', 3);
INSERT INTO Employee (employeeId, name, employeeCode,
password, email, managerEmployeeId)
VALUES (2, 'Ajay Kumar', 'H', 'visualpatterns', 'akumar@acme.com', 3);
INSERT INTO Employee (employeeId, name, employeeCode,
password, email, managerEmployeeId)
VALUES (3, 'Teresa Walker', 'M', 'agilestuff', 'twalker@acme.com', 4);
INSERT INTO Employee (employeeId, name, employeeCode,
password, email)
VALUES (4, 'Tom Brady', 'E', 'superbowl', 'tbrady@acme.com');

INSERT INTO Timesheet(timesheetId, employeeId, statusCode, periodEndingDate,
departmentCode, minutesMon, minutesTue, minutesWed,
minutesThu, minutesFri, minutesSat, minutesSun)
VALUES (1, 2, 'P', '2006-08-19', 'IT', 480, 480, 360, 480, 480, 0, 0);
INSERT INTO Timesheet(timesheetId, employeeId, statusCode, periodEndingDate,
departmentCode, minutesMon, minutesTue, minutesWed,
minutesThu, minutesFri, minutesSat, minutesSun)
VALUES (2, 1, 'A', '2006-08-19', 'HR', 0, 0, 480, 480, 480, 0, 0);

-- Step 5: Verify tables and test data look ok
SELECT * FROM Department;
SELECT * FROM Employee;
SELECT * FROM Timesheet;



Damn!!! Can you believe it all these steps were straight forward! I got hurdle going thought them. And ya my database is created successfully. How do I know? Good question and the answer are verifying it by opening database UI.

Ya but when I tried writing the above Ant script with some changes in DB name for my own student storage program. I went red.


args="${hfile} -dbname.0 ${halias} -port ${hport}">


Server started successfully with above target.
But

driver="org.hsqldb.jdbcDriver"
password=""
url="jdbc:hsqldb:hsql://localhost:${hport}/${halias}}"
userid="sa"
print="yes">
DROP TABLE student IF EXISTS;
CREATE TABLE student
(
rollNo INT NOT NULL,
name VARCHAR(255) NOT NULL
);



This was really a headache for me.
I was getting error below.

BUILD FAILED
C:\Users\ABhi\workspace\Practice\Agile\Hibernate\build.xml:26: java.sql.SQLException: Database does not exists in statement [hibernatedbalias}]

After making changes in above script my script looked like something below and now it was working. I don’t see any changes between both of these but just for the record I’m writing it below.



DROP TABLE student IF EXISTS;
CREATE TABLE student
(
rollNo INT NOT NULL,
name VARCHAR(255) NOT NULL
);


3. Open UI Navigator for our DB.


classname="org.hsqldb.util.DatabaseManagerSwing" />

if you are some geek like our network admin(who actually loves to type everything manually rather than using ready made UI for the same task), I’ve other script for that.


classname="org.hsqldb.util.SqlTool" args="localhost-sa"/>


If you are facing any problem till this point please mail me at
abhishek.gondalia@gmail.com
So that I can reproduce the same problem(Just for sake of solving it.)

Wednesday, April 16, 2008

Sam’s Agile Application. MP & ANT


Sam’s Agile Application.

First thing I needed to decide was whether how many hours from my day life I would be able to spend after this application (Along with my busy schedule at office)?

I just realized not more than 2 and not less than 1. So there it goes.

Microsoft Project

I installed Microsoft Project today. Just going through estimation of chapters. I like the some of its features like

1. Creating project based on your own calendar. In my case I needed something just like that. My working times are not as per some office times so it allowed me to properly estimate them based on hours.

2. Other feature is Task and subtasks dependency. I can directly drag and drop task behind each other to set them up in proper order.

I still need to see some of the areas where I can use in it pair programming and how it helps in assigning project task to different people. Because on that bases only I can estimate task for team. Right now with only one member in project (that me) it was easy to finish of the Project estimation phase. But believe me it wasn’t that easy as it sounds here. Even Microsoft was bad at documenting every aspect of project. I find its Help content very poor. Ya but I won’t be better person to judge it here.

Anyways moving along.

ANT

I started working with Ant. I have eclipse IDE which comes with in built support for Ant features. But as I wanted to avoid the ready made programming with IDE for time being. I installed Ant on my PC. Things went well, especially documentation. I read through some of its basic tutorial pages. After messing with my Environment variable and PATH variable I finally managed to run in from my application folder. I created a simple java file and was able to build it as jar at the end of the day.

I wonder what it would have been without Ant before rise of IDEs. Believe me it would have been chaos. Ant makes life a simple. I remember my organization using this Ant build file when I was new to IT world. Still I’ve not created build.xml file on my own. My tomorrow’s target would be to create one which builds and application for me.

Thursday, April 3, 2008

TimeSheet Agile Application.


TimeSheet Agile Application.


Well, Being in industry and only working through daily stuff at office narrows your knowledge about other technology sometime. So I finally decided to try my hands on some other technology as well. I’ve worked on Spring before (Spring JMS API) it made me fall in love with Spring framework power. And it finally ended up in reaching to this application.


I always preferred learning any new technology from it book so first thing I’ve always done is to WASTE my time finding book related to the technology for quite sometime. Then with 400 to 500 pages in that book I’ll start my session with behind the scene phase of that book. And after a week or so I’ll end up in watching that book getting dirty inside my book self. Ouchhhh. That hurts, seriously, I’ve always been disappointed with my that approach.

So for the first time I want to reverse the procedure of accumulating my knowledge ‘well’. I came around this book “Sams.Agile.Java.Development.with.Spring.Hibernate.and.Eclipse.May.2006.pdf” by Anil Hemrajani and decided to give my hand to complete. One reason to write this blog is that at least I won’t like to waste my efforts that I’ve given in writing this blog. So I expect this project to complete. The project is regarding developing an application with the use of Hibernate, Spring and few other technology which includes Ant, JUnit, HSQLDB & Apache tomcat and most of all it’ll go through the software development process which will give me some idea(enrich my knowledge) about how to do it and which way to use to do it.

RULE 1:

NO HURRY NO WORRY!!!!

I’m not in any hurry to finish this project. Ya of course I’ll setup a dead line for this project but still I don’t want to get in to so much hurry that I’ve to skip some part of this project. So my project completion estimation is going to be on the unit of Days not hours(As I’ve personal & social life to deal with ha ha ha!!

I’ve already been through First few chapters of this book and it’s all about giving you idea on XP and AGILE methodology for development of this application. I’ve already gathered user requirements as part of process, though the requirement have been specified in the book itself.

The XP project life cycle

I’ll list out user requirements them first of all.

  • Hourly employees should be able to sign in to a web application (once or more each week) and enter their hours for each day of a given week.
  • Along with the hours, the employee must select which department the hours are being billed to.
  • Employees will be required to submit their timesheets each week.
  • An employee's manager is notified of successfully submitted timesheets. The manager must then approve or disapprove the timesheets.
  • After a timesheet is approved or disapproved, a notification is sent back to the employee indicating the updated status of the timesheet. If the timesheet is approved, an email is also sent to the accounting department to process the pay check for the given employee.
  • All users of Time Expression will have one or more relevant reports available to them.
  • A weekly reminder email will be sent out to employees who have not submitted their timesheets. Another reminder email is sent to managers who have employee timesheets pending approval.

Going through all these Use stories author has given priority for each user story as below.

Table: User Stories, Priorities, and Estimates for Our Sample Application

$$$

I don’t want to go in to detail about discussing the software development methodology used for this project as that will again switch my focus. Discussing them will be taken out as a totally separate activity in some other blog.

Following is the UI Diagram identified from user story:

$$$

First and foremost thing I’m doing right now is working out for project estimation for me.

PROJECT ESTIMATION:

Hardest thing I find during lifecycle of project is Project estimation. Actually I’m always worried about giving deadline and not meeting them. Reasons for not being able to meet deadline for me can be some of:

1. Estimations are not given by me.

2. When you expect me to work on two or three other tasks as well.

3. SAMAJ SEVA. (Helping others)

4. My own laziness. (Many times).

Anyways rather than giving my rough estimation about how I’ll go through given chapters, finally I’ve decided to get use to some tool for estimation. It doesn’t help me by much but still just as part of industry process I’ve decided to learn Microsoft Project for the same.

Wednesday, April 2, 2008

Spring JMS Template

It provides a template mechanism to hide the details of a typical JMS implementation so developers can concentrate on the actual task of processing messages instead of worrying about how to create, access, or clean up JMS resources.

Synchronous Messaging Service Vs. Asynchronous Messaging Service

Synchronous Messaging Service
1. Has to wait for service completion before starting another service or processing further.
2. Sometime its time consuming when message consumption takes much time.
Asynchronous Messaging Service
1. Does not have to wait for service to be completed. Another service can come which than can be sending in queue rather than waiting for first request to complete.
2. Can’t use in all application.

Two types of messaging:
* Point to Point
* Subscribe & Publish.

JMS
1. Similar to writing JDBC or JCA code
2. Boilerplate code to create or retrieve JMS resource objects that make the task more with more repetitive code.

Typical Process of using JMS:
1. Create JNDI initial context.
2. Get a queue connection factory from the JNDI context.
3. Get a Queue from the queue connection factory.
4. Create a Session object.
5. Create a sender or receiver object.
6. Send or receive a message using the sender or receiver object created in Step 5.
7. Close all of the JMS resources after processing the messages.

Terminology:

A JMS provider is a messaging system that implements the JMS interfaces and provides administrative and control features. An implementation of the J2EE 1.3 platform includes a JMS provider. Bea Weblogic supports JMS as one of its j2ee service.

JMS clients are the programs or components written in the JavaTM programming language that produce and consume messages. Thus both producer and consumer of the Queue or Topic are known as JMS clients

Messages are the objects that communicate information between JMS clients.

Administered objects are preconfigured JMS objects created by an administrator of the J2EE Application Server (e.g. Bea Weblogic or IBM’s Websphere) for the use of clients. There are two kinds of administered objects, destinations (Queue or Topic) and connection factories.

JMS producer sends messages to the Destinations to be consumed by the consumer. Destination can be either Queue or Topic.

SPRING JMS
1. Templates to hide detail of java API.
2. Spring provides the JMSTemplate class so developers don't have to write the boilerplate code for a JMS implementation.
Advantages:
• Provides JMS abstraction API to simplify use of destination (Queue/Topics) and publish message to specified destination.
• No need to deal with Exception as Spring provides unchecked exception for any JMS exception that is re-thrown in JMS code.
• Simple for using asynchronous messaging
Java Classes to use with JMS application.

1. JmsException
This is the base (abstract) class for any exceptions thrown by Spring framework whenever there is a JMS exception.
2. JmsTemplate & JmsTemplate102
These are helper classes used to simplify the use of JMS by handling the creation and release of JMS resources like connection factories, destinations, and sender/receiver objects. JmsTemplate102 is a subclass of JmsTemplate that uses the JMS 1.0.2 specification.

• To get started using JmsTemplate, need to know which JMS specification is supported by the JMS provider. E.g. JBoss AS 4.0.2 supports the JMS 1.0.2 specification.
• JMS 1.1 unifies the programming interfaces for PTP and (Pub/Sub) domains. With this developer can create transacted session, and receive a message from QUEUE (PTP) and send message to TOPIC (Pub/Sub) within the same JMS transaction.

Various methods to send & receive messages:

Send: Send a message to default or specified destination.

Receive: Receive a message from default or specified destination, but only wait for a specified time of delivery.

ConvertAndSend: delegates the conversation process to an instance of MessageConverter interface and then sends it to destination.

ReceiveAndConvert: Receives a message from default or specified destination and converts it to JavaObject.

3. MessageCreator
This is a callback interface used by the JmsTemplate class. It creates a JMS message for a specified session.
4. MessageConverter
This interface acts as an abstraction to convert between Java objects and JMS messages.

MessageConverter
The MessageConverter interface defines a contract to convert Java objects into JMS messages.
Application code can focus on the business objects and not bother with the inner details of how it's represented as a JMS message.
SimpleMessageConverter (and SimpleMessageConverter102) are default implementations of MessageConverter. They are used to convert a String to a JMS TextMessage, a byte array (byte[]) to a JMS BytesMessage, a Map to a JMS MapMessage, and a Serializable object to a JMS ObjectMessage, respectively. You can also write your own custom implementations of MessageConverter to convert XML documents into a TextMessage object using an XML binding framework such as JAXB, Castor, Commons Digester, XMLBeans, or XStream.

5. DestinationResolver
This is an interface used by JmsTemplate for resolving destination names. DynamicDestinationResolver and JndiDestinationResolver are the default implementations of this interface.

Destinations
Destinations are stored and retrieved using a JNDI context. While configuring a Spring application context, we use JndiObjectFactoryBean class to get reference to JMS destinations.
The DestinationResolver interface is used to resolve a destination name to JMS destination, which is used when application has lots of destinations.
DynamicDestinationResolver is used to resolve dynamic destinations.

Process:

1. First thing we need message queue to send and receive message. Configure it in jbossmq-wsc-jboss-service.xml file.


name="jboss.mq.destination:service=Queue,name=CreditRequestSendQueue">

jboss.mq:service=DestinationManager



2. Create new destinations with queue/CreditRequestSendQueue and queue/CreditRequestReceiveQueue.

3. JMS configuration:

4. JNDI context to get resource.





org.jnp.interfaces.NamingContextFactory


localhost


org.jnp.interfaces:org.jboss.naming





5. JMS Queue connection factory configuration.

class="org.springframework.jndi.JndiObjectFactoryBean">




UIL2ConnectionFactory



JndiObjectFactoryBean:
FactoryBean that looks up a JNDI object. It exposes object found in JNDI when used as bean reference. E.g “dataSource”
Register this as singleton factory in an application context.

6. Configuration for send & receive Destination

class="org.springframework.jndi.JndiObjectFactoryBean">




queue/CreditRequestSendQueue



7. JMS Template configuration

class="org.springframework.jms.core.JmsTemplate102">







30000



8. JMS Sender & Receiver configuration















9. Testing:

public void send() {
try {
ClassPathXmlApplicationContext appContext = new
ClassPathXmlApplicationContext(new String[] {
"spring-jms.xml"});

System.out.println("Classpath loaded");

JMSSender jmsSender = (JMSSender)appContext.getBean("jmsSender");

jmsSender.sendMesage();

System.out.println("Message sent using Spring JMS.");
} catch(Exception e) {
e.printStackTrace();
}
}