ResourceAdapter.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package org.ssssssss.magicapi.adapter;
  2. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  3. import org.springframework.util.ResourceUtils;
  4. import org.ssssssss.magicapi.adapter.resource.FileResource;
  5. import org.ssssssss.magicapi.adapter.resource.JarResource;
  6. import java.io.FileNotFoundException;
  7. import java.io.IOException;
  8. import java.net.JarURLConnection;
  9. import java.net.URL;
  10. import java.util.List;
  11. import java.util.jar.JarEntry;
  12. import java.util.jar.JarFile;
  13. import java.util.stream.Collectors;
  14. public abstract class ResourceAdapter {
  15. public static final String SPRING_BOOT_CLASS_PATH = "BOOT-INF/classes/";
  16. private static PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
  17. public static Resource getResource(String location, boolean readonly) throws IOException {
  18. if (location == null) {
  19. return null;
  20. }
  21. org.springframework.core.io.Resource resource;
  22. if (location.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {
  23. resource = resolver.getResource(location);
  24. if (resource.exists()) {
  25. return resolveResource(resource, true);
  26. } else {
  27. throw new FileNotFoundException(String.format("%s not found", resource.getDescription()));
  28. }
  29. } else {
  30. resource = resolver.getResource(location);
  31. if (!resource.exists()) {
  32. resource = resolver.getResource(ResourceUtils.FILE_URL_PREFIX + location);
  33. }
  34. }
  35. return resolveResource(resource, readonly);
  36. }
  37. private static Resource resolveResource(org.springframework.core.io.Resource resource, boolean readonly) throws IOException {
  38. URL url = resource.getURI().toURL();
  39. if (url.getProtocol().equals(ResourceUtils.URL_PROTOCOL_JAR)) {
  40. JarURLConnection connection = (JarURLConnection) url.openConnection();
  41. boolean springBootClassPath = connection.getClass().getName().equals("org.springframework.boot.loader.jar.JarURLConnection");
  42. String entryName = (springBootClassPath ? SPRING_BOOT_CLASS_PATH : "") + connection.getEntryName();
  43. JarFile jarFile = connection.getJarFile();
  44. List<JarEntry> entries = jarFile.stream().filter(it -> it.getName().startsWith(entryName)).collect(Collectors.toList());
  45. if (entries.isEmpty()) {
  46. entries = jarFile.stream().filter(it -> it.getName().startsWith(connection.getEntryName())).collect(Collectors.toList());
  47. return new JarResource(jarFile, connection.getEntryName(), entries, springBootClassPath);
  48. }
  49. return new JarResource(jarFile, entryName, entries, springBootClassPath);
  50. } else {
  51. return new FileResource(resource.getFile(), readonly);
  52. }
  53. }
  54. }