Upgrading current ETSI CSIT to latest honolulu
[integration/csit.git] / plans / so / integration-etsi-testing / so-simulators / sdc-simulator / src / main / java / org / onap / so / sdcsimulator / providers / ResourceProviderImpl.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.CATALOG_URL;
24 import static org.onap.so.sdcsimulator.utils.Constants.DOT_CSAR;
25 import static org.onap.so.sdcsimulator.utils.Constants.MAIN_RESOURCE_FOLDER;
26 import static org.onap.so.sdcsimulator.utils.Constants.WILD_CARD_REGEX;
27 import static org.springframework.core.io.support.ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.nio.file.DirectoryStream;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.util.HashSet;
35 import java.util.Optional;
36 import java.util.Set;
37 import org.onap.so.sdcsimulator.models.ResourceArtifact;
38 import org.onap.so.sdcsimulator.utils.Constants;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.beans.factory.annotation.Value;
43 import org.springframework.core.io.ClassPathResource;
44 import org.springframework.core.io.Resource;
45 import org.springframework.core.io.support.ResourcePatternResolver;
46 import org.springframework.stereotype.Service;
47 import org.springframework.util.StreamUtils;
48
49 /**
50  * @author Eoin Hanan (eoin.hanan@est.tech)
51  */
52 @Service
53 public class ResourceProviderImpl implements ResourceProvider {
54
55     private static final Logger LOGGER = LoggerFactory.getLogger(ResourceProvider.class);
56
57     private final String resourceLocation;
58
59     private final ResourcePatternResolver resourcePatternResolver;
60
61     @Autowired
62     public ResourceProviderImpl(@Value("${sdc.resource.location:/app/csars/}") final String resourceLocation,
63             final ResourcePatternResolver resourcePatternResolver) {
64         this.resourceLocation = resourceLocation;
65         this.resourcePatternResolver = resourcePatternResolver;
66     }
67
68     @Override
69     public Optional<byte[]> getResource(final String csarId) {
70         try {
71             final Optional<InputStream> optionalInputStream = getInputStream(csarId);
72             if (optionalInputStream.isPresent()) {
73                 return Optional.of(StreamUtils.copyToByteArray(optionalInputStream.get()));
74             }
75         } catch (final IOException ioException) {
76             LOGGER.warn("Unable to create file stream ...", ioException);
77         }
78
79         return Optional.empty();
80     }
81
82     @Override
83     public Set<ResourceArtifact> getResource() {
84         final Set<ResourceArtifact> result = new HashSet<>();
85
86         final Path dir = Paths.get(resourceLocation);
87         if (Files.exists(dir)) {
88             try (final DirectoryStream<Path> stream = Files.newDirectoryStream(dir, WILD_CARD_REGEX + DOT_CSAR)) {
89                 for (final Path entry : stream) {
90                     final String filename = getFilenameWithoutExtension(entry);
91                     final ResourceArtifact artifact = getResourceArtifact(filename);
92                     result.add(artifact);
93                     LOGGER.info("Found resource on file system: {}", artifact);
94
95
96                 }
97             } catch (final IOException ioException) {
98                 LOGGER.error("Unable to find resources on filesystem", ioException);
99             }
100         }
101
102         try {
103             final String csarFileLocationPattern =
104                     CLASSPATH_ALL_URL_PREFIX + MAIN_RESOURCE_FOLDER + WILD_CARD_REGEX + DOT_CSAR;
105             final Resource[] resources = resourcePatternResolver.getResources(csarFileLocationPattern);
106             if (resources != null) {
107
108                 for (final Resource resource : resources) {
109                     final ResourceArtifact artifact =
110                             getResourceArtifact(getFilenameWithoutExtension(resource.getFilename()));
111                     result.add(artifact);
112                     LOGGER.info("Found resource in classpath: {}", artifact);
113                 }
114             }
115
116         } catch (final IOException ioException) {
117             LOGGER.error("Unable to find resources in classpath", ioException);
118         }
119
120         return result;
121     }
122
123     private ResourceArtifact getResourceArtifact(final String filename) {
124         return new ResourceArtifact().uuid(filename).invariantUuid(filename).name(filename).version("1.0")
125                 .toscaModelUrl(CATALOG_URL + "/resources/" + filename + "/toscaModel").category("Generic")
126                 .subCategory("Network Service").resourceType("VF").lifecycleState("CERTIFIED")
127                 .lastUpdaterUserId("SDC_SIMULATOR");
128     }
129
130     private String getFilenameWithoutExtension(final String filename) {
131         return filename.substring(0, filename.lastIndexOf('.'));
132     }
133
134     private String getFilenameWithoutExtension(final Path file) {
135         return getFilenameWithoutExtension(file.getFileName().toString());
136     }
137
138     private Optional<InputStream> getInputStream(final String csarId) throws IOException {
139         final Path filePath = Paths.get(resourceLocation, csarId + DOT_CSAR);
140         if (Files.exists(filePath)) {
141             LOGGER.info("Found resource in on file system using path: {}", filePath);
142             return Optional.of(Files.newInputStream(filePath));
143         }
144         LOGGER.warn("Couldn't find file on file system '{}', will search it in classpath", filePath);
145
146         final String path = MAIN_RESOURCE_FOLDER + csarId + DOT_CSAR;
147         ClassPathResource classPathResource = getClassPathResource(path);
148         if (classPathResource.exists()) {
149             LOGGER.info("Found resource in classpath using path: {}", path);
150             return Optional.of(classPathResource.getInputStream());
151         }
152
153         LOGGER.warn("Couldn't find file on file system '{}', will return default csar", filePath);
154         classPathResource = getClassPathResource(getDefaultCsarPath());
155         if (classPathResource.exists()) {
156             LOGGER.info("Found  default csar in classpath");
157             return Optional.of(classPathResource.getInputStream());
158         }
159
160         LOGGER.error("Couldn't find default csar in classpath ....");
161         return Optional.empty();
162     }
163
164     private ClassPathResource getClassPathResource(final String path) {
165         return new ClassPathResource(path, this.getClass());
166     }
167
168     /*
169      * Used in test
170      */
171     String getDefaultCsarPath() {
172         return Constants.DEFAULT_CSAR_PATH;
173     }
174 }