package gvs.access;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Singleton;

/**
 * Guarantees that only one client can communicate with the service at a time.
 * 
 * @author mwieland
 */
@Singleton
public class ConnectionMonitor {

  private String currentOwnerAddress;

  private static final Logger logger = LoggerFactory
      .getLogger(ConnectionMonitor.class);

  /**
   * Reserves the service for a client address.
   * 
   * @param clientAddress
   *          client address
   * @return 0 if service was reserved <br>
   *         -1 if service is busy
   */
  public synchronized int reserveService(String clientAddress) {
    if (currentOwnerAddress == null) {
      currentOwnerAddress = clientAddress;
      logger.info("{} reserved the service.", currentOwnerAddress);
      return 0;
    } else {
      logger.info("Service is busy");
      return -1;
    }
  }

  /**
   * Release the service. <br>
   * Only the current owner of the service can release it for other clients.
   * 
   * @param clientAddress
   *          client address
   */
  public synchronized void releaseService(String clientAddress) {
    if (currentOwnerAddress == null) {
      logger.debug("Service already released.");
    } else if (currentOwnerAddress.equals(clientAddress)) {
      currentOwnerAddress = null;
      logger.info("Serivce will be released...");
    }
  }
}

@@ -595,16 +595,50 @@
 is busy%0A
+   * @throws InterruptedException%0A
    */%0A  
@@ -661,11 +661,12 @@
 zed 
-int
+void
  res
@@ -694,33 +694,70 @@
 ientAddress)
+%0A      throws InterruptedException
  %7B%0A    
-if
+while
  (currentOwn
@@ -758,33 +758,33 @@
 entOwnerAddress 
-=
+!
 = null) %7B%0A      
@@ -775,24 +775,43 @@
 = null) %7B%0A  
+    wait();%0A    %7D%0A%0A
     currentO
@@ -837,24 +837,39 @@
 tAddress;%0A  
+  notifyAll();%0A
     logger.i
@@ -926,98 +926,8 @@
 s);%0A
-      return 0;%0A    %7D else %7B%0A      logger.info(%22Service is busy%22);%0A      return -1;%0A    %7D%0A
   %7D%0A
@@ -1183,35 +1183,29 @@
    if (c
-urrentOwner
+lient
 Address 
 == null)
@@ -1200,95 +1200,25 @@
 ess 
-=
+!
 = null
-) %7B%0A      logger.debug(%22Service already released.%22);%0A    %7D else if (currentOwner
+ && client
 Addr
@@ -1229,21 +1229,27 @@
 equals(c
-lient
+urrentOwner
 Address)
@@ -1312,41 +1312,138 @@
 %22Ser
-i
 v
+i
 ce 
-will be released...%22);%0A    %7D
+released: %22 + clientAddress);%0A    %7D%0A  %7D%0A%0A  public synchronized boolean isReserved() %7B%0A    return currentOwnerAddress != null;
 %0A  %7D

add synchronazation to connection monitor