1 28 29 package sb; 30 31 import javax.naming.Context; 32 import javax.naming.InitialContext; 33 import javax.rmi.PortableRemoteObject; 34 import javax.transaction.UserTransaction; 35 36 41 public class ClientOp { 42 45 private static final int FIRST_BUY_AMOUNT = 10; 46 47 50 private static final int SECOND_BUY_AMOUNT = 20; 51 52 55 private static final int THIRD_BUY_AMOUNT = 50; 56 57 60 private ClientOp() { 61 62 } 63 64 68 public static void main(String[] args) { 69 70 Context initialContext = null; 71 try { 72 initialContext = new InitialContext(); 73 } catch (Exception e) { 74 System.err.println("Cannot get initial context for JNDI: " + e); 75 System.exit(2); 76 } 77 78 UserTransaction utx = null; 80 try { 81 82 utx = (UserTransaction) initialContext.lookup("javax.transaction.UserTransaction"); 84 85 95 96 } catch (Exception e) { 97 System.err.println("Cannot lookup UserTransaction: " + e); 98 System.exit(2); 99 } 100 101 OpHome home = null; 103 try { 104 home = (OpHome) PortableRemoteObject.narrow(initialContext.lookup("OpHome"), OpHome.class); 105 } catch (Exception e) { 106 System.err.println("Cannot lookup OpHome: " + e); 107 System.exit(2); 108 } 109 110 Op t1 = null; 112 try { 113 System.out.println("Create a bean"); 114 t1 = home.create("User1"); 115 } catch (Exception e) { 116 System.err.println("Cannot create OpBean: " + e); 117 System.exit(2); 118 } 119 120 try { 122 System.out.println("Start a first transaction"); 123 utx.begin(); 124 System.out.println("First request on the new bean"); 125 t1.buy(FIRST_BUY_AMOUNT); 126 System.out.println("Second request on the bean"); 127 t1.buy(SECOND_BUY_AMOUNT); 128 System.out.println("Commit the transaction"); 129 utx.commit(); 130 } catch (Exception e) { 131 System.err.println("exception during 1st Tx: " + e); 132 System.exit(2); 133 } 134 try { 136 System.out.println("Start a second transaction"); 137 utx.begin(); 138 t1.buy(THIRD_BUY_AMOUNT); 139 System.out.println("Rollback the transaction"); 140 utx.rollback(); 141 } catch (Exception e) { 142 System.err.println("exception during 2nd Tx: " + e); 143 System.exit(2); 144 } 145 146 int val = 0; 148 try { 149 System.out.println("Request outside any transaction"); 150 val = t1.read(); 151 } catch (Exception e) { 152 System.err.println("Cannot read value on t1 : " + e); 153 System.exit(2); 154 } 155 if (val != FIRST_BUY_AMOUNT + SECOND_BUY_AMOUNT) { 156 System.err.println("Bad value read: " + val); 157 System.exit(2); 158 } 159 160 try { 162 t1.remove(); 163 } catch (Exception e) { 164 System.out.println("Exception on buy: " + e); 165 System.exit(2); 166 } 167 System.out.println("ClientOp OK. Exiting."); 168 } 169 } 170 171 | Popular Tags |