Cues-EJB3.0 Exceptions

This post consists the information of Exceptions in EJB perspective.We have written this post taking EJB Specifications as the reference.

Exceptions can be classified broadly into 3 categories.

  1. JVM Exceptions
  2. Application Exceptions
  3. System Exceptions

JVM Exceptions:These are the exceptions thrown by JVM.Nothing can be done when an JVM Exception occurs.Stop the application serverr and restart it once again.

Application Exceptions:It is nothing but a custom application defined by the application, thrown by the application.They denote that some business logic requirement is not met by the application.(Will be explained in detail with example)

System Exception:Most oftenly System exception as thrown as subclasses of the RunTime Exception by the JVM.Another type of system exception occurs when improperly configured resource is called/used.Examples of this type include using the JNDI resources with mispelt name etc.This kind of checked system exceptions must be caught and thrown as unchecked exceptions.

Thumb Rules :

1.Checked Exception is a subclass of Exception.We are forced by JVM to catch Checked Exceptions at compile time.

2.Unchecked exception is one that subclasses java.lang.RuntimeException. Subclassing java.lang.RuntimeException ensures you will not be forced by the compiler to catch the exception.

3.When we catch the exceptions don't swallow them ,throw them.

EJB3.0 Handling Exceptions:

EJB specification deals with handling two kinds of Exceptions .Application Exception and System Exception.

Application exceptions are defined in the methods of remote interfaces under the throws clause.Any special scenario in the application can be put under the Application Exception.Usually the client is given a recovery option that entails processing the request in a different way.When an application exception occurs, the EJB container doesn't roll back the transaction unless it is asked to do so explicitly, with a call to the setRollbackOnly() or it can be mentioned with an annotation in the application Exception class.

Ex:Session Bean remote Interface

@Remote

public interface TestSRemote{ public void actionShowRegn() throws HelpNotFoundException;}

Application Exception Class

@ApplicationException

public class HelpNotFoundException extends Exception {}

To throw an Application Exception

public void actionShowRegn(List lista) throws HelpNotFoundException{

if (lista.size()>=10)

{throw new HelpNotFoundException("Check the list size");}}

Next coming to System Exceptions

System exception which can be of the type Checked exception or unchecked exception.EJB methods cannot recover from these exceptions.Whenver an EJB method overcomes an unchecked exception the container will roll back the transaction.Where as in case of Checked Exceptions container does not perform the same functionality like roll backing the transaction etc.Whenever a checked system exception (such as a NamingException) occurs, you should throw javax.ejb.EJBException, or a subclass thereof, by wrapping the original exception.

Cues-Postgres-Row Level Locking-EJB3.0

Problem :
Each record in the database have an unique number
i.e, for record A unique number is 123
fore record B unique number is 124
This unique number is generated from a table and after assigning the unique number generated to record(here consider the record as patient record) it will be incremented by one.

Refer to the java snippet code below:
//Private EntityManager em//
//Control File is Entity name whose table name is control_master//
//em.CreateQuery is Java Persistence API Query//
seqQuery = em.createQuery(" SELECT c FROM ControlFile c WHERE c.instCode =:instCode and c.controlType=:controlType").setParameter("instCode",instStringCode).setParameter("controlType",ctrlType.trim() );

For the above query consider my instCode as 100 and controlType as NUMBER.
My table data will be as follows

S.No InstCode ControlType ControlNumber
1 100 NUMBER 25
2 200 NUMBER 570
3 253 NUMBER 32145
So when i execute the above query with my query parametrs as 100,Number i will get my control number as 25 .Immediately i will update my control number to 26
/** Java code for Updation*//
lastNo=controlFile.getCtrlLastNo();
/**So for Inst code=100 and Control Type=Number lastNo=25**/
controlFile.setCtrlLastNo(lastNo+1);
em.merge(controlFile);
em.flush();

/**Updation in the Database Completed**//

This what we have done initially .But as the number of concurrent users who are using the table has got increased i.e, when one more than one user is using the above query at the same time it give me the same control file number for me so because of this i had lost the uniqueness of my records because for two users it is giving the same number.
So we have a written a query so that a row level lock is created on the row which we are accessing.

/**Java Snippet Code which provides Rowlevel Locking on the database row**//
@TransactionAttribute(TransactionAttributeType.MANDATORY)

public Long NumGn(EntityManager em, Long instCode,String ctrlType) throws Exception{

/*This select for update create a read lock for the second or more users when a particular row is read by the first user .The lock will be released at the end of the transaction.Then the next user can read the row and it creates a lock for all other users .As one user only can access a particular row at a time the query execution will give a unique number and my problem has got rectified*/

Query query=em.createNativeQuery(" SELECT ctrl_id, ctrl_type, ctrl_last_no, inst_code FROM control_file WHERE ((inst_code = ?1) AND (ctrl_type = ?2)) FOR UPDATE",ControlFile.class).setParameter("1", instStringCode).setParameter("2",ctrlType.trim());

lastNo=controlFile.getCtrlLastNo();

em.merge(controlFile);
em.flush();}

Cues-Postgres-Query to find duplicate Records in a Table

Everyone may have encountered this duplicate records in the table scenario.
I have a table where i save the patient name,age,sex and his demographic details.If these patient details got saved more than once(Reasons for saving more than once can be many for ex::business logic code in the programming language etc)


CREATE OR REPLACE FUNCTION fncount111()
RETURNS INTEGER AS
$BODY$
declare
drug1 record;

//record is a datatype in postgres //
//when the function gets called
the row that needs to be checked with the next all rows is kept in the drug1
For ex:after the first row is checked with the next all rows in the table then second row
is kept in the drug1
//


drug2 record;
//Here searching for a duplicate record is limited to 3 rows in a table
i.e; if drug1 consists row1 then row2, row3,row4 are inserted into this drug2
and checked//(I have limited it to three rows u can limit it to any number of rows you want// )

checking record;
checking2 record;
patientcount integer;

//After each row is added to drug1 for searching the count
is incremented by one this count is used in inserting
the records into drug2 and comparing//


patientcount1 integer;
begin
patientcount=0;
patientcount1=0;
--raise info '%',;

//inserting the record to be checjed into drug1//
for drug1 in (
select * from mr_regisration_header ORDER BY mr_regh_id desc )
loop
checking=drug1;


//incrementing the count i.e., for row1 patientcount=1, when row2 gets inserted pateintcount=2//
patientcount=patientcount+1;

//If row 1 is insert into drug1 then row2,row3,row4 to be inserted into drug2 for checking(because in query my limit is 3)//
//offset patientcount clause--If row2(for row2 patient count wil be 2) is there in drug1
for comparison then row3,row4,row5 are to be compared with row2
so i am leaving two rows i.e,offset patientcount(offset 2) //

//for loop is for checking row2 with row3,row2 with row4,row2 with row5//

for drug2 in(select * from mr_regisration_header offset patientcount limit 3)
loop
checking2=drug2;

//checking criteria if firstname,cliniccode,date are equal then patient count1 will be incremented by one //

if(checking.mr_regh_first_name=checking2.mr_regh_first_name AND checking.mr_regh_inst_code=checking2.mr_regh_inst_code and checking.mr_regh_registration_date=checking2.mr_regh_registration_date)
THEN
raise info 'hai %',drug2.mr_regh_first_name;
patientcount1=patientcount1+1;

END IF;
end loop;
end loop;
RETURN patientcount1;
end;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
ALTER FUNCTION fncount111() OWNER TO postgres;


Cues-Java-Exceptions








The class Exception is the superclass of all the exceptions that ordinary programs may wish to recover from. The class RuntimeException is a subclass of class Exception. The subclasses of RuntimeException are unchecked exception classes. The subclasses of Exception other than RuntimeException are all checked exception classes.

Errors classes and their part in the exceptions will be discussed seperately in the coming posts.
I hope with the help figure you might have totally understood the hierrachy of Exceptions.

Checked Exceptions:Checked Exceptions are instances of Exception classes or one of its sub-classes excluding the branch of Runtime Exceptions.Any checked exceptions that may be thrown in a method must either be caught or declared in the method's throws clause.

They are called as Checked Exceptions because the Compiler and JVM check to make sure that either it is caught or declared in the method.

RunTime Exceptions: RuntimeException also extends from Exception. However, all of the exceptions that inherit from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions.
Examples of Runtime Exceptions include NullPointer,ArrayIndexOutOFBounds etc.

Cues Postgres-Table,Index,Database Sizes

Here are few queries where we can find the size of relations ,indexes,database----

select pg_size_pretty(pg_database_size('test1'));test1-name of the database
select pg_size_pretty(pg_total_relation_size(123455));123455-oid of the table
the above statement gives you the table size with the indexes.
If you want to find the table size alone execute the below command
select pg_size_pretty(pg_relation_size(123455));123455-oid of the table/index

Cues-Postgres-Bit Map Index

We all know that we can create a B-tree index on column in a table for Postgres ..
But any one ever thought how to create a Bit map index on table column ..

Few points on Postgres Indexing....

We can create multiple column indexes in postgres.Here is the example

CREATE INDEX indexname ON tablename(column1,column2);

Only B-tree and GiST index types support multicolumn indexes.Let's not worry about Gist Indexes they are beyond the present discussion.

Multicolumn indexes can be used with any query conditions that involve any subset of the index's columns,but the index will be more and more effective when the query includes the constriants on the left most columns i.e, for example in the above index the left most column is column2.

As i know ,directly we can not create a Bitmap index in Postgres 8.2.

PostgreSQL can combine multiple indexes and use a bitmap scan during query execution.

This can explained with a example .

CREATE TABLE tablename(
column1 charactervarying(10),column2 charactervarying(10)
);

now assume that we have two indexes one on column1,another on column2 with names index1 and index2.

This our query:

select * from tablename where column1='aa' and column2='bb';

Now postgres will combine both the indexes .To combine multiple indexes i.e. both the indexes , the system scans each needed index and prepares a bitmap in memory giving the locations of table rows which satisfies the index conditions.

The two bitmaps are then added and returned as requested by the query.

Now these rows are scanned and returned .Here the rows are visited in the physcial order because that is how the bitmap is laid out and index will take some additional extra time.

So the postgres query plan executer may not choose this option and it may use another query plan and the return the query output.

Cue Postgres-Indexing

Here are few questions with respect to Indexing in the Postgres database
1.How to reclaim the index space that is no longer in use??
2.What will reindexing of index do??
3.How to find the corrupted index on my database?

In postgres there is no concept of analyzing the index only analyzing the tables is available.
Ex:analyze table tablename;

we will get info on running the above query regarding any index corruption if it has happened .
Ouput on running the above query:

INFO: analyzing "public.mr_regisration_header"
INFO: "mr_regisration_header": scanned 3000 of 16958 pages, containing 146920 live rows and 1 dead rows; 3000 rows in sample, 830490 estimated total rows

Index corrpution mainly occur because of 2 reasons.
1.Sofware bugs 2.Hardware issues

Corrupted index can be reclaimed by the following command ---
reindex indexname

Reindexing provides a recovery method for reclaiming the index.

Reindexing rebuilds the index uisng data stored in the Index's table,replacing the old copy of the index.

Started Blogging

Prisoner of Birth on Paths of Glory

My Space

Hang over--Wrath of Grapes