Updating image version and fixing tests
[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         final Path dir = Paths.get(resourceLocation);
86         if (Files.exists(dir)) {
87             try (final DirectoryStream<Path> stream = Files.newDirectoryStream(dir, WILD_CARD_REGEX + DOT_CSAR)) {
88                 for (final Path entry : stream) {
89                     final String filename = getFilenameWithoutExtension(entry);
90                     final ResourceArtifact artifact = getResourceArtifact(filename);
91                     result.add(artifact);
92                     LOGGER.info("Found resource on file system: {}", artifact);
93                 }
94             } catch (final IOException ioException) {
95                 LOGGER.error("Unable to find resources on filesystem", ioException);
96             }
97         }
98         try {
99             final String csarFileLocationPattern =
100                     CLASSPATH_ALL_URL_PREFIX + MAIN_RESOURCE_FOLDER + WILD_CARD_REGEX + DOT_CSAR;
101             final Resource[] resources = resourcePatternResolver.getResources(csarFileLocationPattern);
102             if (resources != null) {
103                 for (final Resource resource : resources) {
104                     final ResourceArtifact artifact =
105                             getResourceArtifact(getFilenameWithoutExtension(resource.getFilename()));
106                     result.add(artifact);
107                     LOGGER.info("Found resource in classpath: {}", artifact);
108                 }
109             }
110         } catch (final IOException ioException) {
111             LOGGER.error("Unable to find resources in classpath", ioException);
112         }
113         return result;
114     }
115
116     private ResourceArtifact getResourceArtifact(final String filename) {
117         return new ResourceArtifact().uuid(filename).invariantUuid(filename).name(filename).version("1.0")
118                 .toscaModelUrl(CATALOG_URL + "/resources/" + filename + "/toscaModel").category("Generic")
119                 .subCategory("Network Service").resourceType("VF").lifecycleState("CERTIFIED")
120                 .lastUpdaterUserId("SDC_SIMULATOR");
121     }
122
123     private String getFilenameWithoutExtension(final String filename) {
124         return filename.substring(0, filename.lastIndexOf('.'));
125     }
126
127     private String getFilenameWithoutExtension(final Path file) {
128         return getFilenameWithoutExtension(file.getFileName().toString());
129     }
130
131     private Optional<InputStream> getInputStream(final String csarId) throws IOException {
132         final Path filePath = Paths.get(resourceLocation, csarId + DOT_CSAR);
133         if (Files.exists(filePath)) {
134             LOGGER.info("Found resource in on file system using path: {}", filePath);
135             return Optional.of(Files.newInputStream(filePath));
136         }
137
138         LOGGER.warn("Couldn't find file on file system '{}', will search it in classpath", filePath);
139         final String path = MAIN_RESOURCE_FOLDER + csarId + DOT_CSAR;
140         ClassPathResource classPathResource = getClassPathResource(path);
141         if (classPathResource.exists()) {
142             LOGGER.info("Found resource in classpath using path: {}", path);
143             return Optional.of(classPathResource.getInputStream());
144         }
145
146         LOGGER.warn("Couldn't find file on file system '{}', will return default csar", filePath);
147         classPathResource = getClassPathResource(getDefaultCsarPath());
148         if (classPathResource.exists()) {
149             LOGGER.info("Found  default csar in classpath");
150             return Optional.of(classPathResource.getInputStream());
151         }
152
153         LOGGER.error("Couldn't find default csar in classpath ....");
154         return Optional.empty();
155     }
156
157     private ClassPathResource getClassPathResource(final String path) {
158         return new ClassPathResource(path, this.getClass());
159     }
160
161     /*
162      * Used in test
163      */
164     String getDefaultCsarPath() {
165         return Constants.DEFAULT_CSAR_PATH;
166     }
167 }