Adding logic to read response files from
[cps.git] / cps-ncmp-rest-stub / cps-ncmp-rest-stub-service / src / main / java / org / onap / cps / ncmp / rest / stub / providers / ResourceProviderImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2023 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.cps.ncmp.rest.stub.providers;
22
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 lombok.extern.slf4j.Slf4j;
30 import org.springframework.beans.factory.annotation.Autowired;
31 import org.springframework.beans.factory.annotation.Value;
32 import org.springframework.core.io.ClassPathResource;
33 import org.springframework.stereotype.Service;
34
35 @Slf4j
36 @Service
37 public class ResourceProviderImpl implements ResourceProvider {
38
39     private String pathToResponseFiles;
40
41     @Autowired
42     public ResourceProviderImpl(@Value("${stub.path}") final String pathToResponseFiles) {
43         this.pathToResponseFiles = pathToResponseFiles;
44     }
45
46     @Override
47     public Optional<InputStream> getResourceInputStream(final String filename) throws IOException {
48         final Path path = Paths.get(pathToResponseFiles).resolve(filename);
49
50         if (Files.exists(path)) {
51             log.info("Found resource file on file system using path: {}", path);
52             return Optional.of(Files.newInputStream(path));
53         }
54
55         log.warn("Couldn't find file on file system '{}', will search it in classpath", path);
56
57         final ClassPathResource resource = new ClassPathResource(path.toString());
58         if (resource.exists()) {
59             log.info("Found resource in classpath using path: {}", path);
60             return Optional.of(resource.getInputStream());
61         }
62
63         log.error("{} file not found on classpath or on file system", path);
64         return Optional.empty();
65     }
66
67 }