Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Web Development

AJAX & Record Locking


Lock Handling

Recall that all pages initially load as read-only. The lock-handling logic on the client behaves like this: If the page is in view mode, then see right away if the lock for the current record is owned by anyone, and spawn a timer to repeatedly test the lock status of the page. If not in view mode, then verify that the current user owns the lock for the given record. The values for parameters such as <%=curRecId%> and <%=person%> are given to the page as part of the JSP session values:


if('<%=mode%>' == 'view') 
{
  requestLockAction("status","<%=curRecId%>","anyone");
  spawnLockStatusTimer("<%=curRecId%>", 5);
}
else requestLockAction("lock","<%=curRecId%>","<%=person%>");


The work of communicating with the server is done in the requestLockAction(request,id,owner) function. If the client page simply wants to know the status of the lock for the given page, it will take the first branch of logic. However, if the client is asking for the lock (or relinquishing it), it takes the second branch of logic. Notice that we first assign the response handlers according to the request type, then invoke the contentLoader.load function. The response handlers handleLockStatus and handleLockRequest are functions defined elsewhere in the JavaScript.


function requestLockAction(request,id,owner)
{
   // call back for request for lock status
   if(request == "status")
   {
      contentLoader.setResponseHandler(handleLockStatus);
   }
   // call back for request to obtain or release a lock
   else
   {
      contentLoader.setResponseHandler(handleLockRequest);
   }
   // automatically submit asynchronous POST request to server
   contentLoader.load("/xpe/xpe/lockPage?request=
        "+request+"&id="+id+"&owner="+owner);
}

For a user who is asking for the lock (a user who clicked the Edit button) the callback handler is the handleLockRequest function. In this case, the server's response is the message "owned" if the lock request succeeded. It could be the message "locked" if the lock was owned by someone other than the requester. If a user is relinquishing the lock, the server's response indicating success would be the message "unlocked."


function handleLockRequest(reply)
{
    var values = reply.split("~");

    // If the user does not own 
    // thisrecord lock, spawn a 
    // timer to watch changes 
    // in it
    // 
    if(values[0] != 'owned')
    {
        spawnLockStatusTimer
            ("<%=curRecId%>", 5);
    }
    if(values[0] == "locked")
    {
        lockThisRecordOnClient
            (true, values[1]);
    }
    else if(values[0] == "unlocked")
    {
        lockThisRecordOnClient(false);
    }
}

Listing Three (available at http://www.ddj.com/code/) is the function lockThisRecordOnClient(lock, owner). This code simply hides or shows the Edit button. If the button is hidden because a record is being edited by someone else, then an alert lets the record viewer know who has locked the record. The request to the server can also be a request for the status of the lock of the given record, for which the callback handler would call the handleLockStatus function. This is going to be the most common request, as it will be made repeatedly by the timed loop running on the page as a result of the call to spawnLockStatusTimer("<%=curRecId%>",5).

This function handles the server message "noSession" by stopping the looping request timer clock. This only happens when users let a session timeout. The server detects the session timeout and forces the lock to be freed for whatever record it was held on. The client, however, could just sit there polling the server endlessly, so you merely abort the timer loop if this circumstance takes place:

     
function handleLockStatus(status)
{
    var values = status.split("~");
    if(values[0] == "locked")
    {
        lockThisRecordOnClient(true,
            values[1]);
    }
    else if(values[0] == "unlocked")
    {
        lockThisRecordOnClient(false);
    }
    else if(values[0] == "noSession") 
        stopTheClock();
}


The penultimate point to cover is the looped status check (see Listing Four, also available in the source code area). This loop is initiated by the function spawnLockStatusTimer(id, seconds), which establishes for the timer what record ID to periodically check the status of, and the number of seconds to delay between checks. It invokes the startTheTimer() function, which uses window.setTimeout to call back to itself every second, counting down the seconds until it should invoke requestLockAction("status",rec_id,"anyone"). The whole thing is controlled by the timerRunning variable, which can be used to abort the timer process. The third argument to requestLockAction signifies to the server that this client doesn't care who the owner is, just that it wonders if anyone does own the lock for the current record.

Finally, what if a user locks a record, then navigates to a page unrelated to that record without unlocking it? There are two scenarios, one of which is that users navigate out of the web application altogether, the other that users navigate to another page within the web application. Before addressing these, assume users have locked a record and made changes. In our applications, the only way to ensure those changes are saved back to the database is to click the Submit button. This frees the lock on the server by removing the owner and record ID from the map, and returns the read-only view of the just-modified record.

If a user puts a record in edit mode, makes changes, then navigates to another page within the web application, the new client page is a view-only reader page that handles this by telling the server to clear the map of locks owned by the user. In effect it says, "check for any locks owned by this guy, and if you find any, free them because he is no longer editing that record." If a user navigates out of the web application altogether, there is nothing we can do about it. Eventually, however, the user's session within the application will timeout, and any lock will be freed. We also provide an administrator's panel that shows who is viewing or editing what page in the application, and can be used to kick users out of the application altogether by ending their sessions.

DDJ


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.