Removed log constants from translator core
[sdc.git] / openecomp-be / lib / openecomp-sdc-translator-lib / openecomp-sdc-translator-core / src / main / java / org / openecomp / sdc / translator / utils / ResourceWalker.java
1 /*
2  * Copyright © 2016-2017 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.translator.utils;
18
19 import org.apache.commons.io.IOUtils;
20 import org.openecomp.sdc.common.errors.CoreException;
21 import org.openecomp.sdc.common.errors.ErrorCategory;
22 import org.openecomp.sdc.common.errors.ErrorCode;
23 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
24
25 import java.io.BufferedReader;
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.net.URI;
33 import java.net.URISyntaxException;
34 import java.net.URL;
35 import java.util.Enumeration;
36 import java.util.HashMap;
37 import java.util.Map;
38 import java.util.function.BiConsumer;
39 import java.util.function.Predicate;
40 import java.util.zip.ZipEntry;
41 import java.util.zip.ZipFile;
42
43 public class ResourceWalker {
44
45   private ResourceWalker() {
46   }
47
48   /**
49    * Read resources from directory map.
50    *
51    * @param resourceDirectoryToStart the resource directory to start
52    * @return the map of file where key is file name and value is its data
53    * @throws Exception the exception
54    */
55   public static Map<String, String> readResourcesFromDirectory(String resourceDirectoryToStart)
56       throws
57       Exception {
58     Map<String, String> filesContent = new HashMap<>();
59     traverse(resourceDirectoryToStart, (fileName, stream) -> {
60       try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
61         filesContent.put(fileName, IOUtils.toString(reader));
62       } catch (IOException exception) {
63         throw new CoreException((new ErrorCode.ErrorCodeBuilder())
64             .withMessage(LoggerErrorDescription.RESOURCE_FILE_READ_ERROR
65                 + " File name = " + fileName)
66             .withId("Resource Read Error").withCategory(ErrorCategory.APPLICATION).build(),
67             exception);
68       }
69     });
70     return filesContent;
71   }
72
73   private static void traverse(String start, BiConsumer<String, InputStream> handler) throws
74       Exception {
75
76     URL url = ResourceWalker.class.getClassLoader().getResource(start);
77     if (url == null) {
78       throw new FileNotFoundException("Resource not found: " + start);
79     }
80
81     switch (url.getProtocol().toLowerCase()) {
82
83       case "file":
84         traverseFile(new File(url.getPath()), handler);
85         break;
86       case "zip":
87       case "jar":
88         String path = url.getPath();
89         int resourcePosition = path.lastIndexOf("!/" + start);
90         traverseArchive(path.substring(0, resourcePosition), start, handler);
91         break;
92       default:
93         throw new IllegalArgumentException("Unknown protocol");
94     }
95   }
96
97   private static void traverseArchive(String file, String resource, BiConsumer<String, InputStream>
98       handler)
99       throws URISyntaxException, IOException {
100
101     // There is what looks like a bug in Java:
102     // if "abc" is a directory in an archive,
103     // both "abc" and "abc/" will be found successfully.
104     // However, calling isDirectory() will return "true" for "abc/",
105     // but "false" for "abc".
106     try (ZipFile zip = new ZipFile(new URI(file).getPath())) {
107
108       Predicate<ZipEntry> predicate = buildPredicate(resource);
109       Enumeration<? extends ZipEntry> entries = zip.entries();
110       while (entries.hasMoreElements()) {
111         handleZipEntry(predicate, zip, entries.nextElement(), handler);
112       }
113     }
114   }
115
116   private static Predicate<ZipEntry> buildPredicate(String resource) {
117
118     if (resource.endsWith("/")) {
119       return zipEntry ->
120           zipEntry.getName().startsWith(resource) && !zipEntry.isDirectory();
121     } else {
122       return zipEntry -> {
123         String name = zipEntry.getName();
124         return (name.equals(resource) || name.startsWith(resource + "/"))
125             && !zipEntry.isDirectory();
126       };
127     }
128   }
129
130   private static void handleZipEntry(Predicate<ZipEntry> predicate, ZipFile zip, ZipEntry zipEntry,
131                                      BiConsumer<String, InputStream> handler)
132       throws IOException {
133
134     if (predicate.test(zipEntry)) {
135
136       try (InputStream input = zip.getInputStream(zipEntry)) {
137         handler.accept(zipEntry.getName(), input);
138       }
139     }
140   }
141
142   private static void traverseFile(File file, BiConsumer<String, InputStream> handler) throws
143       IOException {
144
145     if (file.isDirectory()) {
146       File[] files = file.listFiles();
147       if (files != null) {
148         for (File sub : files) {
149           traverseFile(sub, handler);
150         }
151       }
152     } else {
153       try (FileInputStream stream = new FileInputStream(file)) {
154         handler.accept(file.getPath(), stream);
155       }
156     }
157   }
158 }