28800b515af7272f0815280b24240b59b937c5d8
[integration/csit.git] / plans / so / integration-etsi-testing / so-simulators / sdc-simulator / src / main / java / org / onap / so / sdcsimulator / providers / AssetProviderImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *   Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.sdcsimulator.providers;
22
23 import static org.onap.so.sdcsimulator.utils.Constants.DOT_CSAR;
24 import static org.onap.so.sdcsimulator.utils.Constants.DOT_JSON;
25 import static org.onap.so.sdcsimulator.utils.Constants.FORWARD_SLASH;
26 import static org.onap.so.sdcsimulator.utils.Constants.MAIN_RESOURCE_FOLDER;
27 import static org.onap.so.sdcsimulator.utils.Constants.WILD_CARD_REGEX;
28 import static org.springframework.core.io.support.ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.nio.file.DirectoryStream;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.util.HashSet;
36 import java.util.Optional;
37 import java.util.Set;
38 import org.onap.so.sdcsimulator.models.AssetInfo;
39 import org.onap.so.sdcsimulator.models.AssetType;
40 import org.onap.so.sdcsimulator.models.Metadata;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.beans.factory.annotation.Value;
45 import org.springframework.core.io.ClassPathResource;
46 import org.springframework.core.io.Resource;
47 import org.springframework.core.io.support.ResourcePatternResolver;
48 import org.springframework.stereotype.Service;
49 import org.springframework.util.StreamUtils;
50
51 /**
52  * @author Waqas Ikram (waqas.ikram@est.tech)
53  */
54 @Service
55 public class AssetProviderImpl implements AssetProvider {
56
57     private static final Logger LOGGER = LoggerFactory.getLogger(AssetProvider.class);
58
59     private final String resourceLocation;
60
61     private final ResourcePatternResolver resourcePatternResolver;
62
63     @Autowired
64     public AssetProviderImpl(@Value("${sdc.resource.location:/app/csars/}") final String resourceLocation,
65             final ResourcePatternResolver resourcePatternResolver) {
66         this.resourceLocation = resourceLocation;
67         this.resourcePatternResolver = resourcePatternResolver;
68     }
69
70     @Override
71     public Optional<byte[]> getAsset(final String csarId, final AssetType assetType) {
72         try {
73             final Optional<InputStream> optionalInputStream = getInputStream(csarId, assetType);
74             if (optionalInputStream.isPresent()) {
75                 return Optional.of(StreamUtils.copyToByteArray(optionalInputStream.get()));
76             }
77         } catch (final IOException ioException) {
78             LOGGER.warn("Unable to create file stream ...", ioException);
79         }
80
81         return Optional.empty();
82     }
83
84     @Override
85     public Set<AssetInfo> getAssetInfo(final AssetType assetType) {
86         final Set<AssetInfo> result = new HashSet<>();
87
88         final Path dir = Paths.get(resourceLocation).resolve(assetType.toString());
89         if (Files.exists(dir)) {
90             try (final DirectoryStream<Path> stream = Files.newDirectoryStream(dir, WILD_CARD_REGEX + DOT_CSAR)) {
91                 for (final Path entry : stream) {
92                     final String filename = getFilenameWithoutExtension(entry);
93                     result.add(getAssetInfo(assetType, filename, entry));
94                 }
95             } catch (final IOException ioException) {
96                 LOGGER.error("Unable to find assetInfo on filesystem", ioException);
97             }
98         }
99
100         try {
101             final String classPathdir = MAIN_RESOURCE_FOLDER + assetType.toString() + FORWARD_SLASH;
102             final String csarFileLocationPattern = CLASSPATH_ALL_URL_PREFIX + classPathdir + WILD_CARD_REGEX + DOT_CSAR;
103             final Resource[] resources = resourcePatternResolver.getResources(csarFileLocationPattern);
104             if (resources != null) {
105
106                 for (final Resource resource : resources) {
107                     final String filename = getFilenameWithoutExtension(resource.getFilename());
108                     result.add(getAssetInfo(assetType, filename, resource));
109                 }
110             }
111
112         } catch (final IOException ioException) {
113             LOGGER.error("Unable to find assetInfo in classpath", ioException);
114         }
115
116         return result;
117     }
118
119     @Override
120     public Optional<Metadata> getMetadata(final String csarId, final AssetType assetType) {
121         final Path dir = Paths.get(resourceLocation).resolve(assetType.toString());
122         final Path metadataFilePath = dir.resolve(csarId + DOT_JSON);
123         try {
124             if (Files.exists(metadataFilePath)) {
125                 LOGGER.info("Found metadata file on file system using path: {}", metadataFilePath);
126
127                 return Optional.of(assetType.getMetadata(metadataFilePath.toFile()));
128
129             }
130         } catch (final IOException ioException) {
131             LOGGER.error("Unable to find metadata file on filesystem", ioException);
132         }
133
134
135         try {
136             final String path = MAIN_RESOURCE_FOLDER + assetType.toString() + FORWARD_SLASH + csarId + DOT_JSON;
137             LOGGER.warn("Couldn't find metadata file on file system '{}', will search it in classpath", path);
138             final ClassPathResource classPathResource = getClassPathResource(path);
139             if (classPathResource.exists()) {
140                 LOGGER.info("Found metadata file in classpath using path: {}", path);
141                 return Optional.of(assetType.getMetadata(classPathResource));
142             }
143         } catch (final IOException ioException) {
144             LOGGER.error("Unable to find metadata file in classpath", ioException);
145         }
146         LOGGER.error("Couldn't find metadata file in classpath ....");
147         return Optional.empty();
148     }
149
150     private AssetInfo getAssetInfo(final AssetType assetType, final String filename, final Resource resource)
151             throws IOException {
152         final Resource jsonResource = resource.createRelative(filename + DOT_JSON);
153
154         if (jsonResource != null && jsonResource.exists()) {
155             final AssetInfo assetInfo = assetType.getAssetInfo(jsonResource);
156             assetInfo.setUuid(filename);
157             assetInfo.setToscaModelUrl(assetType.getToscaModelUrl(filename));
158             LOGGER.info("Found AssetInfo file in classpath: {}", assetInfo);
159             return assetInfo;
160
161         }
162
163         final AssetInfo assetInfo = assetType.getDefaultAssetInfo(filename);
164         LOGGER.info("Returning AssetInfo: {}", assetInfo);
165         return assetInfo;
166
167     }
168
169     private AssetInfo getAssetInfo(final AssetType assetType, final String filename, final Path entry)
170             throws IOException {
171         final Path assetJsonFilePath = entry.getParent().resolve(filename + DOT_JSON);
172         if (Files.exists(assetJsonFilePath)) {
173             final AssetInfo assetInfo = assetType.getAssetInfo(assetJsonFilePath.toFile());
174             assetInfo.setUuid(filename);
175             assetInfo.setToscaModelUrl(assetType.getToscaModelUrl(filename));
176             LOGGER.info("Found AssetInfo file on file system: {}", assetInfo);
177             return assetInfo;
178
179         }
180         final AssetInfo assetInfo = assetType.getDefaultAssetInfo(filename);
181         LOGGER.info("Returning AssetInfo: {}", assetInfo);
182         return assetInfo;
183     }
184
185     private String getFilenameWithoutExtension(final String filename) {
186         return filename.substring(0, filename.lastIndexOf('.'));
187     }
188
189     private String getFilenameWithoutExtension(final Path file) {
190         return getFilenameWithoutExtension(file.getFileName().toString());
191     }
192
193     private Optional<InputStream> getInputStream(final String csarId, final AssetType assetType) throws IOException {
194         final Path filePath = Paths.get(resourceLocation, csarId + DOT_CSAR);
195         if (Files.exists(filePath)) {
196             LOGGER.info("Found csar on file system using path: {}", filePath);
197             return Optional.of(Files.newInputStream(filePath));
198         }
199         LOGGER.warn("Couldn't find file on file system '{}', will search it in classpath", filePath);
200
201         final String path = MAIN_RESOURCE_FOLDER + assetType.toString() + FORWARD_SLASH + csarId + DOT_CSAR;
202         final ClassPathResource classPathResource = getClassPathResource(path);
203         if (classPathResource.exists()) {
204             LOGGER.info("Found csar in classpath using path: {}", path);
205             return Optional.of(classPathResource.getInputStream());
206         }
207
208         LOGGER.error("Couldn't find csar in classpath ....");
209         return Optional.empty();
210     }
211
212     private ClassPathResource getClassPathResource(final String path) {
213         return new ClassPathResource(path, this.getClass());
214     }
215
216 }