/*
 * Copyright 2015 Decebal Suiu
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ro.fortsoft.pf4j;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.fortsoft.pf4j.processor.ServiceProviderExtensionStorage;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * The ServiceLoader base implementation for ExtensionFinder.
 * This class lookup extensions in all extensions index files "META-INF/services".
 *
 * @author Decebal Suiu
 */
public class ServiceProviderExtensionFinder extends AbstractExtensionFinder {

    private static final Logger log = LoggerFactory.getLogger(ServiceProviderExtensionFinder.class);

    public ServiceProviderExtensionFinder(PluginManager pluginManager) {
        super(pluginManager);
    }

    @Override
    public Map<String, Set<String>> readClasspathStorages() {
        log.debug("Reading extensions storages from classpath");
        Map<String, Set<String>> result = new LinkedHashMap<>();

        Set<String> bucket = new HashSet<>();
        try {
            URL url = getClass().getClassLoader().getResource(getExtensionsResource());
            if (url != null) {
                File[] files = new File(url.toURI()).listFiles();
                if (files != null) {
                    for (File file : files) {
                        log.debug("Read '{}'", file);
                        Reader reader = new FileReader(file);
                        ServiceProviderExtensionStorage.read(reader, bucket);
                    }
                }
            }

            if (bucket.isEmpty()) {
                log.debug("No extensions found");
            } else {
                log.debug("Found possible {} extensions:", bucket.size());
                for (String entry : bucket) {
                    log.debug("   " + entry);
                }
            }

            result.put(null, bucket);
        } catch (IOException | URISyntaxException e) {
            log.error(e.getMessage(), e);
        }

        return result;
    }

    @Override
    public Map<String, Set<String>> readPluginsStorages() {
        log.debug("Reading extensions storages from plugins");
        Map<String, Set<String>> result = new LinkedHashMap<>();

        List<PluginWrapper> plugins = pluginManager.getPlugins();
        for (PluginWrapper plugin : plugins) {
            String pluginId = plugin.getDescriptor().getPluginId();
            log.debug("Reading extensions storages for plugin '{}'", pluginId);
            Set<String> bucket = new HashSet<>();

            try {
                URL url = ((PluginClassLoader) plugin.getPluginClassLoader()).findResource(getExtensionsResource());
                if (url != null) {
                    File[] files = new File(url.toURI()).listFiles();
                    if (files != null) {
                        for (File file : files) {
                            log.debug("Read '{}'", file);
                            Reader reader = new FileReader(file);
                            ServiceProviderExtensionStorage.read(reader, bucket);
                        }
                    }
                } else {
                    log.debug("Cannot find '{}'", getExtensionsResource());
                }

                if (bucket.isEmpty()) {
                    log.debug("No extensions found");
                } else {
                    log.debug("Found possible {} extensions:", bucket.size());
                    for (String entry : bucket) {
                        log.debug("   " + entry);
                    }
                }

                result.put(pluginId, bucket);
            } catch (IOException | URISyntaxException e) {
                log.error(e.getMessage(), e);
            }
        }

        return result;
    }

    private static String getExtensionsResource() {
        return ServiceProviderExtensionStorage.EXTENSIONS_RESOURCE;
    }

}

@@ -913,20 +913,18 @@
 ava.
-util.HashSet
+nio.file.*
 ;%0Aim
@@ -937,49 +937,46 @@
 ava.
-util.LinkedHashMap;%0Aimport java.util.List
+nio.file.attribute.BasicFileAttributes
 ;%0Aim
@@ -990,19 +990,17 @@
 va.util.
-Map
+*
 ;%0Aimport
@@ -1010,19 +1010,29 @@
 va.util.
-Set
+stream.Stream
 ;%0A%0A/**%0A 
@@ -1704,32 +1704,38 @@
 p%3C%3E();%0A%0A        
+final 
 Set%3CString%3E buck
@@ -1905,39 +1905,166 @@
         
-File%5B%5D files = 
+Path extensionPath;%0A                if (url.toURI().getScheme().equals(%22jar%22)) %7B%0A                    FileSystem fileSystem = FileSystems.
 new
- 
 File
+System
 (url.toU
@@ -2071,103 +2071,500 @@
 RI()
-).listFiles();%0A                if (files != null) %7B%0A                    for (File file : files)
+, Collections.%3CString, Object%3EemptyMap());%0A                    extensionPath = fileSystem.getPath(getExtensionsResource());%0A                %7D else %7B%0A                    extensionPath = Paths.get(url.toURI());%0A                %7D%0A                Files.walkFileTree(extensionPath, Collections.%3CFileVisitOption%3EemptySet(), 1, new SimpleFileVisitor%3CPath%3E() %7B%0A                    @Override%0A                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
  %7B%0A 
@@ -2652,32 +2652,41 @@
 er reader = 
-new 
 File
+s.newBuffered
 Reader(file)
@@ -2757,32 +2757,89 @@
 eader, bucket);%0A
+                        return FileVisitResult.CONTINUE;%0A
                 
@@ -2853,32 +2853,34 @@
                %7D
+);
 %0A            %7D%0A%0A

Fix issue with listing files from the Jar file. Work with Jar's like with external file system using NIO.