View Javadoc
1   package com.github.searls.jasmine.thirdpartylibs;
2   
3   import org.webjars.WebJarAssetLocator;
4   
5   import java.io.InputStream;
6   import java.util.ArrayList;
7   import java.util.List;
8   import java.util.regex.Pattern;
9   
10  public class WebJarResourceHandler extends AbstractThirdPartyLibsResourceHandler {
11  
12    private static final Pattern WILDCARD = Pattern.compile(".*");
13  
14    private final List<WebJarAssetLocator> webJarAssetLocators;
15    private final ClassLoader projectClassLoader;
16  
17    public WebJarResourceHandler(ClassLoader projectClassLoader) {
18      this.projectClassLoader = projectClassLoader;
19      this.webJarAssetLocators = createWebJarAssetLocators(
20        WebJarResourceHandler.class.getClassLoader(),
21        projectClassLoader
22      );
23    }
24  
25    @Override
26    protected InputStream findResource(String resourcePath) {
27      String fullPath = findFullPath(resourcePath);
28      return fullPath != null ? projectClassLoader.getResourceAsStream(fullPath) : null;
29    }
30  
31    private String findFullPath(String resourcePath) {
32      String fullPath = null;
33      for (WebJarAssetLocator locator : webJarAssetLocators) {
34        fullPath = findFullPath(locator, resourcePath);
35        if (fullPath != null) {
36          break;
37        }
38      }
39      return fullPath;
40    }
41  
42    private String findFullPath(WebJarAssetLocator locator, String resourcePath) {
43      String fullPath = null;
44      try {
45        fullPath = locator.getFullPath(resourcePath);
46      } catch (Exception e) {
47        fullPath = findFullPathByPartial(locator, resourcePath);
48      }
49      return fullPath;
50    }
51  
52    private String findFullPathByPartial(WebJarAssetLocator locator, String resourcePath) {
53  
54      String fullPath = null;
55  
56      int splitAt = resourcePath.indexOf("/");
57  
58      if (splitAt > 0) {
59        String webjar = resourcePath.substring(0, splitAt);
60        String partialPath = resourcePath.substring(splitAt + 1);
61        try {
62          fullPath = locator.getFullPath(webjar, partialPath);
63        } catch (Exception e) {
64          // TODO: at least log this exception
65        }
66      }
67  
68      return fullPath;
69    }
70  
71    private List<WebJarAssetLocator> createWebJarAssetLocators(ClassLoader... classLoaders) {
72      List<WebJarAssetLocator> locators = new ArrayList<WebJarAssetLocator>();
73      for (ClassLoader classLoader : classLoaders) {
74        locators.add(new WebJarAssetLocator(WebJarAssetLocator.getFullPathIndex(WILDCARD, classLoader)));
75      }
76      return locators;
77    }
78  }