Add info types for producer and consumer in rApp package
[nonrtric/plt/rappmanager.git] / rapp-manager-models / src / main / java / com / oransc / rappmanager / models / csar / RappCsarConfigurationHandler.java
1 /*-
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2023 Nordix Foundation. All rights reserved.
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  * ============LICENSE_END========================================================================
17  */
18
19 package com.oransc.rappmanager.models.csar;
20
21 import com.oransc.rappmanager.models.rapp.Rapp;
22 import com.oransc.rappmanager.models.rapp.RappResources;
23 import com.oransc.rappmanager.models.rappinstance.RappACMInstance;
24 import com.oransc.rappmanager.models.rappinstance.RappSMEInstance;
25 import java.io.ByteArrayOutputStream;
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.IOException;
29 import java.nio.file.Path;
30 import java.util.Set;
31 import java.util.UUID;
32 import java.util.function.Predicate;
33 import java.util.stream.Collectors;
34 import java.util.zip.ZipEntry;
35 import java.util.zip.ZipFile;
36 import org.apache.commons.compress.archivers.ArchiveEntry;
37 import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.stereotype.Service;
41 import org.springframework.web.multipart.MultipartFile;
42
43 @Service
44 public class RappCsarConfigurationHandler {
45
46     Logger logger = LoggerFactory.getLogger(RappCsarConfigurationHandler.class);
47     private static final String ACM_COMPOSITION_JSON_LOCATION = "Files/Acm/definition/compositions.json";
48     private static final String ACM_DEFINITION_LOCATION = "Files/Acm/definition";
49     private static final String ACM_INSTANCES_LOCATION = "Files/Acm/instances";
50     private static final String SME_PROVIDER_FUNCS_LOCATION = "Files/Sme/providers";
51     private static final String SME_SERVICE_APIS_LOCATION = "Files/Sme/serviceapis";
52     private static final String SME_INVOKERS_LOCATION = "Files/Sme/invokers";
53     private static final String DME_PRODUCER_INFO_TYPES_LOCATION = "Files/Dme/producerinfotypes";
54     private static final String DME_CONSUMER_INFO_TYPES_LOCATION = "Files/Dme/consumerinfotypes";
55     private static final String DME_INFO_PRODUCERS_LOCATION = "Files/Dme/infoproducers";
56     private static final String DME_INFO_CONSUMERS_LOCATION = "Files/Dme/infoconsumers";
57
58
59     public boolean isValidRappPackage(MultipartFile multipartFile) {
60         String originalFilename = multipartFile.getOriginalFilename();
61         if (originalFilename != null) {
62             return originalFilename.endsWith(".csar") && isFileExistsInCsar(multipartFile,
63                     ACM_COMPOSITION_JSON_LOCATION);
64         }
65         return false;
66     }
67
68     boolean isFileExistsInCsar(MultipartFile multipartFile, String fileLocation) {
69         try (ZipArchiveInputStream zipArchiveInputStream = new ZipArchiveInputStream(multipartFile.getInputStream())) {
70             ArchiveEntry zipEntry;
71             while ((zipEntry = zipArchiveInputStream.getNextEntry()) != null) {
72                 if (zipEntry.getName().matches(fileLocation)) {
73                     return Boolean.TRUE;
74                 }
75             }
76             return Boolean.FALSE;
77         } catch (IOException e) {
78             logger.error("Unable to find the CSAR file", e);
79             return Boolean.FALSE;
80         }
81     }
82
83     public Path getRappPackageLocation(String csarLocation, String rappId, String fileName) {
84         return Path.of(csarLocation, rappId, fileName);
85     }
86
87     public String getInstantiationPayload(Rapp rapp, RappACMInstance rappACMInstance, UUID compositionId) {
88         return getPayload(rapp, getResourceUri(ACM_INSTANCES_LOCATION, rappACMInstance.getInstance())).replaceAll(
89                 "COMPOSITIONID", String.valueOf(compositionId));
90     }
91
92     String getPayload(Rapp rapp, String location) {
93         logger.debug("Getting payload for {} from {}", rapp.getRappId(), location);
94         File csarFile = getCsarFile(rapp);
95         return getFileFromCsar(csarFile, location).toString();
96     }
97
98     File getCsarFile(Rapp rapp) {
99         return new File(
100                 getRappPackageLocation(rapp.getPackageLocation(), rapp.getName(), rapp.getPackageName()).toUri());
101     }
102
103     ByteArrayOutputStream getFileFromCsar(File csarFile, String fileLocation) {
104         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
105         try (FileInputStream fileInputStream = new FileInputStream(csarFile);
106              ZipArchiveInputStream zipArchiveInputStream = new ZipArchiveInputStream(fileInputStream)) {
107             ArchiveEntry entry;
108             while ((entry = zipArchiveInputStream.getNextEntry()) != null) {
109                 if (!entry.isDirectory() && entry.getName().equals(fileLocation)) {
110                     byte[] buffer = new byte[1024];
111                     int bytesRead;
112                     while ((bytesRead = zipArchiveInputStream.read(buffer)) != -1) {
113                         byteArrayOutputStream.write(buffer, 0, bytesRead);
114                     }
115                 }
116             }
117         } catch (IOException e) {
118             logger.error("Unable to find the CSAR file", e);
119         }
120         return byteArrayOutputStream;
121     }
122
123
124     public String getSmeProviderDomainPayload(Rapp rapp, RappSMEInstance rappSMEInstance) {
125         return getPayload(rapp, getResourceUri(SME_PROVIDER_FUNCS_LOCATION, rappSMEInstance.getProviderFunction()));
126     }
127
128     public String getSmeProviderApiPayload(Rapp rapp, RappSMEInstance rappSMEInstance) {
129         return getPayload(rapp, getResourceUri(SME_SERVICE_APIS_LOCATION, rappSMEInstance.getServiceApis()));
130     }
131
132     public String getSmeInvokerPayload(Rapp rapp, RappSMEInstance rappSMEInstance) {
133         return getPayload(rapp, getResourceUri(SME_INVOKERS_LOCATION, rappSMEInstance.getInvokers()));
134     }
135
136     public String getAcmCompositionPayload(Rapp rapp) {
137         return getPayload(rapp,
138                 getResourceUri(ACM_DEFINITION_LOCATION, rapp.getRappResources().getAcm().getCompositionDefinitions()));
139     }
140
141     public String getDmeInfoProducerPayload(Rapp rapp, String producerIdentifier) {
142         return getPayload(rapp, getResourceUri(DME_INFO_PRODUCERS_LOCATION, producerIdentifier));
143     }
144
145     public String getDmeProducerInfoTypePayload(Rapp rapp, String infoTypeIdentifier) {
146         return getPayload(rapp, getResourceUri(DME_PRODUCER_INFO_TYPES_LOCATION, infoTypeIdentifier));
147     }
148
149     public String getDmeConsumerInfoTypePayload(Rapp rapp, String infoTypeIdentifier) {
150         return getPayload(rapp, getResourceUri(DME_CONSUMER_INFO_TYPES_LOCATION, infoTypeIdentifier));
151     }
152
153     public String getDmeInfoConsumerPayload(Rapp rapp, String infoConsumerIdentifier) {
154         return getPayload(rapp, getResourceUri(DME_INFO_CONSUMERS_LOCATION, infoConsumerIdentifier));
155     }
156
157     String getResourceUri(String resourceLocation, String resource) {
158         return resourceLocation + "/" + resource + ".json";
159     }
160
161     public RappResources getRappResource(Rapp rapp) {
162         RappResources rappResources = new RappResources();
163         try {
164             File csarFile = getCsarFile(rapp);
165             if (csarFile.exists()) {
166                 rappResources.setAcm(RappResources.ACMResources.builder().compositionDefinitions(
167                         getFileListFromCsar(csarFile, ACM_DEFINITION_LOCATION).iterator().next()).compositionInstances(
168                         getFileListFromCsar(csarFile, ACM_INSTANCES_LOCATION)).build());
169                 rappResources.setSme(RappResources.SMEResources.builder().providerFunctions(
170                                 getFileListFromCsar(csarFile, SME_PROVIDER_FUNCS_LOCATION))
171                                              .serviceApis(getFileListFromCsar(csarFile, SME_SERVICE_APIS_LOCATION))
172                                              .invokers(getFileListFromCsar(csarFile, SME_INVOKERS_LOCATION)).build());
173                 rappResources.setDme(RappResources.DMEResources.builder().producerInfoTypes(
174                                 getFileListFromCsar(csarFile, DME_PRODUCER_INFO_TYPES_LOCATION)).consumerInfoTypes(
175                                 getFileListFromCsar(csarFile, DME_CONSUMER_INFO_TYPES_LOCATION))
176                                              .infoProducers(getFileListFromCsar(csarFile, DME_INFO_PRODUCERS_LOCATION))
177                                              .infoConsumers(getFileListFromCsar(csarFile, DME_INFO_CONSUMERS_LOCATION))
178                                              .build());
179             }
180         } catch (Exception e) {
181             logger.warn("Error in getting the rapp resources", e);
182         }
183         return rappResources;
184     }
185
186     Set<String> getFileListFromCsar(File csarFile, String dirLocation) {
187         try (ZipFile zipFile = new ZipFile(csarFile)) {
188             return zipFile.stream().filter(Predicate.not(ZipEntry::isDirectory)).map(ZipEntry::getName)
189                            .filter(name -> name.startsWith(dirLocation))
190                            .map(name -> name.substring(name.lastIndexOf("/") + 1, name.lastIndexOf(".")))
191                            .collect(Collectors.toSet());
192         } catch (IOException e) {
193             logger.warn("Error in listing the files from csar", e);
194         }
195         return Set.of();
196     }
197 }