+
+ private boolean isLastActiveClient(SimpleClient client)
+ {
+ log.debug("Testing if current client is the last one.");
+ log.debug("current client lockfile is '"+client.getClientlockFile()+"'");
+ boolean noOtherActiveClient = true;
+ //create, if need, subdirectory to contain client files
+ File clientlockFileDir = new File (this.sessionDir, clientFileDirectory);
+ if( !clientlockFileDir.exists())
+ {
+ log.error("Something wrong the active client file does not exits... should not happen");
+ return false;
+ }
+
+ try {
+
+ //no check every file in the directory and try to get lock on it.
+ File [] clientFiles = clientlockFileDir.listFiles();
+ if(clientFiles == null || clientFiles.length==0)
+ {//there is not file on the directory. the current client should be the last one.
+ return true;
+ }
+
+ for (int i = clientFiles.length - 1; i>-1&& noOtherActiveClient ;i--)
+ {
+ File clientFile = clientFiles[i];
+ log.debug("testing file for lock: "+clientFile.getAbsolutePath());
+ if(client.getClientLock().isTargetLockFile(clientFile))
+ {
+ log.debug("current client file found");
+ continue;
+ }
+ if (clientFile != null && clientFile.exists() )
+ {
+ try
+ {
+ log.debug("Try to acquire a lock on the file");
+ // Get a file channel for the file
+ FileChannel channel = new RandomAccessFile(clientFile, "rw").getChannel();
+
+ // Use the file channel to create a lock on the file.
+ // This method blocks until it can retrieve the lock.
+ // java.nio.channels.FileLock activeClientFilelock = channel.lock();
+
+ // Try acquiring the lock without blocking. This method returns
+ // null or throws an exception if the file is already locked.
+ try
+ {
+ java.nio.channels.FileLock activeClientFilelock = channel.tryLock();
+
+ //the lock has been acquired.
+ //the file was not lock and so the corresponding application seems to have die
+ if(activeClientFilelock != null)
+ {
+ log.debug("lock obtained : file must be from a crashed application");
+
+
+ activeClientFilelock.release();
+ log.debug("lock released");
+
+ channel.close();
+ log.debug("channel closed");
+
+ //delete file
+ clientFile.delete();
+ log.debug("crashed application file deleted");
+
+ }
+ else
+ {
+ noOtherActiveClient = false;
+ log.debug("lock not obtained : another application is active");
+ }
+ }
+ catch (OverlappingFileLockException e)
+ {
+ // File is already locked in this thread or virtual machine
+ //that the expected behaviour
+ log.debug("lock not accessible ",e);
+ }
+ }
+ catch (Exception e)
+ {
+ log.debug("error during lock testing ",e);
+ }
+ }
+ }
+
+ } catch (Exception e) {
+ log.error("error during counting active clients");
+ }
+ return noOtherActiveClient;
+ }