2 * Copyright 2020 Nokia.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.onap.vtp.execution;
19 import com.google.gson.Gson;
20 import com.google.gson.JsonArray;
21 import com.google.gson.JsonElement;
22 import com.google.gson.JsonParseException;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
27 import java.io.IOException;
28 import java.nio.file.Files;
29 import java.util.Arrays;
30 import java.util.Comparator;
31 import java.util.Optional;
33 public class VTPExecutionResultsSupplier {
35 public static final Logger logger = LoggerFactory.getLogger(VTPExecutionResultsSupplier.class);
37 private static final String SUB_PATH_TO_EXECUTION_OUTPUT = "/output";
38 private static final Gson gson = new Gson();
40 protected String pathToExecutions;
42 VTPExecutionResultsSupplier(String pathToExecutions) {
43 this.pathToExecutions = pathToExecutions;
46 public JsonElement getExecutionOutputsFromFile(String executionId) {
47 File directoryWithExecutionFiles = new File(pathToExecutions);
48 return getExecutionFilesForGivenRequest(executionId, directoryWithExecutionFiles)
49 .map(this::getOutputOfLatestExecutionFile)
50 .orElse(createNoOutputFileErrorMessageInJsonFormat());
53 private Optional<File[]> getExecutionFilesForGivenRequest(String requestId, File directoryWithExecutionsData) {
54 return Optional.ofNullable(
55 directoryWithExecutionsData.listFiles((dir, name) -> name.startsWith(requestId))
59 private JsonElement getOutputOfLatestExecutionFile(File[] directoriesWithExecutionsData) {
60 return Arrays.stream(directoriesWithExecutionsData)
61 .max(Comparator.comparing(File::lastModified))
62 .map(file -> new File(file.getAbsolutePath() + SUB_PATH_TO_EXECUTION_OUTPUT))
64 .map(this::loadOutputJsonFromFile)
65 .orElse(createNoOutputFileErrorMessageInJsonFormat());
68 private JsonArray loadOutputJsonFromFile(File file) {
71 String executionResult = Files.readString(file.toPath());
72 outputJson = gson.fromJson(executionResult, JsonArray.class);
73 } catch (IOException | JsonParseException e) {
74 logger.error(e.getMessage(),e);
75 String errorMessage = "" +
76 "[{ \"error\": \"fail to load execution result\",\"reason\":\"" + e.getMessage() + "\"}]";
77 outputJson = gson.fromJson(errorMessage, JsonArray.class);
82 private JsonArray createNoOutputFileErrorMessageInJsonFormat() {
83 return gson.fromJson("[{ \"error\": \"unable to find execution results\"}]", JsonArray.class);