85e1a44d482916673f78e9065c4ff76df58718bf
[nonrtric/plt/rappmanager.git] / rapp-manager-application / src / main / java / com / oransc / rappmanager / rest / RappController.java
1 /*-
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2023-2024 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.rest;
20
21 import com.oransc.rappmanager.configuration.RappManagerConfiguration;
22 import com.oransc.rappmanager.models.cache.RappCacheService;
23 import com.oransc.rappmanager.models.csar.RappCsarConfigurationHandler;
24 import com.oransc.rappmanager.models.csar.validator.RappValidationHandler;
25 import com.oransc.rappmanager.models.exception.RappHandlerException;
26 import com.oransc.rappmanager.models.rapp.PrimeOrder;
27 import com.oransc.rappmanager.models.rapp.Rapp;
28 import com.oransc.rappmanager.models.rapp.RappPrimeOrder;
29 import com.oransc.rappmanager.models.rapp.RappState;
30 import com.oransc.rappmanager.service.RappService;
31 import java.io.File;
32 import java.io.IOException;
33 import java.nio.file.Files;
34 import java.nio.file.StandardCopyOption;
35 import java.util.Collection;
36 import java.util.Optional;
37 import lombok.RequiredArgsConstructor;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.http.HttpStatus;
41 import org.springframework.http.ResponseEntity;
42 import org.springframework.web.bind.annotation.DeleteMapping;
43 import org.springframework.web.bind.annotation.GetMapping;
44 import org.springframework.web.bind.annotation.PathVariable;
45 import org.springframework.web.bind.annotation.PostMapping;
46 import org.springframework.web.bind.annotation.PutMapping;
47 import org.springframework.web.bind.annotation.RequestBody;
48 import org.springframework.web.bind.annotation.RequestMapping;
49 import org.springframework.web.bind.annotation.RequestPart;
50 import org.springframework.web.bind.annotation.RestController;
51 import org.springframework.web.multipart.MultipartFile;
52
53 @RestController
54 @RequestMapping(path = "rapps")
55 @RequiredArgsConstructor
56 public class RappController {
57
58     Logger logger = LoggerFactory.getLogger(RappController.class);
59     private final RappCsarConfigurationHandler rappCsarConfigurationHandler;
60     private final RappValidationHandler rappValidationHandler;
61     private final RappManagerConfiguration rappManagerConfiguration;
62     private final RappCacheService rappCacheService;
63     private final RappService rappService;
64     private static final String RAPP_NOT_FOUND = "rApp %s not found.";
65
66     @GetMapping
67     public ResponseEntity<Collection<Rapp>> getRapps() {
68         return ResponseEntity.ok(rappCacheService.getAllRapp());
69     }
70
71     @GetMapping("{rapp_id}")
72     public ResponseEntity<Rapp> getRapp(@PathVariable("rapp_id") String rappId) {
73         return rappCacheService.getRapp(rappId).map(ResponseEntity::ok).orElseThrow(
74                 () -> new RappHandlerException(HttpStatus.NOT_FOUND, String.format(RAPP_NOT_FOUND, rappId)));
75     }
76
77     @PostMapping("{rapp_id}")
78     public ResponseEntity<Rapp> createRapp(@PathVariable("rapp_id") String rappId,
79             @RequestPart("file") MultipartFile csarFilePart) throws IOException {
80         if (rappValidationHandler.isValidRappPackage(csarFilePart)) {
81             File csarFile = new File(
82                     rappCsarConfigurationHandler.getRappPackageLocation(rappManagerConfiguration.getCsarLocation(),
83                             rappId, csarFilePart.getOriginalFilename()).toUri());
84             csarFile.getParentFile().mkdirs();
85             Files.copy(csarFilePart.getInputStream(), csarFile.getAbsoluteFile().toPath(),
86                     StandardCopyOption.REPLACE_EXISTING);
87             Rapp rapp = Rapp.builder().name(rappId).packageLocation(rappManagerConfiguration.getCsarLocation())
88                                 .packageName(csarFile.getName()).state(RappState.COMMISSIONED).build();
89             rapp.setRappResources(rappCsarConfigurationHandler.getRappResource(rapp));
90             rappCacheService.putRapp(rapp);
91             return ResponseEntity.accepted().build();
92         } else {
93             logger.info("Invalid Rapp package for {}", rappId);
94             throw new RappHandlerException(HttpStatus.BAD_REQUEST, "Invalid rApp package.");
95         }
96     }
97
98     @PutMapping("{rapp_id}")
99     public ResponseEntity<String> primeRapp(@PathVariable("rapp_id") String rappId,
100             @RequestBody RappPrimeOrder rappPrimeOrder) {
101         // @formatter:off
102         return rappCacheService.getRapp(rappId)
103                        .map(rapp -> Optional.ofNullable(rappPrimeOrder.getPrimeOrder())
104                             .filter(primeOrder -> primeOrder.equals(PrimeOrder.PRIME))
105                             .map(primeOrder -> rappService.primeRapp(rapp))
106                             .orElseGet(() -> rappService.deprimeRapp(rapp)))
107                        .orElseThrow(() -> new RappHandlerException(HttpStatus.NOT_FOUND,
108                                String.format(RAPP_NOT_FOUND, rappId)));
109         // @formatter:on
110     }
111
112     @DeleteMapping("{rapp_id}")
113     public ResponseEntity<String> deleteRapp(@PathVariable("rapp_id") String rappId) {
114         // @formatter:off
115         return rappCacheService.getRapp(rappId)
116                .map(rappService::deleteRapp)
117                .orElseThrow(() -> new RappHandlerException(HttpStatus.NOT_FOUND,
118                        String.format(RAPP_NOT_FOUND, rappId)));
119         // @formatter:on
120     }
121 }