JBoss.orgCommunity Documentation

Chapter 4. Source Code Overview

4.1. Interfaces and contracts
4.1.1. Registration Binding
4.1.2. Data Source Child
4.1.3. Data Source Parent
4.2. SIPRegistrarSbb
4.2.1. Local interface
4.2.2. Child relation
4.2.3. REGISTER handler
4.2.4. TIMER handler
4.3. DataSourceChild SBB
4.3.1. Local interface
4.3.2. Parent relation
4.3.3. JDBC RA Tasks
4.3.4. JDBC Task Exception handler
4.3.5. JDBC Task Result handler

Important

To obtain the example's complete source code please refer to Section 2.2, “Mobicents JAIN SLEE SIP JDBC Registrar Example Source Code”.

Chapter Chapter 3, Design Overview explains top level view of example. This chapter explains how components perform their tasks. For more detailed explanation of JSLEE related source code and xml descriptors, please refer to simpler examples, like sip-wakeup or jdbc-demo.

This section outlines interfaces declared by this example. Those interfaces declare contracts between example components. Thus it is important to understand them well, since such design allows one to introduce his own implementation of examples component.

The RegistrationBinding class is a simple java bean. It is used to pass information about user contact from DataSourceChild SBB to SIPRegistrar SBB. It has simple set of fields which correspond to contact data like contact address, call id, etc:



public class RegistrationBinding {
    private String sipAddress;
    private String contactAddress;
    private long expires;
    private long registrationDate;
    private float qValue;
    private String callId;
    private long cSeq;
    
    public RegistrationBinding(String sipAddress, String contactAddress, long expires, long registrationDate, float value, String callId, long seq) {
        super();
        this.sipAddress = sipAddress;
        this.contactAddress = contactAddress;
        this.expires = expires;
        this.registrationDate = registrationDate;
        this.qValue = value;
        this.callId = callId;
        this.cSeq = seq;
        
    }
    
    ....
    
}
        

Since RegistrationBinding follows java bean pattern, it also defines set of simple accessors:



public class RegistrationBinding {       
    public String getSipAddress() {
        return sipAddress;
    }
    public void setSipAddress(String sipAddress) {
        this.sipAddress = sipAddress;
    }
    public String getContactAddress() {
        return contactAddress;
    }
    public void setContactAddress(String contactAddress) {
        this.contactAddress = contactAddress;
    }
   ...
   
    // --- logic methods
    /**
     * Returns number of mseconds till this entry expires May be 0 or -ve if
     * already expired
     */
    public long getExpiresDelta() {
        return ((getExpires() - (System.currentTimeMillis() - getRegistrationDate()) / 1000));
    }
 
    ....
    
}
        

The Data Source Child (DataSourceChild SBB) as mentioned is responsible for proper storing user contact data. To allow that, there must be a definition of methods, which will allow to manipulate user data. Such definition can be found in org.mobicents.slee.example.sjr.data.DataSourceChildSbbLocalInterface. The said interface is defined as follows:



public interface DataSourceChildSbbLocalInterface {
    public void init();
    public void getBindings(String address);
    public void removeBinding(String contact, String address);
    public void removeBindings(String address, String callId, long cSeq);
    public void updateBindings(String address, String callId, long cSeq,
            List<ContactHeader> contacts);
}
       

Defined methods have following contracts:

init()

allows to initialize data storage. It is invoked once, when service starts.

getBindings(String address)

request DataSourceChild SBB to fetch contact addresses for passed AOR. Result is passed to parent as SBB Local Interface invocation(Section 4.1.3, “Data Source Parent”).

removeBinding(String contact, String address)

request DataSourceChild SBB to remove one contact address for passed AOR.Result is passed to parent as SBB Local Interface invocation(Section 4.1.3, “Data Source Parent”).

removeBindings(String address, String callId, long cSeq)

request DataSourceChild SBB to remove all contacts addresses for passed AOR. Result is passed to parent as SBB Local Interface invocation(Section 4.1.3, “Data Source Parent”).

updateBindings(String address, String callId, long cSeq, List<ContactHeader> contacts)

request DataSourceChild SBB to update list of available contacts for AOR. Result is passed to parent as SBB Local Interface invocation(Section 4.1.3, “Data Source Parent”). Passed list with contacts will become current set of contact for passed AOR(this may result in removal of previously existing contacts if they are not in new set).

The Data Source Parent (SIPRegistrar SBB/DataSourceParent SBB ) consumes UAC requests and triggers DataSourceChild SBB to store registration infomration. To do so it makes use of DataSourceChildSbbLocalInterface(Section 4.1.2, “Data Source Child”). The child SBB passes outcome of invocations to Data Source Parent by means of another interface - org.mobicents.slee.example.sjr.data.DataSourceParentSbbLocalInterface. It is defined as follows:



public interface DataSourceParentSbbLocalInterface {
    public void getBindingsResult(int resultCode, List<RegistrationBinding> bindings);
        
    public void removeBindingsResult(int resultCode, List<RegistrationBinding> currentBindings, List<RegistrationBinding> removedBindings);
    
    public void updateBindingsResult(int resultCode, List<RegistrationBinding> currentBindings, List<RegistrationBinding> updatedBindings, List<RegistrationBinding> removedBindings);
    
}
       

Note that each method has resultCode argument. Its value indicates outcome of child interface invocation, that is, this value is set as Status-Code header in asnwer

Defined methods have following contracts:

getBindingsResult(int resultCode, List<RegistrationBinding> bindings)

invoked as result of call to DataSourceChildSbbLocalInterface.getBindings. Arguments contain list of current bindings.

removeBindingsResult(int resultCode, List<RegistrationBinding> currentBindings, List<RegistrationBinding> removedBindings)

invoked as result of call to DataSourceChildSbbLocalInterface.removeBinding and DataSourceChildSbbLocalInterface.removeBindings. Arguments contain list of current bindings and list of removed bindings.

updateBindingsResult(int resultCode, List<RegistrationBinding> currentBindings, List<RegistrationBinding> updatedBindings, List<RegistrationBinding> removedBindings);

invoked as result of call to DataSourceChildSbbLocalInterface.updateBindings. Arguments contain list of current bindings, updated bindings and removed bindings.

SIP Registrar SBB is responsible for handling REGISTER requests and sending proper response. SIP Registrar SBB receives REGISTER requests as initial events.

Class org.mobicents.slee.example.sjr.sip.SIPRegistrarSbb includes all the service logic required to perform registry tasks. That is to consume REGISTER and generate proper answer based on outcome of registry operation.

SIP Registrar SBB declares SBB Local interface. This interface is used by DataSourceChild SBB to inform SIP Registrar SBB when data source operation returns result. So in short it defines contract between SIP Registrar SBB and DataSourceChild SBB. Local interface is declared in sbb-jar.xml in following way:



 <sbb-jar>
    <sbb>
        <sbb-name>SIP Registrar</sbb-name>
        <sbb-vendor>org.mobicents</sbb-vendor>
        <sbb-version>1.0</sbb-version>
    
       ...
        
        <sbb-classes>
            <sbb-abstract-class
                reentrant="True">
                <sbb-abstract-class-name>org.mobicents.slee.example.sjr.sip.SIPRegistrarSbb</sbb-abstract-class-name>
                <sbb-local-interface>
                    <sbb-local-interface-name>
                        org.mobicents.slee.example.sjr.data.DataSourceParentSbbLocalObject
                    </sbb-local-interface-name>
                </sbb-local-interface>   
            </sbb-abstract-class>
            
            ....
                       
        </sbb-classes>
        
        ...
        
    </sbb>
</sbb-jar>
        
        

Parent interface is declared as follows:



public interface DataSourceParentSbbLocalObject extends SbbLocalObject,
        DataSourceParentSbbLocalInterface {
}
        

Above methods(Section 4.1.3, “Data Source Parent”) are invoked by DataSourceChild SBB as result of operations invoked on its local interface. According to name, methods perform certain task:

Send query result to UAC


    @Override
    public void getBindingsResult(int resultCode,
            List<RegistrationBinding> bindings) {
        ServerTransaction serverTransaction = getRegisterTransactionToReply();
        if (serverTransaction == null) {
            tracer.warning("failed to find SIP server tx to send response");
            return;
        }
        try {
            if (resultCode < 300) {
                sendRegisterSuccessResponse(resultCode, bindings,
                        serverTransaction);
            } else {
                sendErrorResponse(resultCode, serverTransaction);
            }
        } catch (Exception e) {
            tracer.severe("failed to send SIP response", e);
        }
    }
                    
Send update binding result to UAC


    @Override
    public void updateBindingsResult(int resultCode,
            List<RegistrationBinding> currentBindings,
            List<RegistrationBinding> updatedBindings,
            List<RegistrationBinding> removedBindings) {
        ServerTransaction serverTransaction = getRegisterTransactionToReply();
        if (serverTransaction == null) {
            tracer.warning("failed to find SIP server tx to send response");
            return;
        }
        try {
            if (resultCode < 300) {
                // we have to post process, reset/add/cancel timers...
                // first update, since those are more important. This has to be
                // done, since we want timers updated first
                // so events are not fired and dont corrupt DB entries(remove
                // them,
                // after they are updated)
                updateTimers(updatedBindings);
                cancelTimers(removedBindings);
                sendRegisterSuccessResponse(resultCode, currentBindings,
                        serverTransaction);
            } else {
                // we just fail :)
                sendErrorResponse(resultCode, serverTransaction);
            }
        } catch (Exception e) {
            tracer.severe("failed to send SIP response", e);
        }
    }
                    
Send confirmation on remove of binding



    private static final List<RegistrationBinding> EMPTY_LIST = Collections.emptyList();
    @Override
    public void removeBindingsResult(int resultCode,
            List<RegistrationBinding> currentBindings,
            List<RegistrationBinding> removedBindings) {
        // same processing as update result
        updateBindingsResult(resultCode, currentBindings, EMPTY_LIST,
                removedBindings);
    }
                    

SIP Registrar SBB defines DataSourceChild SBB as child. The DataSourceChild SBB child is used as a driver which manages persistence of user registration data. Child relation is declared in sbb-jar.xml descriptor:



 <sbb-jar>
    <sbb>
        <sbb-name>SIP Registrar</sbb-name>
        <sbb-vendor>org.mobicents</sbb-vendor>
        <sbb-version>1.0</sbb-version>
    
        <sbb-ref>
            <sbb-name>DataSourceChild</sbb-name>
            <sbb-vendor>org.mobicents</sbb-vendor>
            <sbb-version>1.0</sbb-version>
            <sbb-alias>childSbb</sbb-alias>
        </sbb-ref>
        
        <sbb-classes>
            <sbb-abstract-class
                reentrant="True">
                <sbb-abstract-class-name>org.mobicents.slee.example.sjr.sip.SIPRegistrarSbb</sbb-abstract-class-name>
                <get-child-relation-method>
                    <sbb-alias-ref>childSbb</sbb-alias-ref>                 
                    <get-child-relation-method-name>getChildRelation</get-child-relation-method-name>
                    <default-priority>0</default-priority>                  
                </get-child-relation-method>                
            </sbb-abstract-class>
            
            ....
                       
        </sbb-classes>
        
        ...
        
    </sbb>
</sbb-jar>
        
        

Parent declaration in descriptor defines method name, in case of example its getChildRelation, implented by JSLEE. This method allows parent to access javax.slee.ChildRelation object representing link to defined child. ChildRelation object gives access to SbbLocalObject interface. This object allows parent to:

Its defined in source as follows:



public abstract class SIPRegistrarSbb implements Sbb, DataSourceParentSbbLocalInterface{
        
    ...
    
    public abstract ChildRelationExt getChildRelation();
    
    ...
}
        

Refer to Section 4.3, “DataSourceChild SBB” for definition of child interface.

The SIPRegistrarSbb performs following operations in REGISTER event handler:

The SIPRegistrarSbb listens for timer events. Receiving one, is equal to expiration of certain contact. The AOR and expired contact are determined by value of ACI variable of custom activity context interface. The interface is defined as follows:



public interface SbbActivityContextInterface extends
        ActivityContextInterfaceExt {
    public RegistrationBindingData getData();
    public void setData(RegistrationBindingData value);
}
        

Since SLEE 1.1 allows custom ACI in event handler method signature, timer event handler looks as follows:



    public void onTimerEvent(TimerEvent timer, SbbActivityContextInterface aci) {
        // detach from this activity, we don't want to handle any other event on
        // it
        aci.detach(this.sbbContextExt.getSbbLocalObject());
        // get data needed to remove binding from aci
        RegistrationBindingData data = aci.getData();
        if (data == null) {
            // another service's timer event, ignore
            return;
        }
        try {
            DataSourceChildSbbLocalInterface child = (DataSourceChildSbbLocalInterface) getChildRelation()
                    .create(ChildRelationExt.DEFAULT_CHILD_NAME);
            child.removeBinding(data.getContact(), data.getAddress());
        } catch (Exception e) {
            tracer.severe("Exception invoking data source child sbb.", e);
            return;
        }
        // end the activity
        try {
            ((NullActivity) aci.getActivity()).endActivity();
        } catch (Exception e) {
            tracer.warning("failed to end binding aci", e);
        }
    }
        

DataSourceChild SBB is responsible for two tasks. First one is to persist registration data in some sort of a storage. Second is to callback SIP Registrar SBB with result of operation invoked on DataSourceChild SBB local interface.

This example uses DataSourceChild SBB implementation which interacts with database by means of JDBC Resource Adaptor. This following sections contain not only general description of DataSourceChild SBB , they contain description of specific implementation of said SBB.

DataSourceChild SBB declares SBB Local interface. This interface is used by SIP Registrar SBB to trigger DataSourceChild SBB to perform certain operation on storage in which registration data is beeing held. So in short it defines contract between SIP Registrar SBB and DataSourceChild SBB. Local interface is declared in sbb-jar.xml in following way:



 <sbb-jar>
 
    ...
 
    <sbb>
        <sbb-name>DataSourceChild</sbb-name>
        <sbb-vendor>org.mobicents</sbb-vendor>
        <sbb-version>1.0</sbb-version>

        <sbb-classes>
            <sbb-abstract-class
                reentrant="True">
                <sbb-abstract-class-name>
                    org.mobicents.slee.example.sjr.data.jdbc.DataSourceChildSbb
                </sbb-abstract-class-name>
            </sbb-abstract-class>
            <sbb-local-interface>
                <sbb-local-interface-name>
                    org.mobicents.slee.example.sjr.data.DataSourceChildSbbLocalObject
                </sbb-local-interface-name>
            </sbb-local-interface>
        </sbb-classes>
        
        ...
        
    </sbb>
</sbb-jar>
        
        

Child interface is declared as follows:



public interface DataSourceChildSbbLocalObject extends SbbLocalObject,
        DataSourceChildSbbLocalInterface {
}
        

Above methods(Section 4.1.2, “Data Source Child”) are invoked by SIP Registrar SBB as result of registrar routines. According to name, methods perform certain task:

Initiate data storage


    @Override
    public void init() {
        // create db schema if needed
        Connection connection = null;
        try {
            connection = jdbcRA.getConnection();
            connection.createStatement().execute(
                    DataSourceSchemaInfo._QUERY_CREATE);
        } catch (SQLException e) {
            tracer.warning("failed to create db schema", e);
        } finally {
            try {
                connection.close();
            } catch (SQLException e) {
                tracer.severe("failed to close db connection", e);
            }
        }
    }
                    
Fetch bindings for AOR


    @Override
    public void getBindings(String address) {
        executeTask(new GetBindingsJdbcTask(address, tracer));
    }
    
                    
Remove single binding


    @Override
    public void removeBinding(String contact, String address) {
        executeTask(new RemoveBindingJdbcTask(address, contact, tracer));
    }
   
                    
Remove all bindings


    @Override
    public void removeBindings(String address, String callId, long cSeq) {
        executeTask(new RemoveBindingsJdbcTask(address, callId, cSeq, tracer));
    }
   
                    
Update/Add bindings


    @Override
    public void updateBindings(String address, String callId, long cSeq,
            List<ContactHeader> contacts) {
        executeTask(new UpdateBindingsJdbcTask(address, callId, cSeq, contacts, tracer));
    }
                    

Default implementation of DataSourceChild SBB uses JDBC RA to persist user contact information. It performs its task using set of JDBC RA tasks.

Each task use queries defined in org.mobicents.slee.example.sjr.data.jdbc.DataSourceSchemaInfo. Example of such query, looks as follows:



public class DataSourceSchemaInfo {
    // lets define some statics for table and queries in one place.
    public static final String _TABLE_NAME = "SIP_REGISTRAR";
    public static final String _COLUMN_SIP_ADDRESS = "SIP_ADDRESS";
    public static final String _COLUMN_CONTACT = "CONTACT";
    public static final String _COLUMN_EXPIRES = "EXPIRES";
    public static final String _COLUMN_REGISTER_DATE = "REGISTER_DATE";
    public static final String _COLUMN_Q = "Q"; 
    public static final String _COLUMN_CALL_ID = "CALL_ID";
    public static final String _COLUMN_C_SEQ = "C_SEQ";
    // SQL queries.
    // drop table
    public static final String _QUERY_DROP = "DROP TABLE IF EXISTS "
            + _TABLE_NAME + ";";
    // create table, use contact as PK, since it will be unique ?
    // | CONTACT (PK) | SIP_ADDRESS (PK) | Q | EXPIRES | REGISTER_DATE | CALL_ID
    // | C_SEQ |
    public static final String _QUERY_CREATE = "CREATE TABLE " + _TABLE_NAME
            + " (" + _COLUMN_CONTACT + " VARCHAR(255) NOT NULL, "
            + _COLUMN_SIP_ADDRESS + " VARCHAR(255) NOT NULL, " + _COLUMN_Q
            + " FLOAT NOT NULL, " + _COLUMN_EXPIRES + " BIGINT NOT NULL, "
            + _COLUMN_REGISTER_DATE + " BIGINT NOT NULL, " + _COLUMN_C_SEQ
            + " BIGINT NOT NULL, " + _COLUMN_CALL_ID
            + " VARCHAR(255) NOT NULL, " + "PRIMARY KEY(" + _COLUMN_CONTACT
            + "," + _COLUMN_SIP_ADDRESS + ")" + ");";
    ...    
    // update row for AOR and contact
    public static final String _QUERY_UPDATE = "UPDATE " + _TABLE_NAME + " "
            + "SET " + _COLUMN_CALL_ID + "=?, " + _COLUMN_C_SEQ + "=?, "
            + _COLUMN_EXPIRES + "=?, " + _COLUMN_Q + "=?, "
            + _COLUMN_REGISTER_DATE + "=? " + "WHERE " + _COLUMN_SIP_ADDRESS
            + "=? AND " + _COLUMN_CONTACT + "=?;";
    
    ...
    
}
        

Following tasks are defined to perform operations on persistent storage:

GetBindingsJdbcTask



public class GetBindingsJdbcTask extends DataSourceJdbcTask {
    private List<RegistrationBinding> bindings = null;
    private final String address;
    private final Tracer tracer;
    
    public GetBindingsJdbcTask(String address, Tracer tracer) {
        this.address = address;
        this.tracer = tracer;
    }
    @Override
    public Object executeSimple(JdbcTaskContext taskContext) {
        try {
            PreparedStatement preparedStatement = taskContext.getConnection()
                    .prepareStatement(DataSourceSchemaInfo._QUERY_SELECT);
            preparedStatement.setString(1, address);
            preparedStatement.execute();
            ResultSet resultSet = preparedStatement.getResultSet();
            bindings = DataSourceSchemaInfo.getBindingsAsList(address, resultSet);
        } catch (Exception e) {
            tracer.severe("failed to execute task to get bindings of "+address,e);
        }
        return this;
    }
    @Override
    public void callBackParentOnException(
            DataSourceParentSbbLocalInterface parent) {
        parent.getBindingsResult(Response.SERVER_INTERNAL_ERROR,
                EMPTY_BINDINGS_LIST);
    }
    @Override
    public void callBackParentOnResult(DataSourceParentSbbLocalInterface parent) {
        if (bindings == null) {
            parent.getBindingsResult(Response.SERVER_INTERNAL_ERROR, EMPTY_BINDINGS_LIST);
        }
        else {
            parent.getBindingsResult(Response.OK, bindings);
        }
    }
}
                    
RemoveBindingJdbcTask



public class RemoveBindingJdbcTask extends DataSourceJdbcTask {
    private final String address;
    private final String contact;
    private final Tracer tracer;
    public RemoveBindingJdbcTask(String address, String contact, Tracer tracer) {
        this.address = address;
        this.contact = contact;
        this.tracer = tracer;
    }
    @Override
    public Object executeSimple(JdbcTaskContext taskContext) {
        try {
            PreparedStatement preparedStatement = taskContext.getConnection()
                    .prepareStatement(DataSourceSchemaInfo._QUERY_DELETE);
            preparedStatement.setString(1, address);
            preparedStatement.setString(2, contact);
            preparedStatement.execute();
            if (this.tracer.isInfoEnabled()) {
                this.tracer.info("Removed binding: " + address
                        + " -> " + contact);
            }
        } catch (Exception e) {
            tracer.severe("failed to remove binding", e);
        }
        return this;
    }
    @Override
    public void callBackParentOnException(
            DataSourceParentSbbLocalInterface parent) {
        // nothing to call back
    }
    @Override
    public void callBackParentOnResult(DataSourceParentSbbLocalInterface parent) {
        // nothing to call back
    }
}
                    

RemoveBindingsJdbcTask



public class RemoveBindingsJdbcTask extends DataSourceJdbcTask {
    private int resultCode = Response.OK;
    private List<RegistrationBinding> currentBindings = null;
    private List<RegistrationBinding> removedBindings = null;
    private final String address;
    private final String callId;
    private final long cSeq;
    private final Tracer tracer;
    public RemoveBindingsJdbcTask(String address, String callId, long cSeq,
            Tracer tracer) {
        this.address = address;
        this.callId = callId;
        this.cSeq = cSeq;
        this.tracer = tracer;
    }
    @Override
    public Object executeSimple(JdbcTaskContext taskContext) {
        SleeTransaction tx = null;
        try {
            tx = taskContext.getSleeTransactionManager().beginSleeTransaction();
            Connection connection = taskContext.getConnection();
            // static value of query string, since its widely used :)
            PreparedStatement preparedStatement = connection
                    .prepareStatement(DataSourceSchemaInfo._QUERY_SELECT);
            preparedStatement.setString(1, address);
            preparedStatement.execute();
            ResultSet resultSet = preparedStatement.getResultSet();
            // IMPORTANT: we need both - currently present bindings and removed
            // ones
            // so SBB can update timers
            currentBindings = DataSourceSchemaInfo.getBindingsAsList(address, resultSet);
            List<RegistrationBinding> removedBindings = new ArrayList<RegistrationBinding>();
            Iterator<RegistrationBinding> it = currentBindings.iterator();
            while (it.hasNext()) {
                RegistrationBinding binding = it.next();
                if (callId.equals(binding.getCallId())) {
                    if (cSeq > binding.getCSeq()) {
                        it.remove();
                        removedBindings.add(binding);
                        preparedStatement = connection
                                .prepareStatement(DataSourceSchemaInfo._QUERY_DELETE);
                        preparedStatement.setString(1, address);
                        preparedStatement.setString(2,
                                binding.getContactAddress());
                        preparedStatement.execute();
                        if (this.tracer.isInfoEnabled()) {
                            this.tracer.info("Removed binding: " + address
                                    + " -> " + binding.getContactAddress());
                        }
                    } else {
                        resultCode = Response.BAD_REQUEST;
                        return this;
                    }
                } else {
                    removedBindings.add(binding);
                    preparedStatement = connection
                            .prepareStatement(DataSourceSchemaInfo._QUERY_DELETE);
                    preparedStatement.setString(1, address);
                    preparedStatement.setString(2, binding.getContactAddress());
                    preparedStatement.execute();
                    if (this.tracer.isInfoEnabled()) {
                        this.tracer.info("Removed binding: " + address
                                + " -> " + binding.getContactAddress());
                    }
                }
            }
            tx.commit();
            tx = null;
        } catch (Exception e) {
            tracer.severe("Failed to execute task", e);
            resultCode = Response.SERVER_INTERNAL_ERROR;
        } finally {
            if (tx != null) {
                try {
                    tx.rollback();
                } catch (Exception f) {
                    tracer.severe("failed to rollback tx", f);
                }
            }
        }
        return this;
    }
    @Override
    public void callBackParentOnException(
            DataSourceParentSbbLocalInterface parent) {
        parent.removeBindingsResult(Response.SERVER_INTERNAL_ERROR,
                EMPTY_BINDINGS_LIST, EMPTY_BINDINGS_LIST);
    }
    @Override
    public void callBackParentOnResult(DataSourceParentSbbLocalInterface parent) {
        if (resultCode > 299) {
            parent.removeBindingsResult(resultCode, EMPTY_BINDINGS_LIST,
                     EMPTY_BINDINGS_LIST);
        } else {
            parent.removeBindingsResult(resultCode, currentBindings,
                    removedBindings);
        }
    }
}
                    
UpdateBindingsJdbcTask



public class UpdateBindingsJdbcTask extends DataSourceJdbcTask {
    private int resultCode = Response.OK;
    private List<RegistrationBinding> currentBindings = null;
    private List<RegistrationBinding> updatedBindings = null;
    private List<RegistrationBinding> removedBindings = null;
    private final String address;
    private final String callId;
    private final long cSeq;
    private final List<ContactHeader> contacts;
    private final Tracer tracer;
    public UpdateBindingsJdbcTask(String address, String callId, long cSeq,
            List<ContactHeader> contacts, Tracer tracer) {
        this.address = address;
        this.callId = callId;
        this.cSeq = cSeq;
        this.contacts = contacts;
        this.tracer = tracer;
    }
    @Override
    public Object executeSimple(JdbcTaskContext taskContext) {
        // fetch those values, yes, we do some things twice, its done to
        // avoid pushing everythin into JDBC execute.
        // final ExpiresHeader expiresHeader =
        // super.event.getRequest().getExpires();
        ListIterator<ContactHeader> li = this.contacts.listIterator();
        SleeTransaction tx = null;
        try {
            tx = taskContext.getSleeTransactionManager().beginSleeTransaction();
            Connection connection = taskContext.getConnection();
            // static value of query string, since its widely used :)
            PreparedStatement preparedStatement = connection
                    .prepareStatement(DataSourceSchemaInfo._QUERY_SELECT);
            preparedStatement.setString(1, address);
            preparedStatement.execute();
            ResultSet resultSet = preparedStatement.getResultSet();
            // lets have it as map, it will be easier to manipulate in this
            // case.
            Map<String, RegistrationBinding> bindings = DataSourceSchemaInfo
                    .getBindingsAsMap(address, resultSet);
            removedBindings = new ArrayList<RegistrationBinding>();
            updatedBindings = new ArrayList<RegistrationBinding>();
            while (li.hasNext()) {
                ContactHeader contact = li.next();
                //
                // get expires value, either in header or default
                // do min-expires etc
                long requestedExpires = contact.getExpires();
                float q = 0;
                if (contact.getQValue() != -1)
                    q = contact.getQValue();
                // Find existing binding
                String contactAddress = contact.getAddress().getURI()
                        .toString();
                RegistrationBinding binding = (RegistrationBinding) bindings
                        .get(contactAddress);
                if (binding != null) { // Update this binding
                    if (this.callId.equals(binding.getCallId())) {
                        if (this.cSeq <= binding.getCSeq()) {
                            resultCode = Response.BAD_REQUEST;
                            return this;
                        }
                    }
                    if (requestedExpires == 0) {
                        bindings.remove(contactAddress);
                        removedBindings.add(binding);
                        preparedStatement = connection
                                .prepareStatement(DataSourceSchemaInfo._QUERY_DELETE);
                        preparedStatement.setString(1, address);
                        preparedStatement.setString(2,
                                binding.getContactAddress());
                        preparedStatement.execute();
                        if (this.tracer.isInfoEnabled()) {
                            this.tracer.info("Removed binding: " + address
                                    + " -> " + contactAddress);
                        }
                    } else {
                        // udpate binding in map, it will be sent back
                        binding.setCallId(callId);
                        binding.setExpires(requestedExpires);
                        binding.setRegistrationDate(System.currentTimeMillis());
                        binding.setCSeq(this.cSeq);
                        binding.setQValue(q);
                        updatedBindings.add(binding);
                        // udpate DB
                        preparedStatement = connection
                                .prepareStatement(DataSourceSchemaInfo._QUERY_UPDATE);
                        preparedStatement.setString(1, binding.getCallId());
                        preparedStatement.setLong(2, binding.getCSeq());
                        preparedStatement.setLong(3, binding.getExpires());
                        preparedStatement.setFloat(4, binding.getQValue());
                        preparedStatement.setLong(5,
                                binding.getRegistrationDate());
                        preparedStatement.setString(6, address);
                        preparedStatement.setString(7,
                                binding.getContactAddress());
                        preparedStatement.execute();
                        if (this.tracer.isInfoEnabled()) {
                            this.tracer.info("Updated binding: " + address
                                    + " -< " + contactAddress);
                        }
                    }
                } else {
                    // Create new binding
                    if (requestedExpires != 0) {
                        RegistrationBinding newRegistrationBinding = new RegistrationBinding(
                                address, contactAddress, requestedExpires,
                                System.currentTimeMillis(), q, callId,
                                this.cSeq);
                        // put in bindings
                        bindings.put(
                                newRegistrationBinding.getContactAddress(),
                                newRegistrationBinding);
                        updatedBindings.add(newRegistrationBinding);
                        // update DB
                        preparedStatement = connection
                                .prepareStatement(DataSourceSchemaInfo._QUERY_INSERT);
                        preparedStatement.setString(1,
                                newRegistrationBinding.getCallId());
                        preparedStatement.setLong(2,
                                newRegistrationBinding.getCSeq());
                        preparedStatement.setLong(3,
                                newRegistrationBinding.getExpires());
                        preparedStatement.setFloat(4,
                                newRegistrationBinding.getQValue());
                        preparedStatement.setLong(5,
                                newRegistrationBinding.getRegistrationDate());
                        preparedStatement.setString(6, address);
                        preparedStatement.setString(7,
                                newRegistrationBinding.getContactAddress());
                        preparedStatement.execute();
                        if (this.tracer.isInfoEnabled()) {
                            this.tracer.info("Added new binding: " + address
                                    + " -< " + contactAddress);
                        }
                    }
                }
            }
            // now lets push current bindings
            currentBindings = new ArrayList<RegistrationBinding>(
                    bindings.values());
            tx.commit();
            tx = null;
        } catch (Exception e) {
            tracer.severe("Failed to execute jdbc task.", e);
            resultCode = Response.SERVER_INTERNAL_ERROR;
        } finally {
            if (tx != null) {
                try {
                    tx.rollback();
                } catch (Exception f) {
                    tracer.severe("failed to rollback tx", f);
                }
            }
        }
        return this;
    }
    @Override
    public void callBackParentOnException(
            DataSourceParentSbbLocalInterface parent) {
        parent.updateBindingsResult(Response.SERVER_INTERNAL_ERROR,
                EMPTY_BINDINGS_LIST, EMPTY_BINDINGS_LIST, EMPTY_BINDINGS_LIST);
    }
    @Override
    public void callBackParentOnResult(DataSourceParentSbbLocalInterface parent) {
        if (resultCode > 299) {
            parent.updateBindingsResult(resultCode, EMPTY_BINDINGS_LIST,
                    EMPTY_BINDINGS_LIST, EMPTY_BINDINGS_LIST);
        } else {
            parent.updateBindingsResult(resultCode, currentBindings,
                    updatedBindings, removedBindings);
        }
    }
}
                    

Similar to Section 4.3.4, “JDBC Task Exception handler”, the SimpleJdbcTaskResultEvent is also very simple:



    public void onSimpleJdbcTaskResultEvent(SimpleJdbcTaskResultEvent event,
            ActivityContextInterface aci) {
        if (tracer.isFineEnabled()) {
            tracer.fine("Received a SimpleJdbcTaskResultEvent, as result of executed task "
                    + event.getTask());
        }
        // end jdbc activity
        final JdbcActivity activity = (JdbcActivity) aci.getActivity();
        activity.endActivity();
        // call back parent
        final DataSourceParentSbbLocalInterface parent = (DataSourceParentSbbLocalInterface) sbbContextExt
                .getSbbLocalObject().getParent();
        final DataSourceJdbcTask jdbcTask = (DataSourceJdbcTask) event
                .getTask();
        jdbcTask.callBackParentOnResult(parent);
    }