001 package crisp.wbwiki.client; 002 003 import com.google.gwt.user.client.rpc.AsyncCallback; 004 005 public class ClientStateManager { 006 /** The last page version loaded from the server */ 007 private Page lastLoadedPage = null; 008 private final WikiServiceAsync wikiService; 009 private static boolean loggingEnabled = true; 010 011 012 public ClientStateManager(final WikiServiceAsync wikiService) { 013 this.wikiService = wikiService; 014 } 015 016 public void synchronizeWithServer(final WikiGui gui) { 017 String currentContent = gui.getCurrentContent(); 018 019 final Integer lastLoadedVersion; 020 final String contentToSendToServer; 021 if (lastLoadedPage == null) { 022 lastLoadedVersion = null; 023 contentToSendToServer = null; 024 } else { 025 lastLoadedVersion = new Integer(lastLoadedPage.getVersion()); 026 if (lastLoadedPage.getContent().equals(currentContent)) { 027 contentToSendToServer = null; 028 } else { 029 log(gui, "Content has changed!\nold: '" + lastLoadedPage.getContent() + "'\nnew: '" + currentContent + "'"); 030 contentToSendToServer = currentContent; 031 } 032 } 033 log(gui, "Calling synchronize(" + lastLoadedVersion + ", " + contentToSendToServer + ")"); 034 wikiService.synchronize( 035 lastLoadedVersion, 036 contentToSendToServer, 037 new AsyncCallback() { 038 public void onFailure(Throwable err) { 039 //TODO error handling 040 err.printStackTrace(); 041 } 042 public void onSuccess(Object response) { 043 Page updatedPage = (Page) response; 044 log(gui, "Received response: " + updatedPage); 045 if (updatedPage == null) { 046 //The server didn't feel any need to give me an updated page 047 if (contentToSendToServer == null) { 048 //I didn't send any content to the server, 049 //so nothing has changed by me or anybody else. 050 //So we do nothing. 051 } else { 052 //Nothing has changed on the server side, 053 //but I sent new content so the version number was updated. 054 lastLoadedPage = new Page( 055 lastLoadedPage.getVersion() + 1, 056 contentToSendToServer 057 ); 058 } 059 } else { 060 //I received an updated page from the server, 061 //so someone else has been changing the page! 062 //Need to update my state. 063 lastLoadedPage = updatedPage; 064 gui.setCurrentContent(updatedPage.getContent()); 065 } 066 } 067 } 068 ); 069 } 070 071 void log(WikiGui gui, String logEntry) { 072 if (loggingEnabled) { 073 gui.log(logEntry); 074 } 075 } 076 077 }