99aa4518a4ab88886e20c4ad8bca1a8c292d5642
[transportpce.git] / tests / honeynode / 1.2.1 / 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 ResourceLoaderIml() {
62             throw new UnsupportedOperationException();
63         }
64
65         private static Set<String> readFromFolder(final URL folderUrl) {
66             final File folder = new File(folderUrl.getPath());
67             final File[] files = checkNotNull(folder.listFiles(), "No files present on path %s", folderUrl);
68             return Arrays.stream(files)
69                     .map(ResourceLoaderIml::fileToUrl)
70                     .map(ResourceLoaderIml::urlToContentString)
71                     .flatMap(content -> Arrays.stream(content.split(System.lineSeparator())))
72                     .filter(ResourceLoaderIml::filterNonEmpty)
73                     .collect(Collectors.toSet());
74         }
75
76         private static Set<String> readFromJar(final String path, final URL url) {
77             final String uriString = urlToUri(url).toString();
78             final String fileReference = extractJarFilePath(uriString);
79             try (JarFile jar = new JarFile(new File(fileReference))) {
80                 return Collections.list(jar.entries())
81                         .stream()
82                         .filter(jarEntry -> jarEntry.getName().contains(path))
83                         .map(jarEntry -> getJarEntryStream(jar, jarEntry))
84                         .map(ResourceLoaderIml::readJarEntryStream)
85                         .flatMap(content -> Arrays.stream(content.split(System.lineSeparator())))
86                         .filter(ResourceLoaderIml::filterNonEmpty)
87                         .collect(Collectors.toSet());
88             } catch (IOException e) {
89                 throw new IllegalStateException(e);
90             }
91         }
92
93         private static String extractJarFilePath(final String uriString) {
94             return uriString.substring(0, uriString.indexOf("!")).replace("jar:file:", "");
95         }
96
97         private static boolean filterNonEmpty(final String line) {
98             return !Strings.isNullOrEmpty(line.trim());
99         }
100
101         private static String readJarEntryStream(final InputStream inputStream) {
102             try {
103                 final String value = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
104                 IOUtils.closeQuietly(inputStream);
105                 return value;
106             } catch (IOException e) {
107                 throw new IllegalStateException(e);
108             }
109         }
110
111         private static InputStream getJarEntryStream(final JarFile jar, final JarEntry jarEntry) {
112             try {
113                 return jar.getInputStream(jarEntry);
114             } catch (IOException e) {
115                 throw new IllegalStateException(format("Unable to get stream for entry %s | jar %s", jar, jarEntry), e);
116             }
117         }
118
119         private static URI urlToUri(final URL url) {
120             try {
121                 return url.toURI();
122             } catch (URISyntaxException e) {
123                 throw new IllegalStateException(format("Unable to convert URL %s to URI", url), e);
124             }
125         }
126
127         private static String urlToContentString(final URL url) {
128             try {
129                 return Resources.toString(url, Charsets.UTF_8);
130             } catch (IOException e) {
131                 throw new IllegalArgumentException("Unable to read resource from: " + url, e);
132             }
133         }
134
135         private static URL fileToUrl(final File file) {
136             try {
137                 return file.toURI().toURL();
138             } catch (MalformedURLException e) {
139                 throw new IllegalStateException(e);
140             }
141         }
142     }
143 }