JBoss.orgCommunity Documentation
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:
allows to initialize data storage. It is invoked once, when service starts.
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”).
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”).
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”).
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:
invoked as result of call to DataSourceChildSbbLocalInterface.getBindings
. Arguments contain list of current bindings.
invoked as result of call to DataSourceChildSbbLocalInterface.removeBinding
and DataSourceChildSbbLocalInterface.removeBindings
. Arguments contain list of current bindings and list of removed bindings.
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:
@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);
}
}
@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);
}
}
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:
attach child to ActivityContextInterface
to make it eligible to receive events.
invoke synchronously methods defined in child SbbLocalObject
.
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:
check if request is a query, if so send response with list of contacts
// get configuration from MBean
final long maxExpires = config.getSipRegistrationMaxExpires();
final long minExpires = config.getSipRegistrationMinExpires();
// Process require header
// Authenticate
// Authorize
// OK we're authorized now ;-)
// extract address-of-record
String sipAddressOfRecord = getCanonicalAddress((HeaderAddress) event
.getRequest().getHeader(ToHeader.NAME));
if (this.tracer.isFineEnabled()) {
this.tracer
.fine("onRegisterEvent: address-of-record from request= "
+ sipAddressOfRecord);
}
final String sipAddress = getCanonicalAddress((HeaderAddress) event
.getRequest().getHeader(ToHeader.NAME));
final String callId = ((CallIdHeader) event.getRequest().getHeader(
CallIdHeader.NAME)).getCallId();
final long cSeq = ((CSeqHeader) event.getRequest().getHeader(
CSeqHeader.NAME)).getSeqNumber();
if (event.getRequest().getHeader(ContactHeader.NAME) == null) {
// Just send OK with current bindings - this request was a
// query.
if (this.tracer.isFineEnabled()) {
this.tracer.fine("query for bindings: sipAddress="
+ sipAddress);
}
try {
DataSourceChildSbbLocalInterface child = (DataSourceChildSbbLocalInterface) getChildRelation()
.create(ChildRelationExt.DEFAULT_CHILD_NAME);
child.getBindings(sipAddress);
} catch (Exception e) {
tracer.severe("Exception invoking data source child sbb.",
e);
aci.detach(sbbContextExt.getSbbLocalObject());
sendErrorResponse(Response.SERVER_INTERNAL_ERROR,
event.getServerTransaction());
}
return;
}
check if request is remove action, if so remove bindings from data base
// else its update/add/remove op
// do some prechecks before sending task to JDBC RA. JDBC exeutes
// batch in another set of threads. To avoid
// latency, lets check if we can deny REGISTER without pushing job
// to JDBC RA threads.
List<ContactHeader> newContacts = getContactHeaderList(event
.getRequest().getHeaders(ContactHeader.NAME));
final ExpiresHeader expiresHeader = event.getRequest().getExpires();
if (hasWildCard(newContacts)) {
if (this.tracer.isFineEnabled()) {
this.tracer.fine("Wildcard remove");
}
// This is a "Contact: *" "remove all bindings" request
if ((expiresHeader == null)
|| (expiresHeader.getExpires() != 0)
|| (newContacts.size() > 1)) {
// malformed request in RFC3261 ch10.3 step 6
aci.detach(sbbContextExt.getSbbLocalObject());
sendErrorResponse(Response.BAD_REQUEST,
event.getServerTransaction());
return;
}
// now do the work. in jdbc task
try {
DataSourceChildSbbLocalInterface child = (DataSourceChildSbbLocalInterface) getChildRelation()
.create(ChildRelationExt.DEFAULT_CHILD_NAME);
child.removeBindings(sipAddress, callId, cSeq);
} catch (Exception e) {
tracer.severe("Exception invoking data source child sbb.",
e);
aci.detach(sbbContextExt.getSbbLocalObject());
sendErrorResponse(Response.SERVER_INTERNAL_ERROR,
event.getServerTransaction());
return;
}
} else { ... }
check condition for udpate, update bindings, add,remove and send response
if(){
// ...
} else {
// Update bindings
if (this.tracer.isFineEnabled()) {
this.tracer.fine("Updating bindings");
}
ListIterator<ContactHeader> li = newContacts.listIterator();
while (li.hasNext()) {
final ContactHeader contact = (ContactHeader) li.next();
// get expires value, either in header or default
// do min-expires etc
long requestedExpires = 0;
if (contact.getExpires() >= 0) {
requestedExpires = contact.getExpires();
} else if ((expiresHeader != null)
&& (expiresHeader.getExpires() >= 0)) {
requestedExpires = expiresHeader.getExpires();
} else {
requestedExpires = 3600; // default
}
// If expires too large, reset to our local max
if (requestedExpires > maxExpires) {
requestedExpires = maxExpires;
} else if ((requestedExpires > 0)
&& (requestedExpires < minExpires)) {
// requested expiry too short, send response with
// min-expires
//
aci.detach(sbbContextExt.getSbbLocalObject());
sendErrorResponse(Response.INTERVAL_TOO_BRIEF,
event.getServerTransaction());
return;
}
try {
contact.setExpires((int) requestedExpires);
} catch (InvalidArgumentException e) {
tracer.severe("failed to set expires?!?!", e);
aci.detach(sbbContextExt.getSbbLocalObject());
sendErrorResponse(Response.SERVER_INTERNAL_ERROR,
event.getServerTransaction());
return;
}
// Get the q-value (preference) for this binding - default
// to 0.0 (min)
float q = 0;
if (contact.getQValue() != -1)
q = contact.getQValue();
if ((q > 1) || (q < 0)) {
aci.detach(sbbContextExt.getSbbLocalObject());
sendErrorResponse(Response.BAD_REQUEST,
event.getServerTransaction());
return;
}
}
// play with DB :)
try {
DataSourceChildSbbLocalInterface child = (DataSourceChildSbbLocalInterface) getChildRelation()
.create(ChildRelationExt.DEFAULT_CHILD_NAME);
child.updateBindings(sipAddress, callId, cSeq, newContacts);
} catch (Exception e) {
tracer.severe("Exception invoking data source child sbb.",
e);
aci.detach(sbbContextExt.getSbbLocalObject());
sendErrorResponse(Response.SERVER_INTERNAL_ERROR,
event.getServerTransaction());
return;
}
}
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:
@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);
}
}
}
@Override
public void getBindings(String address) {
executeTask(new GetBindingsJdbcTask(address, tracer));
}
@Override
public void removeBinding(String contact, String address) {
executeTask(new RemoveBindingJdbcTask(address, contact, tracer));
}
@Override
public void removeBindings(String address, String callId, long cSeq) {
executeTask(new RemoveBindingsJdbcTask(address, callId, cSeq, tracer));
}
@Override
public void updateBindings(String address, String callId, long cSeq,
List<ContactHeader> contacts) {
executeTask(new UpdateBindingsJdbcTask(address, callId, cSeq, contacts, tracer));
}
The DataSourceChild SBB
in this example has a parent. In this example, the parent is SIP Registrar SBB
.
The DataSourceChild SBB
accesses its parent by using Mobicents SLEE extension API:
final DataSourceParentSbbLocalInterface parent = (DataSourceParentSbbLocalInterface) sbbContextExt
.getSbbLocalObject().getParent();
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:
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);
}
}
}
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);
}
}
}
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);
}
}
}
The JdbcTaskExecutionThrowableEvent
handler is fairly simple as it only invokes parent:
public void onJdbcTaskExecutionThrowableEvent(
JdbcTaskExecutionThrowableEvent event, ActivityContextInterface aci) {
if (tracer.isWarningEnabled()) {
tracer.warning(
"Received a JdbcTaskExecutionThrowableEvent, as result of executed task "
+ event.getTask(), event.getThrowable());
}
// 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.callBackParentOnException(parent);
}
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);
}