View Javadoc
1   package cn.home1.cloud.config.server.util;
2   
3   import static com.google.common.base.Preconditions.checkArgument;
4   import static lombok.AccessLevel.PRIVATE;
5   import static org.apache.commons.io.FileUtils.copyInputStreamToFile;
6   import static org.apache.commons.io.FileUtils.forceMkdir;
7   
8   import cn.home1.cloud.config.server.ConfigServer;
9   
10  import lombok.NoArgsConstructor;
11  import lombok.SneakyThrows;
12  
13  import org.apache.commons.lang3.StringUtils;
14  
15  import java.io.File;
16  import java.io.InputStream;
17  
18  @NoArgsConstructor(access = PRIVATE)
19  public abstract class ResourceUtils {
20  
21      /**
22       * Find resource in classpath and on filesystem, return its path or null (not found)
23       *
24       * @param location        start with 'classpath:' or 'file:'
25       * @param outputDirectory dump resource into 'outputDirectory + location', if found in classpath
26       * @return resource file path or null (not found)
27       */
28      @SneakyThrows
29      public static String findResourceFile(final String location, final String outputDirectory) {
30          final String result;
31  
32          if (location.startsWith("classpath:")) {
33              // see: http://www.baeldung.com/convert-input-stream-to-a-file
34              // read resource from classpath
35              final String fileName = StringUtils.replaceOnce(location, "classpath:", "");
36              final InputStream streamIn = ConfigServer.class.getClassLoader().getResourceAsStream(fileName);
37              checkArgument(streamIn != null,
38                  "resource '" + location + "' not found in classpath ('" + fileName + "')");
39  
40              // write resource to filesystem
41              forceMkdir(new File(outputDirectory));
42              final File fileOut = new File(outputDirectory + (location.startsWith("/") ? location : "/" + location));
43              copyInputStreamToFile(streamIn, fileOut);
44              checkArgument(fileOut.exists() && fileOut.canRead(),
45                  "File '" + fileOut.getPath() + "' not found or not readable");
46  
47              result = fileOut.getPath();
48          } else if (location.startsWith("file:")) {
49              result = StringUtils.replaceOnce(location, "file:", "");
50          } else {
51              result = location;
52          }
53  
54          return result;
55      }
56  }