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