9ff1ff99926374e8da9d4fc8e82ec7fa6b786184
[sdc.git] /
1 package org.openecomp.sdc.translator.utils;
2
3 import org.apache.commons.io.IOUtils;
4 import org.openecomp.sdc.common.errors.CoreException;
5 import org.openecomp.sdc.common.errors.ErrorCategory;
6 import org.openecomp.sdc.common.errors.ErrorCode;
7 import org.openecomp.sdc.datatypes.error.ErrorLevel;
8 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
9 import org.openecomp.sdc.logging.types.LoggerConstants;
10 import org.openecomp.sdc.logging.types.LoggerErrorCode;
11 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
12 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
13
14 import java.io.BufferedReader;
15 import java.io.File;
16 import java.io.FileInputStream;
17 import java.io.FileNotFoundException;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.InputStreamReader;
21 import java.net.URI;
22 import java.net.URISyntaxException;
23 import java.net.URL;
24 import java.util.Enumeration;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.function.BiConsumer;
28 import java.util.function.Predicate;
29 import java.util.zip.ZipEntry;
30 import java.util.zip.ZipFile;
31
32 /**
33  * @author EVITALIY.
34  * @since 02 Apr 17
35  */
36 public class ResourceWalker {
37
38   public static Map<String, String> readResourcesFromDirectory(String resourceDirectoryToStart)
39       throws
40       Exception {
41     Map<String, String> filesContent = new HashMap<>();
42     traverse(resourceDirectoryToStart, (fileName, stream) -> {
43       try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
44         filesContent.put(fileName, IOUtils.toString(reader));
45       } catch (IOException exception) {
46         MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API,
47             LoggerTragetServiceName.READ_RESOURCE_FILE, ErrorLevel.ERROR.name(),
48             LoggerErrorCode.DATA_ERROR.getErrorCode(),
49             LoggerErrorDescription.RESOURCE_FILE_READ_ERROR
50                 + " File name = " + fileName);
51         throw new CoreException((new ErrorCode.ErrorCodeBuilder())
52             .withMessage(LoggerErrorDescription.RESOURCE_FILE_READ_ERROR
53                 + " File name = " + fileName)
54             .withId("Resource Read Error").withCategory(ErrorCategory.APPLICATION).build(),
55             exception);
56       }
57     });
58     return filesContent;
59   }
60
61   private static void traverse(String start, BiConsumer<String, InputStream> handler) throws
62       Exception {
63
64     URL url = ResourceWalker.class.getClassLoader().getResource(start);
65     if (url == null) {
66       throw new FileNotFoundException("Resource not found: " + start);
67     }
68
69     switch (url.getProtocol().toLowerCase()) {
70
71       case "file":
72         traverseFile(new File(url.getPath()), handler);
73         break;
74       case "zip":
75       case "jar":
76         String path = url.getPath();
77         int resourcePosition = path.lastIndexOf("!/" + start);
78         traverseArchive(path.substring(0, resourcePosition), start, handler);
79         break;
80       default:
81         throw new IllegalArgumentException("Unknown protocol");
82     }
83   }
84
85   private static void traverseArchive(String file, String resource, BiConsumer<String, InputStream>
86       handler)
87       throws URISyntaxException, IOException {
88
89     // There is what looks like a bug in Java:
90     // if "abc" is a directory in an archive,
91     // both "abc" and "abc/" will be found successfully.
92     // However, calling isDirectory() will return "true" for "abc/",
93     // but "false" for "abc".
94     try (ZipFile zip = new ZipFile(new URI(file).getPath())) {
95
96       Predicate<ZipEntry> predicate = buildPredicate(resource);
97       Enumeration<? extends ZipEntry> entries = zip.entries();
98       while (entries.hasMoreElements()) {
99         handleZipEntry(predicate, zip, entries.nextElement(), handler);
100       }
101     }
102   }
103
104   private static Predicate<ZipEntry> buildPredicate(String resource) {
105
106     if (resource.endsWith("/")) {
107       return zipEntry ->
108           zipEntry.getName().startsWith(resource) && !zipEntry.isDirectory();
109     } else {
110       return zipEntry -> {
111         String name = zipEntry.getName();
112         return (name.equals(resource) || name.startsWith(resource + "/"))
113             && !zipEntry.isDirectory();
114       };
115     }
116   }
117
118   private static void handleZipEntry(Predicate<ZipEntry> predicate, ZipFile zip, ZipEntry zipEntry,
119                                      BiConsumer<String, InputStream> handler)
120       throws IOException {
121
122     if (predicate.test(zipEntry)) {
123
124       try (InputStream input = zip.getInputStream(zipEntry)) {
125         handler.accept(zipEntry.getName(), input);
126       }
127     }
128   }
129
130   private static void traverseFile(File file, BiConsumer<String, InputStream> handler) throws
131       IOException {
132
133     if (file.isDirectory()) {
134       for (File sub : file.listFiles()) {
135         traverseFile(sub, handler);
136       }
137     } else {
138       try (FileInputStream stream = new FileInputStream(file)) {
139         handler.accept(file.getPath(), stream);
140       }
141     }
142   }
143 }