package se.chalmers.dat255.grupp12; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; /** * Created with IntelliJ IDEA. * User: Patrik * Date: 10/4/13 * Time: 1:48 PM * To change this template use File | Settings | File Templates. */ public class CommitController { private CommitHandler taskCommitHandler; private CommitHandler listCommitHandler; private ClientChangeList changes = new ClientChangeList(); private User user; /** * Constructor that sets the current user and creates new CommitHandlers * * @param sessionUser - The current user */ public CommitController(User sessionUser) { this.user = sessionUser; this.taskCommitHandler = new TaskCommitHandler(changes,user); this.listCommitHandler = new ListCommitHandler(changes,user); } /** * Performs the requested operations to the database and returns all the changes made * * @param element - A Json-array containing all the changes to be made * @return - A CommitChangeList containing all the changes made */ public synchronized ClientChangeList getChanges(JsonArray element) { Gson gson = new Gson(); for(JsonElement change : element){ Modification m = gson.fromJson(change, Modification.class); performOperation(m); } changes.setUserLists(user); return changes; } /** * Handles a Modification which contains an action and a change * Performs an operation depending on what the action of the modification contains * * @param m - The modification to be handled */ private void performOperation(Modification m) { String action = m.getAction(); CommitHandler handler; if (action.contains("TASK")) { handler = taskCommitHandler; } else { handler = listCommitHandler; } action = action.substring(0,action.length() - 4); switch (action) { case "ADD": { handler.insert(m); break; } case "CHANGE": { handler.update(m); break; } case "REMOVE": handler.delete(m); break; default: throw new UnsupportedOperationException("UNSUPPORTED OPERATION: " + action); } } }