package shoehorn;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Ryan Brainard
 */
public class Shoehorn {

    private final Map<String, String> feet;
    private final Map<String, String> mappings;

    public Shoehorn(Map<String, String> feet, Map<String, String> mappings) {
        this.feet = feet;
        this.mappings = mappings;
    }

    void shoehorn() {
        for (Map.Entry<String, String> foot : feet.entrySet()) {
            if (!mappings.containsKey(foot.getKey())) {
                continue;
            }

            final String shoeKey;
            if (mappings.get(foot.getKey()).trim().equals("")) {
                shoeKey = foot.getKey();
            } else {
                shoeKey = mappings.get(foot.getKey());
            }

            System.setProperty(shoeKey, foot.getValue());
            System.out.println("Shoehorned [" + foot.getKey() + "] into [" + shoeKey + "]");
        }
    }

    public static void premain(String agentArgs) {
        new Shoehorn(System.getenv(), getMappings("shoehorn.map")).shoehorn();
    }

    static Map<String, String> getMappings(String mapFilePath) {
        final Properties mappingsAsProps = new Properties();
        final File mapFile = new File(mapFilePath);

        InputStream mapFileStream = null;
        try {
            mapFileStream = new FileInputStream(mapFile);
            mappingsAsProps.load(mapFileStream);
            System.out.println("Loaded shoehorn mappings: " + mapFilePath);
        } catch (FileNotFoundException e) {
            System.err.println("Could not find shoehorn mappings: " + mapFilePath);
        } catch (IOException e) {
            System.err.println("Failed to load shoehorn mappings: " + mapFilePath);
        } finally {
            if (mapFileStream != null) {
                try {
                    mapFileStream.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }

        final Map<String, String> mappings = new HashMap<String, String>();
        for (Map.Entry<Object, Object> prop : mappingsAsProps.entrySet()) {
            mappings.put(prop.getKey().toString(), prop.getValue().toString());
        }

        return mappings;
    }
}

@@ -166,16 +166,87 @@
 horn %7B%0A%0A
+    public static final String DEFAULT_MAP_FILE_PATH = %22shoehorn.map%22;%0A
     priv
@@ -1105,24 +1105,114 @@
 gentArgs) %7B%0A
+        final String mapFilePath = agentArgs != null ? agentArgs : DEFAULT_MAP_FILE_PATH;%0A
         new 
@@ -1249,30 +1249,27 @@
 appings(
-%22shoehorn.map%22
+mapFilePath
 )).shoeh

allow users to override map file path