views:

178

answers:

2

Hello, I have an application that allows multiple users to access 1 xml file. The problem is that when all the users save at once the other changes by other users does not get saved. How do I detect if the file is in user in groovy?

Thanks!

+2  A: 

This issue has nothing specifically to do with groovy/grails, but is just a fundamental problem of concurrent file modification. You should handle this problem in the same way as a source code control system (SCCS) such as SVN or CVS.

Specifically, store the time that a file was last modified. This could be stored in the file itself, in the file's metadata, or in another file that is is provided each time the XML file is uploaded. When a user uploads a file, check if it has been modified (by another user) since he obtained the copy. If it has, you have a number of choices:

  • Give him the most recent copy and tell him to merge the changes himself (this is what a crappy SCCS will do)
  • Try and automatically merge the changes if they don't conflict (this is what a better SCCS will do). If there are conflicts, these will need to be resolved manually by the user.

One approach (which might be overkill) would be to actually use a SCCS to handle this versioning problem. There is a Java API for CVS (and probably for other SCCSs), that enables you to programatically checkin, checkout and merge a file.

This suggestion assumes that you need to allow concurrent modification of the file. If you don't then it would be simpler to solve the problem using an approach that prohibits simultaneous modification.

Update: Some information about the version property that one of the commenters mentioned is available in sections 5.3.5 and 5.5.2.7 of the Grails reference manual

Don
If they are editing it through a webpage, and the xml file has a domain object, you could use the version attribute for option 1 ;)
tim_yates
Hi Tim, have you got any good links about the version attribute? Had a quick look on Google and Definitive Guide to Grails book, and it definitely sounds like a good way to identify instances of concurrent modification but Wikipedia says (http://en.wikipedia.org/wiki/Optimistic_concurrency_control) that it might not be the most efficient way to handle it. Also a worked example would be handy :-)
Alison
A: 

Another approach: maintain a global scoped hashmap containing file -> user mappings (or just a list of files if it's not relevant which user has locked the file). If an user tries to open a file:

  1. check if this file is already contained in the map
  2. if so, deny the attempt and do some error handling
  3. if not, add an entry to the map
  4. open the file and do the work
  5. after saving the file, the respective entry should be removed from the map

Such a global scoped hashmap might be stored as an attribute in the ServletContext. See also this.

Stefan
thanks for the inputs guys! I really appreciate it.
Anthony Umpad