1 package hero.session; 2 3 import java.rmi.RemoteException ; 4 import java.sql.Connection ; 5 import java.sql.Statement ; 6 import java.sql.ResultSet ; 7 import java.sql.SQLException ; 8 9 import javax.ejb.CreateException ; 10 import javax.ejb.EJBException ; 11 import javax.ejb.SessionBean ; 12 import javax.ejb.SessionContext ; 13 import javax.naming.Context ; 14 import javax.naming.InitialContext ; 15 import javax.naming.NamingException ; 16 import javax.naming.ServiceUnavailableException ; 17 import javax.sql.DataSource ; 18 19 48 public class SequenceGeneratorBean 49 implements SessionBean 50 { 51 52 56 60 private SessionContext mContext; 61 private int mNextNumber = 0; 63 64 68 80 public int getNextNumber( String pSequenceName ) 81 throws 82 ServiceUnavailableException , 83 RemoteException 84 { 85 Connection aConnection = null; 86 Statement aStatement = null; 87 try 88 { 89 112 Context aJNDIContext = new InitialContext (); 121 DataSource aSource = (DataSource ) aJNDIContext.lookup("java:comp/env/jdbc/myDS"); 122 aConnection = aSource.getConnection(); 123 aStatement = aConnection.createStatement(); 124 String aSql = "SELECT COUNT( * ) FROM "+pSequenceName; 125 ResultSet aResult = aStatement.executeQuery( aSql ); 126 int lResult = -1; 127 if( aResult.next() ) { 128 lResult = aResult.getInt( 1 ); 129 if( lResult <= 0 ) { 130 lResult = 0; 131 } 132 } 133 return lResult + 1; 134 135 136 137 } 138 catch( SQLException se ) {se.printStackTrace(); 139 throw new ServiceUnavailableException ( "Sequence number is broken" ); 140 } 141 catch( NamingException ne ) { 142 throw new ServiceUnavailableException ( "JNDI Lookup broken" ); 143 } 144 finally { 145 try { 146 if( aStatement != null ) { 147 aStatement.close(); 148 } 149 } 150 catch( Exception e ) { 151 } 152 try { 153 if( aConnection != null ) { 154 aConnection.close(); 155 } 156 } 157 catch( Exception e ) { 158 } 159 } 160 } 161 162 169 public void ejbCreate() 170 throws 171 CreateException 172 { 173 } 174 175 181 public String toString() 182 { 183 return "SequenceGeneratorBean [ " + " ]"; 184 } 185 186 190 public void setSessionContext( SessionContext aContext ) 191 throws EJBException 192 { 193 mContext = aContext; 194 } 195 196 public void ejbActivate() 197 throws EJBException 198 { 199 } 200 201 public void ejbPassivate() 202 throws EJBException 203 { 204 } 205 206 public void ejbRemove() 207 throws EJBException 208 { 209 } 210 211 } 212 | Popular Tags |