01: package com.mockrunner.example.connector;
02:
03: import java.util.Iterator;
04:
05: import javax.naming.InitialContext;
06: import javax.resource.ResourceException;
07: import javax.resource.cci.Connection;
08: import javax.resource.cci.ConnectionFactory;
09: import javax.resource.cci.IndexedRecord;
10: import javax.resource.cci.Interaction;
11: import javax.resource.cci.LocalTransaction;
12: import javax.resource.cci.RecordFactory;
13:
14: /**
15: * A DAO that calls a database stored procedure over an resource adapter
16: * using local transactions. The stored procedure takes the name of a
17: * person and creates an account for this person returning the account id.
18: * The stored procedure may be defined like this:
19: * <br>
20: * <code>PROCEDURE CRTACCT(IN firstname VARCHAR, IN lastname VARCHAR, OUT id INTEGER)</code>
21: */
22: public class AccountDAO {
23: public int createAccount(String firstName, String lastName) {
24: Connection connection = null;
25: LocalTransaction transaction = null;
26: try {
27: InitialContext context = new InitialContext();
28: ConnectionFactory connectionFactory = (ConnectionFactory) context
29: .lookup("java:ra/db/ConnectionFactory");
30: connection = connectionFactory.getConnection();
31: Interaction interaction = connection.createInteraction();
32: CCIInteractionSpec spec = new CCIInteractionSpec();
33: spec.setFunctionName("CRTACCT");
34: spec.setSchema("testschema");
35: spec.setCatalog(null);
36: RecordFactory recordFactory = connectionFactory
37: .getRecordFactory();
38: IndexedRecord inputRecord = recordFactory
39: .createIndexedRecord("Input");
40: inputRecord.add(firstName);
41: inputRecord.add(lastName);
42: transaction = connection.getLocalTransaction();
43: transaction.begin();
44: IndexedRecord outputRecord = (IndexedRecord) interaction
45: .execute(spec, inputRecord);
46: transaction.commit();
47: if (null != outputRecord) {
48: Iterator iterator = outputRecord.iterator();
49: if (iterator.hasNext()) {
50: Integer value = (Integer) iterator.next();
51: return value.intValue();
52: }
53: }
54: } catch (Exception exc) {
55: handleException(exc, transaction);
56: } finally {
57: try {
58: if (null != connection)
59: connection.close();
60: } catch (ResourceException exc) {
61: exc.printStackTrace();
62: }
63: }
64: return -1;
65: }
66:
67: private void handleException(Exception exc,
68: LocalTransaction transaction) {
69: if (null != transaction) {
70: try {
71: transaction.rollback();
72: } catch (ResourceException txExc) {
73: txExc.printStackTrace();
74: }
75: }
76: }
77: }
|