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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.so.sdcsimulator.providers;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 import java.util.Optional;
29 import org.onap.so.sdcsimulator.utils.Constants;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.springframework.beans.factory.annotation.Value;
33 import org.springframework.core.io.ClassPathResource;
34 import org.springframework.stereotype.Service;
35 import org.springframework.util.StreamUtils;
38 * @author Eoin Hanan (eoin.hanan@est.tech)
41 public class ResourceProviderImpl implements ResourceProvider {
43 private static final Logger LOGGER = LoggerFactory.getLogger(ResourceProvider.class);
45 private final String resourceLocation;
47 public ResourceProviderImpl(@Value("${sdc.resource.location:/app/csars/}") final String resourceLocation) {
48 this.resourceLocation = resourceLocation;
52 public Optional<byte[]> getResource(final String csarId) {
54 final Optional<InputStream> optionalInputStream = getInputStream(csarId);
55 if (optionalInputStream.isPresent()) {
56 return Optional.of(StreamUtils.copyToByteArray(optionalInputStream.get()));
58 } catch (final IOException ioException) {
59 LOGGER.warn("Unable to create file stream ...", ioException);
62 return Optional.empty();
66 public Optional<InputStream> getInputStream(final String csarId) throws IOException {
67 final Path filePath = Paths.get(resourceLocation, csarId + ".csar");
68 if (Files.exists(filePath)) {
69 return Optional.of(Files.newInputStream(filePath));
72 LOGGER.info("Couldn't find file on file system '{}', will return default csar", filePath);
73 final ClassPathResource classPathResource = new ClassPathResource(getDefaultCsarPath(), this.getClass());
74 if (classPathResource.exists()) {
75 return Optional.of(classPathResource.getInputStream());
78 LOGGER.error("Couldn't find default csar in classpath ....");
79 return Optional.empty();
85 String getDefaultCsarPath() {
86 return Constants.DEFAULT_CSAR_PATH;