6db3797f9b3acb277fa6cff121d53c133f9a76fb
[so.git] / adapters / mso-vnfm-adapter / mso-vnfm-etsi-adapter / src / main / java / org / onap / so / adapters / vnfmadapter / rest / Sol003PackageManagementSubscriptionController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 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.so.adapters.vnfmadapter.rest;
22
23 import static org.onap.so.adapters.vnfmadapter.Constants.PACKAGE_MANAGEMENT_BASE_URL;
24 import static org.slf4j.LoggerFactory.getLogger;
25 import java.net.URI;
26 import java.security.GeneralSecurityException;
27 import java.util.List;
28 import java.util.Optional;
29 import javax.ws.rs.core.MediaType;
30 import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.ProblemDetails;
31 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2002;
32 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.PkgmSubscriptionRequest;
33 import org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement.SubscriptionManager;
34 import org.slf4j.Logger;
35 import org.springframework.beans.factory.annotation.Autowired;
36 import org.springframework.http.HttpHeaders;
37 import org.springframework.http.HttpStatus;
38 import org.springframework.http.ResponseEntity;
39 import org.springframework.stereotype.Controller;
40 import org.springframework.web.bind.annotation.DeleteMapping;
41 import org.springframework.web.bind.annotation.GetMapping;
42 import org.springframework.web.bind.annotation.PathVariable;
43 import org.springframework.web.bind.annotation.PostMapping;
44 import org.springframework.web.bind.annotation.RequestBody;
45 import org.springframework.web.bind.annotation.RequestMapping;
46
47 /**
48  * Controller for handling the Subscription Management. The client can use this resource to subscribe to notifications
49  * related to the VNF package management, and to query its subscriptions. For further information please read:
50  * https://www.etsi.org/deliver/etsi_gs/NFV-SOL/001_099/003/02.05.01_60/gs_nfv-sol003v020501p.pdf Use the section number
51  * above each endpoint to find the corresponding section in the above document.
52  *
53  * @author Ronan Kenny (ronan.kenny@est.tech)
54  * @author Gareth Roper (gareth.roper@est.tech)
55  */
56 @Controller
57 @RequestMapping(value = PACKAGE_MANAGEMENT_BASE_URL, produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML},
58         consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
59 public class Sol003PackageManagementSubscriptionController {
60
61     private static final String LOG_REQUEST_RECEIVED = "Subscription Management Controller: {} {}";
62     private static final Logger logger = getLogger(Sol003PackageManagementSubscriptionController.class);
63     private final SubscriptionManager subscriptionManager;
64
65     @Autowired
66     public Sol003PackageManagementSubscriptionController(final SubscriptionManager subscriptionManager) {
67         this.subscriptionManager = subscriptionManager;
68     }
69
70     /**
71      * POST Subscribe request. Will send request and respond with the subscription that you subscribed to, if
72      * successful. Section Number: 10.4.7
73      * 
74      * @param pkgmSubscriptionRequest This includes the details of the subscription to be created.
75      * @return The subscription requested, if successful. Object: InlineRespone2002 Response Code: 201 Created Response
76      *         Code: 303 Duplicate Subscription
77      * @throws GeneralSecurityException
78      */
79     @PostMapping(value = "/subscriptions")
80     public ResponseEntity<?> postSubscriptionRequest(@RequestBody final PkgmSubscriptionRequest pkgmSubscriptionRequest)
81             throws GeneralSecurityException {
82         logger.info(LOG_REQUEST_RECEIVED, " postSubscriptionRequest Endpoint Called", pkgmSubscriptionRequest);
83
84         // Check if subscription exists already.
85         final Optional<String> exists = subscriptionManager.getSubscriptionId(pkgmSubscriptionRequest);
86
87         if (exists.isPresent()) {
88             final URI subscriptionUri = subscriptionManager.getSubscriptionUri(exists.get());
89             final HttpHeaders headers = createLocationHeader(subscriptionUri);
90             logger.info("PkgmSubscriptionRequest already exists with uri {} ", subscriptionUri);
91             return new ResponseEntity<>(headers, HttpStatus.SEE_OTHER);
92         }
93
94         logger.debug("No duplicate Subscription exists, continuing with POST.");
95         final Optional<InlineResponse2002> optionalInlineResponse2002 =
96                 subscriptionManager.createSubscription(pkgmSubscriptionRequest);
97
98         if (optionalInlineResponse2002.isPresent()) {
99             InlineResponse2002 inlineResponse2002 = optionalInlineResponse2002.get();
100             final URI subscriptionUri = subscriptionManager.getSubscriptionUri(inlineResponse2002.getId());
101             final HttpHeaders headers = createLocationHeader(subscriptionUri);
102             logger.debug("Sending response with uri {} ", subscriptionUri);
103             return new ResponseEntity<>(inlineResponse2002, headers, HttpStatus.CREATED);
104         }
105         final String errorMessage = "A null response was received during the postSubscriptionRequest call.";
106         logger.error(errorMessage);
107         return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage));
108     }
109
110     /**
111      * GET all subscriptions. Will return a list of all subscriptions currently active. Section Number: 10.4.7
112      * 
113      * @return All of the current active subscriptions. Object: List<InlineResponse2002> Response Code: 200 OK
114      */
115     @GetMapping(value = "/subscriptions")
116     public ResponseEntity<List<InlineResponse2002>> getSubscriptions() {
117         logger.info(LOG_REQUEST_RECEIVED, " getSubscriptions.");
118         List<InlineResponse2002> subscriptionsList = subscriptionManager.getSubscriptions();
119         return new ResponseEntity<>(subscriptionsList, HttpStatus.OK);
120     }
121
122     /**
123      * GET a specific subscription, by subscriptionId. Section Number: 10.4.8
124      * 
125      * @param subscriptionId The ID of the subscription that you wish to retrieve.
126      * @return A subscription based on subscriptionId. Object: InlineResponse2002 Response Code: 200 OK
127      */
128     @GetMapping(value = "/subscriptions/{subscriptionId}")
129     public ResponseEntity<?> getSubscription(@PathVariable("subscriptionId") final String subscriptionId) {
130         logger.info(LOG_REQUEST_RECEIVED, " Getting Subscription: ", subscriptionId);
131         final Optional<InlineResponse2002> optional = subscriptionManager.getSubscription(subscriptionId);
132         if (optional.isPresent()) {
133             logger.debug("Return subscription with id {} and body {}", subscriptionId, optional);
134             return new ResponseEntity<>(optional.get(), HttpStatus.OK);
135         }
136         final String errorMessage =
137                 "The requested subscription: " + subscriptionId + " was not found on call getSubscription";
138         logger.error(errorMessage);
139         return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ProblemDetails().detail(errorMessage));
140     }
141
142     /**
143      * DELETE a specific subscription, by subscriptionId. Section Number: 10.4.8.3.5
144      *
145      * @param subscriptionId The ID of the subscription that you wish to delete.
146      * @return Empty response if successful. Object: Void Response Code: 204 No Content
147      */
148     @DeleteMapping(value = "/subscriptions/{subscriptionId}")
149     public ResponseEntity<?> deleteSubscription(@PathVariable("subscriptionId") final String subscriptionId) {
150         if (subscriptionManager.deleteSubscription(subscriptionId)) {
151             logger.debug("Successfully deleted subscription with id {}", subscriptionId);
152             return ResponseEntity.noContent().build();
153         }
154         final String errorMessage =
155                 "The requested subscription: " + subscriptionId + " was not found on call deleteSubscription";
156         logger.error(errorMessage);
157         return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ProblemDetails().detail(errorMessage));
158     }
159
160     /**
161      * Method to set the Location in the header with the URI parameter
162      * 
163      * @param subscriptionUri
164      * @return header with callbackUri in Location
165      */
166     private HttpHeaders createLocationHeader(final URI subscriptionUri) {
167         final HttpHeaders headers = new HttpHeaders();
168         headers.setLocation(subscriptionUri);
169         return headers;
170     }
171
172 }