<commit_before>/**
 * 
 */
package org.commcare.restore;

import java.util.Hashtable;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;

import org.commcare.model.PeriodicEvent;
import org.commcare.resources.model.CommCareOTARestoreListener;
import org.commcare.util.CommCareRestorer;
import org.commcare.util.CommCareUtil;
import org.commcare.util.time.AutoSyncEvent;
import org.javarosa.core.log.WrappedException;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.storage.IStorageIterator;
import org.javarosa.core.services.storage.StorageManager;
import org.javarosa.core.services.storage.StorageModifiedException;
import org.javarosa.j2me.log.CrashHandler;
import org.javarosa.j2me.log.HandledCommandListener;
import org.javarosa.j2me.view.J2MEDisplay;
import org.javarosa.service.transport.securehttp.AuthenticatedHttpTransportMessage;
import org.javarosa.service.transport.securehttp.DefaultHttpCredentialProvider;
import org.javarosa.service.transport.securehttp.HttpAuthenticator;
import org.javarosa.user.model.User;

/**
 * 
 * This class is a huge quagmire of interlinking completely coupled method stacks. Rewrite to have clear
 * workflow v. functional chunks
 * @author ctsims
 * 
 * This class now handles requests for restoring, passing them into the asynchronous class
 * CommCareRestorer, acting as the listener, and updating the CommCareOTARestoreView
 *
 *@author wspride
 */
public class CommCareOTARestoreController implements HandledCommandListener, CommCareOTARestoreListener {
	
	CommCareOTACredentialEntry entry;
	CommCareOTARestoreView view;
	CommCareOTAFailView fView;
	CommCareRestorer mRestorer;
	
	CommCareOTARestoreTransitions transitions;
	
	int authAttempts = 0;
	String restoreURI;
	boolean noPartial;
	boolean isSync;
	int[] caseTallies;
	int totalItemCount = -1;
	
	HttpAuthenticator authenticator;
	boolean errorsOccurred;
	String syncToken;
	String originalRestoreURI;
	String logSubmitURI;
	String stateHash;
	
	public CommCareOTARestoreController(CommCareOTARestoreTransitions transitions, String restoreURI) {
		this(transitions, restoreURI, null);
	}
	
	public CommCareOTARestoreController(CommCareOTARestoreTransitions transitions, String restoreURI, HttpAuthenticator authenticator) {
		this(transitions, restoreURI, authenticator, false, false, null, null);
	}
				
	public CommCareOTARestoreController(CommCareOTARestoreTransitions transitions, String restoreURI,
			HttpAuthenticator authenticator, boolean isSync, boolean noPartial, String syncToken, String logSubmitURI) {

		view = new CommCareOTARestoreView(Localization.get("intro.restore"));
		view.setCommandListener(this);
		
		fView = new CommCareOTAFailView(Localization.get("intro.restore"));
		fView.setCommandListener(this);
		
		entry = new CommCareOTACredentialEntry(Localization.get("intro.restore"));
		entry.setCommandListener(this);
		
		mRestorer = new CommCareRestorer();
		
		this.transitions = transitions;
		this.restoreURI = restoreURI;
		this.authenticator = authenticator;
		this.isSync = isSync;
		this.noPartial = noPartial;
		this.syncToken = syncToken;
		this.logSubmitURI = logSubmitURI;
		
	}
	
	public void start() {
		entry.setInteractive(false);
		mRestorer.initialize(this, transitions, restoreURI, authenticator, isSync, noPartial, syncToken, logSubmitURI);
	}
	
	protected String getCacheRef() {
		return "jr://file/commcare_ota_backup.xml";
	}
	

	public void _commandAction(Command c, Displayable d) {
		System.out.println("Command action, c: " + c.getLabel() + ", d: " + d.getTitle());
		if(c.equals(CommCareOTACredentialEntry.DOWNLOAD)) {
			if(userExists(entry.getUsername()) && !isSync) {
				entry.sendMessage(Localization.get("restore.user.exists"));
				return;
			}
			this.authenticator = new HttpAuthenticator(CommCareUtil.wrapCredentialProvider(new DefaultHttpCredentialProvider(entry.getUsername(), entry.getPassword())), false);
			entry.setInteractive(false);
			mRestorer.initialize(this, transitions, restoreURI, authenticator, isSync, noPartial, syncToken, logSubmitURI);
			//tryDownload(getClientMessage());
		} else if(d == entry && c.equals(CommCareOTACredentialEntry.CANCEL)) {
			transitions.cancel();
		} else if(c.equals(view.FINISHED)) {
			PeriodicEvent.markTriggered(new AutoSyncEvent());
			transitions.done(errorsOccurred);
		}
		else if(c.equals(CommCareOTAFailView.DOWNLOAD)){
			entry.setInteractive(false);
			mRestorer.initialize(this, transitions, restoreURI, authenticator, isSync, noPartial, syncToken, logSubmitURI);
		}
		else if(c.equals(CommCareOTAFailView.CANCEL)){
			System.out.println("entered cancel!");
			transitions.cancel();
		}
	}
	
	private boolean userExists(String username) {
		int attempts = 0;
		//An absurd number of tries
		while(attempts < 50) {
			try{
				IStorageIterator iterator = StorageManager.getStorage(User.STORAGE_KEY).iterate();
				while(iterator.hasMore()) {
					User u = (User)iterator.nextRecord();
					if(username.toLowerCase().equals(u.getUsername().toLowerCase())) {
						return true;
					}
				}
				return false;
			}
			catch(StorageModifiedException sme) {
				//storage modified while we were going through users. Try again
				attempts++;
			}
		}
		//Dunno what to do here, really, it would be crazy to gt to this point.
		//Maybe should throw an exception, actually.
		Logger.log("restore", "Could not look through User list to determine if user " + username + " exists.");<commit_msg>cleaned up sysouts<commit_after>/**
 * 
 */
package org.commcare.restore;

import java.util.Hashtable;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;

import org.commcare.model.PeriodicEvent;
import org.commcare.resources.model.CommCareOTARestoreListener;
import org.commcare.util.CommCareRestorer;
import org.commcare.util.CommCareUtil;
import org.commcare.util.time.AutoSyncEvent;
import org.javarosa.core.log.WrappedException;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.storage.IStorageIterator;
import org.javarosa.core.services.storage.StorageManager;
import org.javarosa.core.services.storage.StorageModifiedException;
import org.javarosa.j2me.log.CrashHandler;
import org.javarosa.j2me.log.HandledCommandListener;
import org.javarosa.j2me.view.J2MEDisplay;
import org.javarosa.service.transport.securehttp.AuthenticatedHttpTransportMessage;
import org.javarosa.service.transport.securehttp.DefaultHttpCredentialProvider;
import org.javarosa.service.transport.securehttp.HttpAuthenticator;
import org.javarosa.user.model.User;

/**
 * 
 * This class is a huge quagmire of interlinking completely coupled method stacks. Rewrite to have clear
 * workflow v. functional chunks
 * @author ctsims
 * 
 * This class now handles requests for restoring, passing them into the asynchronous class
 * CommCareRestorer, acting as the listener, and updating the CommCareOTARestoreView
 *
 *@author wspride
 */
public class CommCareOTARestoreController implements HandledCommandListener, CommCareOTARestoreListener {
	
	CommCareOTACredentialEntry entry;
	CommCareOTARestoreView view;
	CommCareOTAFailView fView;
	CommCareRestorer mRestorer;
	
	CommCareOTARestoreTransitions transitions;
	
	int authAttempts = 0;
	String restoreURI;
	boolean noPartial;
	boolean isSync;
	int[] caseTallies;
	int totalItemCount = -1;
	
	HttpAuthenticator authenticator;
	boolean errorsOccurred;
	String syncToken;
	String originalRestoreURI;
	String logSubmitURI;
	String stateHash;
	
	public CommCareOTARestoreController(CommCareOTARestoreTransitions transitions, String restoreURI) {
		this(transitions, restoreURI, null);
	}
	
	public CommCareOTARestoreController(CommCareOTARestoreTransitions transitions, String restoreURI, HttpAuthenticator authenticator) {
		this(transitions, restoreURI, authenticator, false, false, null, null);
	}
				
	public CommCareOTARestoreController(CommCareOTARestoreTransitions transitions, String restoreURI,
			HttpAuthenticator authenticator, boolean isSync, boolean noPartial, String syncToken, String logSubmitURI) {

		view = new CommCareOTARestoreView(Localization.get("intro.restore"));
		view.setCommandListener(this);
		
		fView = new CommCareOTAFailView(Localization.get("intro.restore"));
		fView.setCommandListener(this);
		
		entry = new CommCareOTACredentialEntry(Localization.get("intro.restore"));
		entry.setCommandListener(this);
		
		mRestorer = new CommCareRestorer();
		
		this.transitions = transitions;
		this.restoreURI = restoreURI;
		this.authenticator = authenticator;
		this.isSync = isSync;
		this.noPartial = noPartial;
		this.syncToken = syncToken;
		this.logSubmitURI = logSubmitURI;
		
	}
	
	public void start() {
		entry.setInteractive(false);
		mRestorer.initialize(this, transitions, restoreURI, authenticator, isSync, noPartial, syncToken, logSubmitURI);
	}
	
	protected String getCacheRef() {
		return "jr://file/commcare_ota_backup.xml";
	}
	

	public void _commandAction(Command c, Displayable d) {
		if(c.equals(CommCareOTACredentialEntry.DOWNLOAD)) {
			if(userExists(entry.getUsername()) && !isSync) {
				entry.sendMessage(Localization.get("restore.user.exists"));
				return;
			}
			this.authenticator = new HttpAuthenticator(CommCareUtil.wrapCredentialProvider(new DefaultHttpCredentialProvider(entry.getUsername(), entry.getPassword())), false);
			entry.setInteractive(false);
			mRestorer.initialize(this, transitions, restoreURI, authenticator, isSync, noPartial, syncToken, logSubmitURI);
			//tryDownload(getClientMessage());
		} else if(d == entry && c.equals(CommCareOTACredentialEntry.CANCEL)) {
			transitions.cancel();
		} else if(c.equals(view.FINISHED)) {
			PeriodicEvent.markTriggered(new AutoSyncEvent());
			transitions.done(errorsOccurred);
		}
		else if(c.equals(CommCareOTAFailView.DOWNLOAD)){
			entry.setInteractive(false);
			mRestorer.initialize(this, transitions, restoreURI, authenticator, isSync, noPartial, syncToken, logSubmitURI);
		}
		else if(c.equals(CommCareOTAFailView.CANCEL)){
			transitions.cancel();
		}
	}
	
	private boolean userExists(String username) {
		int attempts = 0;
		//An absurd number of tries
		while(attempts < 50) {
			try{
				IStorageIterator iterator = StorageManager.getStorage(User.STORAGE_KEY).iterate();
				while(iterator.hasMore()) {
					User u = (User)iterator.nextRecord();
					if(username.toLowerCase().equals(u.getUsername().toLowerCase())) {
						return true;
					}
				}
				return false;
			}
			catch(StorageModifiedException sme) {
				//storage modified while we were going through users. Try again
				attempts++;
			}
		}
		//Dunno what to do here, really, it would be crazy to gt to this point.
		//Maybe should throw an exception, actually.
		Logger.log("restore", "Could not look through User list to determine if user " + username + " exists.");
{'fraction_non_alphanumeric': 0.09939704001461722, 'fraction_numerical': 0.0016444363237712407, 'mean_word_length': 5.416764361078546, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5045233', 'n_tokens_mistral': 3691, 'n_tokens_neox': 3284, 'n_words': 691}