<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE Rule PUBLIC "sailpoint.dtd" "sailpoint.dtd">
<Rule language="beanshell" name="ContractorLatestEndDateBuildMap" type="BuildMap">
  <Description>Pre-scans a delimited file once per aggregation on IIQ or VA file sources, filters valid contractor IDs, and caches the row with the latest EndDate inside state.</Description>
  <Signature returnType="Map">
    <Inputs>
      <Argument name="cols" type="java.util.List">
        <Description>Ordered list of column names from the file header.</Description>
      </Argument>
      <Argument name="record" type="java.util.List">
        <Description>Ordered list of values for the current record.</Description>
      </Argument>
      <Argument name="application" type="sailpoint.object.Application">
        <Description>Application object.</Description>
      </Argument>
      <Argument name="schema" type="sailpoint.object.Schema">
        <Description>Schema reference for the delimited file source.</Description>
      </Argument>
      <Argument name="state" type="java.util.Map">
        <Description>Shared state map persisting across rows during aggregation.</Description>
      </Argument>
    </Inputs>
    <Returns>
      <Argument name="map" type="java.util.Map">
        <Description>Map of attributes representing the processed account row.</Description>
      </Argument>
    </Returns>
  </Signature>
  <Source><![CDATA[
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import sailpoint.tools.Util;
import sailpoint.connector.DelimitedFileConnector;

List parseDelimitedLine(String line, String delimiter) {
    List list = new ArrayList();
    if (line == null) return list;
    char delim = (delimiter != null && delimiter.length() > 0) ? delimiter.charAt(0) : ',';
    if (delimiter != null && (delimiter.equals("\\t") || delimiter.equals("\t"))) delim = '\t';
    boolean inQuotes = false;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < line.length(); i++) {
        char c = line.charAt(i);
        if (c == '"') {
            inQuotes = !inQuotes;
        } else if (c == delim && !inQuotes) {
            list.add(sb.toString().trim());
            sb.setLength(0);
        } else {
            sb.append(c);
        }
    }
    list.add(sb.toString().trim());
    return list;
}

Date parseDate(String val) {
    if (Util.isNullOrEmpty(val)) return null;
    try {
        return new SimpleDateFormat("MM/dd/yyyy").parse(val.trim());
    } catch (Exception e) {
        return null;
    }
}

String uniqueKey = "WorkerUserName";
Map map = DelimitedFileConnector.defaultBuildMap(cols, record);

if (state == null) return map;

String username = (String) map.get(uniqueKey);

if (Util.isNullOrEmpty(username)) return new HashMap();
// If header row, just return empty map
if (uniqueKey.equalsIgnoreCase(username.trim())) {
    return new HashMap();
}

boolean isProperContractorId = username.trim().matches("(?i)^x\\d{3}.*");

Map filteredMap = (Map) state.get("filteredMap");
String filePath = null;

if (filteredMap == null) {
    filteredMap = new HashMap();
    filePath = (String) application.getAttributeValue("file");

    if (filePath != null) {
        BufferedReader reader = null;
        try {
            String delimiter = (String) application.getAttributeValue("group.delimiter");
            if (delimiter == null) delimiter = ",";
            int linesToSkip = 0;
            Object skipObj = application.getAttributeValue("numberOfLinesToSkip");
            if (skipObj instanceof Number) {
                linesToSkip = ((Number) skipObj).intValue();
            } else if (skipObj instanceof String) {
                try {
                    linesToSkip = Integer.parseInt((String) skipObj);
                } catch (Exception e) {
                }
            }
            String commentChar = (String) application.getAttributeValue("commentCharacter");
            reader = new BufferedReader(new FileReader(filePath));
            String line;
            int currentLine = 0;
            List fileCols = null;
            while (currentLine < linesToSkip && (line = reader.readLine()) != null) {
                if (commentChar != null && line.startsWith(commentChar)) continue;
                fileCols = parseDelimitedLine(line, delimiter);
                currentLine++;
            }
            while ((line = reader.readLine()) != null) {
                currentLine++;
                if (commentChar != null && line.startsWith(commentChar)) continue;
                if (fileCols != null && !fileCols.isEmpty()) {
                    List fileRecord = parseDelimitedLine(line, delimiter);
                    Map rowMap = DelimitedFileConnector.defaultBuildMap(fileCols, fileRecord);
                    if (rowMap != null) {
                        String user = (String) rowMap.get(uniqueKey);
                        if (Util.isNotNullOrEmpty(user)) {
                            boolean isRowContractor = user.trim().matches("(?i)^x\\d{3}.*");
                            if (isRowContractor) {
                                Map existingMap = (Map) filteredMap.get(user);
                                if (existingMap == null) {
                                    filteredMap.put(user, rowMap);
                                } else {
                                    Date newEnd = parseDate((String) rowMap.get("EndDate"));
                                    Date existingEnd = parseDate((String) existingMap.get("EndDate"));
                                    if (newEnd != null && existingEnd != null) {
                                        if (newEnd.after(existingEnd)) {
                                            filteredMap.put(user, rowMap);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    throw new Exception("Unable to find header items: " + fileCols);
                }
            }
            state.put("filteredMap", filteredMap);
        } catch (Exception e) {
            throw new Exception("Unknown Error: " + e.getMessage());
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    } else {
        throw new Exception("Filepath not defined");
    }
}

if (!isProperContractorId) {
    return new HashMap();
}

filteredMap = (Map) state.get("filteredMap");
Map returnMap = (Map) filteredMap.get(username);
if (returnMap == null && isProperContractorId) {
    throw new Exception("Username '" + username + "' not found in file: '" + filePath);
} else if (returnMap == null) {
    returnMap = new HashMap();
}

return returnMap;
  ]]></Source>
</Rule>
