/* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. */

package com.amazonaws.services.lambda.runtime.api.client;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

class CustomerClassLoader extends URLClassLoader {
    /**
     * This Comparator is used to ensure that jars added to this classloader are added in a deterministic order which
     * does not depend on the underlying filesystem.
     */
    private final static Comparator<String> LEXICAL_SORT_ORDER = Comparator.comparing(String::toString);

    CustomerClassLoader(String taskRoot, String optRoot, ClassLoader parent) throws IOException {
        super(getUrls(taskRoot, optRoot), parent);
    }

    private static URL[] getUrls(String taskRoot, String optRoot) throws MalformedURLException {
        File taskDir = new File(taskRoot + "/");
        List<URL> res = new ArrayList<>();
        res.add(newURL(taskDir, ""));
        appendJars(new File(taskRoot + "/lib"), res);
        appendJars(new File(optRoot + "/lib"), res);
        return res.toArray(new URL[res.size()]);
    }

    private static void appendJars(File dir, List<URL> result) throws MalformedURLException {
        if (!dir.isDirectory()) {
            return;
        }
        String[] names = dir.list();
        if (names == null) {
            return;
        }
        Arrays.sort(names, CustomerClassLoader.LEXICAL_SORT_ORDER);
        for(String path : names) {
            if(path.endsWith(".jar")) {
                result.add(newURL(dir, path));
            }
        }
    }

    private static URL newURL(File parent, String path) throws MalformedURLException {
        return new URL("file", null, -1, parent.getPath() + "/" + path);
    }
}

@@ -152,16 +152,47 @@
 o.File;%0A
+import java.io.FilenameFilter;%0A
 import j
@@ -203,32 +203,32 @@
 io.IOException;%0A
-
 import java.net.
@@ -751,16 +751,418 @@
 String);
+%0A    private final static FilenameFilter JAR_FILE_NAME_FILTER = new FilenameFilter() %7B%0A%0A        @Override%0A        public boolean accept(File dir, String name) %7B%0A            int offset = name.length() - 4;%0A            if (offset %3C= 0) %7B /* must be at least A.jar */%0A                return false;%0A            %7D else %7B%0A                return name.startsWith(%22.jar%22, offset);%0A            %7D%0A        %7D%0A    %7D;
 %0A%0A    Cu
@@ -1893,16 +1893,56 @@
 ir.list(
+CustomerClassLoader.JAR_FILE_NAME_FILTER
 );%0A     
@@ -2059,24 +2059,25 @@
 ORT_ORDER);%0A
+%0A
         for(
@@ -2075,16 +2075,17 @@
      for
+ 
 (String 
@@ -2104,52 +2104,8 @@
 ) %7B%0A
-            if(path.endsWith(%22.jar%22)) %7B%0A    
     
@@ -2143,30 +2143,16 @@
 path));%0A
-            %7D%0A
         

Optimize jar discovery (#350)