Honeynode test tool
[transportpce.git] / tests / honeynode / minimal-distribution-core / src / main / java / io / fd / honeycomb / infra / distro / schema / ResourceLoader.java
1 /*
2  * Copyright (c) 2017 Cisco and/or its affiliates.
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 io.fd.honeycomb.infra.distro.schema;
18
19 import static com.google.common.base.Preconditions.checkNotNull;
20 import static com.google.common.base.Preconditions.checkState;
21 import static java.lang.String.format;
22
23 import com.google.common.base.Charsets;
24 import com.google.common.base.Strings;
25 import com.google.common.io.Resources;
26 import java.io.File;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.net.MalformedURLException;
30 import java.net.URI;
31 import java.net.URISyntaxException;
32 import java.net.URL;
33 import java.nio.charset.StandardCharsets;
34 import java.util.Arrays;
35 import java.util.Collections;
36 import java.util.Set;
37 import java.util.jar.JarEntry;
38 import java.util.jar.JarFile;
39 import java.util.stream.Collectors;
40 import org.apache.commons.io.IOUtils;
41
42 /**
43  * Allows loading content of X amount of files from filesystem or archive
44  */
45 public interface ResourceLoader {
46
47     default Set<String> loadResourceContentsOnPath(final String path) {
48         final URL folderUrl = getClass().getClassLoader().getResource(path);
49         checkState(folderUrl != null, "Resources %s not found", path);
50
51         if (ResourceLoaderIml.urlToUri(folderUrl).getScheme().equals("jar")) {
52             return ResourceLoaderIml.readFromJar(path, folderUrl);
53         } else {
54             return ResourceLoaderIml.readFromFolder(folderUrl);
55         }
56
57     }
58
59     final class ResourceLoaderIml {
60
61         private static Set<String> readFromFolder(final URL folderUrl) {
62             final File folder = new File(folderUrl.getPath());
63             final File[] files = checkNotNull(folder.listFiles(), "No files present on path %s", folderUrl);
64             return Arrays.stream(files)
65                     .map(ResourceLoaderIml::fileToUrl)
66                     .map(ResourceLoaderIml::urlToContentString)
67                     .flatMap(content -> Arrays.stream(content.split(System.lineSeparator())))
68                     .filter(ResourceLoaderIml::filterNonEmpty)
69                     .collect(Collectors.toSet());
70         }
71
72         private static Set<String> readFromJar(final String path, final URL url) {
73             final String uriString = urlToUri(url).toString();
74             final String fileReference = extractJarFilePath(uriString);
75             try (JarFile jar = new JarFile(new File(fileReference))) {
76                 return Collections.list(jar.entries())
77                         .stream()
78                         .filter(jarEntry -> jarEntry.getName().contains(path))
79                         .map(jarEntry -> getJarEntryStream(jar, jarEntry))
80                         .map(ResourceLoaderIml::readJarEntryStream)
81                         .flatMap(content -> Arrays.stream(content.split(System.lineSeparator())))
82                         .filter(ResourceLoaderIml::filterNonEmpty)
83                         .collect(Collectors.toSet());
84             } catch (IOException e) {
85                 throw new IllegalStateException(e);
86             }
87         }
88
89         private static String extractJarFilePath(final String uriString) {
90             return uriString.substring(0, uriString.indexOf("!")).replace("jar:file:", "");
91         }
92
93         private static boolean filterNonEmpty(final String line) {
94             return !Strings.isNullOrEmpty(line.trim());
95         }
96
97         private static String readJarEntryStream(final InputStream inputStream) {
98             try {
99                 final String value = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
100                 IOUtils.closeQuietly(inputStream);
101                 return value;
102             } catch (IOException e) {
103                 throw new IllegalStateException(e);
104             }
105         }
106
107         private static InputStream getJarEntryStream(final JarFile jar, final JarEntry jarEntry) {
108             try {
109                 return jar.getInputStream(jarEntry);
110             } catch (IOException e) {
111                 throw new IllegalStateException(format("Unable to get stream for entry %s | jar %s", jar, jarEntry), e);
112             }
113         }
114
115         private static URI urlToUri(final URL url) {
116             try {
117                 return url.toURI();
118             } catch (URISyntaxException e) {
119                 throw new IllegalStateException(format("Unable to convert URL %s to URI", url), e);
120             }
121         }
122
123         private static String urlToContentString(final URL url) {
124             try {
125                 return Resources.toString(url, Charsets.UTF_8);
126             } catch (IOException e) {
127                 throw new IllegalArgumentException("Unable to read resource from: " + url, e);
128             }
129         }
130
131         private static URL fileToUrl(final File file) {
132             try {
133                 return file.toURI().toURL();
134             } catch (MalformedURLException e) {
135                 throw new IllegalStateException(e);
136             }
137         }
138     }
139 }