public class AssessmentRun extends SwampThing{
    public AssessmentRun(Session session) {
        super(session);
    }
    public AssessmentRun(Session session, Map map) {
        super(session, map);
    }

    @Override
    protected SwampThing getNewInstance() {
        return new AssessmentRun(getSession());
    }

    @Override
    public String getIDKey() {
        return AssessmentRunHandler.ASSESSMENT_RUN_UUID;
    }


    public Project getProject() {
        return project;
    }

    public void setProject(Project project) {
        this.project = project;
    }

    public PackageThing getPkg() {
        return pkg;
    }

    public void setPkg(PackageThing pkg) {
        this.pkg = pkg;
    }

    public Platform getPlatform() {
        return platform;
    }

    public void setPlatform(Platform platform) {
        this.platform = platform;
    }

    public void setPlatformVersion(PlatformVersion platform_version) {
        this.platform_version = platform_version;
    }
    
    public Tool getTool() {
        return tool;
    }

    public void setTool(Tool tool) {
        this.tool = tool;
    }

    public String getPackageName() {
        return getConversionMap().getString("package_name");
    }
    
    public String getPackageVersion() {
        return getConversionMap().getString("package_version_string");
    }
    
    public String getToolName() {
        return getConversionMap().getString("tool_name");
    }
    
    public String getToolVersion() {
        return getConversionMap().getString("tool_version_string");
    }

    public String getPlatformName() {
        return getConversionMap().getString("platform_name");
    }
    
    public String getPlatformVersion() {
        return getConversionMap().getString("platform_version_string");
    }
    
    Project project;
    PackageThing pkg;
    Platform platform;
    PlatformVersion platform_version;
    Tool tool;

    @Override
    public String toString() {
        return "AssessmentRun[" +
                "uuid=" + getIdentifier() +
                ", project=" + (project==null?"none":getProject().getFullName())+
                ", pkg=" + (pkg==null?"none":getPkg().getName()) +
                ", platform=" + (platform==null?"none":getPlatform().getName()) +
                ", tool=" + (tool==null?"none":getTool().getName()) +
                "]";
    }
} public class Project extends SwampThing {


    @Override
    protected SwampThing getNewInstance() {
        return new Project(getSession());
    }

    @Override
    public String getIDKey() {
        return PROJECT_UID_KEY;
    }


    public Project(Session session) {
        super(session);
    }
    public Project(Session session, Map map) {
        super(session, map);
    }


    public String getDescription() {
        return getString(DESCRIPTION_KEY);
    }

    public void setDescription(String description) {
        put(DESCRIPTION_KEY, description);
    }

    public String getFullName() {
        return getString(FULL_NAME_KEY);
    }

    public void setFullName(String fullName) {
        put(FULL_NAME_KEY, fullName);
    }


    public String getShortName() {
        return getString(SHORT_NAME_KEY);
    }

    public void setShortName(String shortName) {
        put(SHORT_NAME_KEY, shortName);
    }

    public String getAffiliation() {
        return getString(AFFILIATION_KEY);
    }

    public void setAffiliation(String affiliation) {
        put(AFFILIATION_KEY, affiliation);
    }

    public Date getCreateDate() {
        return getDate(CREATE_DATE_KEY);
    }

    public void setCreateDate(Date createDate) {
        put(CREATE_DATE_KEY, createDate);
    }

    public Date getDenialDate() {
        return getDate(DENIAL_DATE_KEY);
    }

    public void setDenialDate(Date denialDate) {
        put(DENIAL_DATE_KEY, denialDate);
    }

    public Date getDeactivationDate() {
        return getDate((DEACTIVATION_DATE_KEY));
    }

    public void setDeactivationDate(Date deactivationDate) {
        put(DEACTIVATION_DATE_KEY, deactivationDate);
    }

    public String getOwnerUUID() {
        return getString(USER_UID_KEY);
    }

    public void setOwnerUUID(String ownerUUID) {
        put(USER_UID_KEY, ownerUUID);
    }

    public boolean isTrialProjectFlag() {
        return getBoolean(TRIAL_PROJECT_FLAG_KEY);
    }

    public void setTrialProjectFlag(boolean trialProjectFlag) {
        put(TRIAL_PROJECT_FLAG_KEY, trialProjectFlag);
    }

    @Override
    public String toString() {
        return "Project[name=" + getFullName() + ",description=" + getDescription() + ", owner id=" + getOwnerUUID() +
                ", create date=" + getCreateDate() + ", uuid=" + getIdentifier() + "]";
    }
} public class CommandLineOptionException extends SwampApiWrapperException {

	public CommandLineOptionException(Exception exception){
		super(exception);
		setExitCode(SwampApiWrapperExitCodes.INVALID_CLI_OPTIONS);
	}

	public CommandLineOptionException(String msg){
	    super(msg);
	    setExitCode(SwampApiWrapperExitCodes.INVALID_CLI_OPTIONS);
	}

} public class ConflictingNamesException extends SwampApiWrapperException {
	public ConflictingNamesException(Exception exception){
		super(exception);
		setExitCode(SwampApiWrapperExitCodes.CONFLICTING_NAME);
	}

	public ConflictingNamesException(String msg){
	    super(msg);
	    setExitCode(SwampApiWrapperExitCodes.CONFLICTING_NAME);
	}

} public class IncompatibleAssessmentTupleException extends SwampApiWrapperException {
	public IncompatibleAssessmentTupleException(Exception exception){
		super(exception);
		setExitCode(SwampApiWrapperExitCodes.INCOMPATIBLE_TUPLE);
	}

	public IncompatibleAssessmentTupleException(String msg){
	    super(msg);
	    setExitCode(SwampApiWrapperExitCodes.INCOMPATIBLE_TUPLE);
	}

} public class InvalidIdentifierException extends SwampApiWrapperException {
	public InvalidIdentifierException(Exception exception){
		super(exception);
		setExitCode(SwampApiWrapperExitCodes.INVALID_UUID);
	}

	public InvalidIdentifierException(String msg){
	    super(msg);
	    setExitCode(SwampApiWrapperExitCodes.INVALID_UUID);
	}

} public class InvalidNameException extends SwampApiWrapperException {
	public InvalidNameException(Exception exception){
		super(exception);
		setExitCode(SwampApiWrapperExitCodes.INVALID_NAME);
	}

	public InvalidNameException(String msg){
	    super(msg);
	    setExitCode(SwampApiWrapperExitCodes.INVALID_NAME);
	}

} public class SessionExpiredException extends SwampApiWrapperException {
	public SessionExpiredException(Exception exception){
		super(exception);
		setExitCode(SwampApiWrapperExitCodes.SESSION_EXPIRED);
	}
	
    public SessionExpiredException(String msg){
        super(msg);
        setExitCode(SwampApiWrapperExitCodes.SESSION_EXPIRED);
    }

} public enum SwampApiWrapperExitCodes {
	NO_ERRORS(0), 
	INVALID_CLI_OPTIONS(1),
	CLI_PARSER_ERROR(2),
	INVALID_UUID(3),
	INCOMPATIBLE_TUPLE(4),
	SESSION_EXPIRED(5),
	SESSION_RESTORE_ERROR(6),
	SESSION_SAVE_ERROR(7),
	NO_DEFAULT_PLATFORM(8),
	INVALID_NAME(9),
	CONFLICTING_NAME(10),
	TOOL_NO_PERMISSION(11),
	
	HTTP_EXCEPTION(20),
	HTTP_GENERAL_EXCEPTION(30),
	;
	private int exitCode;
	 
	public int getExitCode() {
		return exitCode;
	}

	protected void setExitCode(int exitCode) {
		this.exitCode = exitCode;
	}

	private SwampApiWrapperExitCodes(int exit_code) {
		setExitCode(exit_code);
	}
	
	public static int NormalizeHttpExitCode(int http_exit_code) {
		int exit_code = HTTP_EXCEPTION.getExitCode();
		
		if (http_exit_code >= 400 && http_exit_code < 500){
			exit_code = http_exit_code - 380;
		}else if (http_exit_code >= 500 && http_exit_code <= 599){
			exit_code = http_exit_code - 460;
		}
		return exit_code;
	}
} public enum AssessmentStatus {
	INPROGRESS,
	FAILED,
	SUCCESS,
	UNKNOWN;
	
	public static String getStatusString(AssessmentStatus status) {
		String str;
		
		switch (status) {
		case INPROGRESS:
			str = "Inprogess";
			break;
		case FAILED:
			str = "Failed";
			break;
		case SUCCESS:
			str = "Success";
			break;
		default:
			str = "Unknown";
			break;
		}
		
		return str;
	}
	
	private static boolean inList(List<String> status_list, String status_str) {
		for (String str : status_list) {
			if (str.equalsIgnoreCase(status_str)) {
				return true;
			}
		}
		return false;
	}
	
	public static AssessmentStatus translateAssessmentStatus(String status_str) {
		
		List<String> inprogess_status_list = Arrays.asList( "WAITING TO START",
				"SUBMITTING TO HTCONDOR",
				"Demand Queued",
				"Swamp Off Queued", 
				"Drain ReLaunch",
				"Drain ReQueued",
				"Creating HTCondor Job",
				"Waiting in HTCondor Queue",
				"Failed to submit to HTCondor",
				"Starting Virtual Machine",
				"Unable to Start VM",
				"vm failed - [start time] [current time] ([seconds between current and start]",
				"vm started and failed - [start time] [current time] ([seconds between current and start]",
				"vm [raw virsh command]",
				"vm [raw virsh command] failed",
				"Obtaining VM IP Address",
				"Obtaining Viewer Machine IP Address",
				"Obtained VM IP",
				"Failed to Obtain VM IP Address",
				"Starting Assessment Run Script", 
				"Executing cloc on package",
				"Performing Assessment",
				"Shutting Down the VM",
				"Shutting down the assessment machine",
				"Extracting Assessment Results",
				"Failed to extract assessment results",
				"Post-Processing",
				"Assessment failed (logged but not set as status)",
				"Assessment Passed (logged but not set as status)",
				"Assessment retry  (logged but not set as status)",
				"Assessment result not found",
				"Failed to parse assessment results",
				"Failed to preserve assessment results",
				"Failed to compute assessment result metrics",
				"Saving Results",
				"Failed to save assessment results in database",
				"Terminating"
				);
		
		List<String> failed_status_list = Arrays.asList("FAILED TO VALIDATE ASSESSMENT DATA",
				"FAILED TO START",
				"Finished with Errors",
				"Finished with Errors - Retry",
				"Terminated");
		
		List<String> success_status_list = Arrays.asList("Finished",
				"Finished with Warnings");
		
		if (inList(inprogess_status_list, status_str)) {
			// System.out.println("inprogress status: '" + status_str + "'");
			return AssessmentStatus.INPROGRESS;
		}
		
		if (inList(failed_status_list, status_str)) {
			return AssessmentStatus.FAILED;
		}
		
		if (inList(success_status_list, status_str)) {
			return AssessmentStatus.SUCCESS;
		}
		
		if (status_str.startsWith("Finish with Errors")) {
			return AssessmentStatus.FAILED;
		}
		
		if (status_str.startsWith("Finished")) {
			return AssessmentStatus.SUCCESS;
		}

		// System.out.println("unknown status: '" + status_str + "'");
		
		return AssessmentStatus.UNKNOWN;
	}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Pattern;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;
import org.continuousassurance.swamp.api.AssessmentRecord;
import org.continuousassurance.swamp.api.AssessmentRun;
import org.continuousassurance.swamp.api.PackageThing;
import org.continuousassurance.swamp.api.PackageVersion;
import org.continuousassurance.swamp.api.PlatformVersion;
import org.continuousassurance.swamp.api.Project;
import org.continuousassurance.swamp.api.Tool;
import org.continuousassurance.swamp.api.ToolVersion;
import org.continuousassurance.swamp.api.User;
import org.continuousassurance.swamp.cli.exceptions.CommandLineOptionException;
import org.continuousassurance.swamp.cli.exceptions.ConflictingNamesException;
import org.continuousassurance.swamp.cli.exceptions.IncompatibleAssessmentTupleException;
import org.continuousassurance.swamp.cli.exceptions.InvalidIdentifierException;
import org.continuousassurance.swamp.cli.exceptions.InvalidNameException;
import org.continuousassurance.swamp.cli.exceptions.SessionExpiredException;
import org.continuousassurance.swamp.cli.exceptions.SwampApiWrapperException;
import org.continuousassurance.swamp.cli.exceptions.SwampApiWrapperExitCodes;
import org.continuousassurance.swamp.cli.util.AssessmentStatus;
import org.continuousassurance.swamp.session.HTTPException;
import org.continuousassurance.swamp.session.util.Proxy;
import edu.uiuc.ncsa.security.core.exceptions.GeneralException;
                        }else if (arg_list.contains("--tool-uuid")) {
                            arg_list.add("-TL");
                            arg_list.add(arg_list.get(arg_list.indexOf("--tool-uuid") + 1));
                        }
                    }
                }
            }

            CommandLine parsed_options = new DefaultParser().parse(run_options, main_options.getArgList().toArray(new String[0]));
            cred_map.put("sub-command", "run");

            cred_map.put("quiet", parsed_options.hasOption("Q"));
            cred_map.put("package", parsed_options.getOptionValue("PK"));
            //cred_map.put("pkg-version", parsed_options.getOptionValue("PV"));
            cred_map.put("tool", Arrays.asList(parsed_options.getOptionValues("TL")));
            //cred_map.put("tool-version", parsed_options.getOptionValue("TV"));			
            if (parsed_options.hasOption("PL")){
                cred_map.put("platform", Arrays.asList(parsed_options.getOptionValues("PL")));
            }else if (parsed_options.hasOption("F")){
                cred_map.put("platform", Arrays.asList(parsed_options.getOptionValues("F")));
            }

            return cred_map;
        }else if (main_options.hasOption("L")){
            CommandLine parsed_options = new DefaultParser().parse(list_options, main_options.getArgList().toArray(new String[0]));
            cred_map.put("sub-command", "list");
            cred_map.put("quiet", parsed_options.hasOption("Q"));
            cred_map.put("verbose", parsed_options.hasOption("V"));
            cred_map.put("package", parsed_options.getOptionValue("PK"));
            cred_map.put("project", main_options.getOptionValue("PJ"));
            cred_map.put("tool", parsed_options.getOptionValue("TL"));
            cred_map.put("platform", parsed_options.getOptionValue("PL"));			

            return cred_map;
        }

        return cred_map;

    }

    public HashMap<String, Object> processCliArgs(String command, 
            ArrayList<String> cliArgs) throws CommandLineOptionException, ParseException, FileNotFoundException, IOException{

        HashMap<String, Object> opt_map = null;

        switch (command) {
        case SC_LOGIN:
            opt_map = loginOptionsHandler(command, cliArgs);
            break;
        case "package":
        case SC_PACKAGES:
            opt_map = packageOptionsHandler(command, cliArgs);
            break;
        case "project":
        case SC_PROJECTS:
            opt_map = projectOptionsHandler(command, cliArgs);
            break;
        case "tool":    
        case SC_TOOLS:
            opt_map = toolsOptionsHandler(command, cliArgs);
            break;
        case "assess":
        case SC_ASSESSMENTS:
            opt_map = assessmentOptionsHandler(command, cliArgs);
            break;
        case "platform":
        case SC_PLATFORMS:
            opt_map = platformOptionsHandler(command, cliArgs);
            break;
        case SC_RESULTS:
            opt_map = resultsOptionsHandler(command, cliArgs);
            break;
        case SC_STATUS:
            opt_map = statusOptionsHandler(command, cliArgs);
            break;
        case "user":
            opt_map = userOptionsHandler(command, cliArgs);
            break;
        case SC_LOGOUT:
            opt_map = logoutOptionsHandler(command, cliArgs);
            break;
        default:
            break;
        }
        return opt_map;
    }

    public void loginHandler(HashMap<String, Object> optMap) throws MalformedURLException {
        String host_name = (String)optMap.get("swamp-host");

        Proxy proxy = SwampApiWrapper.getProxy((String)optMap.get("proxy-scheme"),
                (String)optMap.get("proxy-host"),
                (String)optMap.get("proxy-port"),
                (String)optMap.get("proxy-user"),
                (String)optMap.get("proxy-password"));

        String user_uuid = apiWrapper.login((String)optMap.get("username"), 
                (String)optMap.get("password"),
                host_name,
                proxy,
                (String)optMap.get("keystore"));

        if (user_uuid != null){

            if ((boolean)optMap.get("quiet") == false) {
                System.out.println("Login successful");
            }

            apiWrapper.saveSession();
        }else {
            if ((boolean)optMap.get("quiet") == false) {
                System.out.println("Login failed");
            }
        }
    }

    public void printAllProjects(boolean quiet, boolean verbose) {
        if (verbose) {
            System.out.println(String.format("%-37s %-25s %-40s %-15s", 
                    "UUID",
                    "Project",