a4c52fd13da3d5e95bc12f36308697abe4366b4e
[so.git] / adapters / mso-vnfm-adapter / mso-vnfm-etsi-adapter / src / main / java / org / onap / so / adapters / vnfmadapter / packagemanagement / subscriptionmanagement / SubscriptionManager.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.packagemanagement.subscriptionmanagement;
22
23 import static org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.SubscriptionAuthentication.AuthTypeEnum.BASIC;
24 import static org.slf4j.LoggerFactory.getLogger;
25 import java.net.URI;
26 import java.security.GeneralSecurityException;
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Objects;
31 import java.util.Optional;
32 import org.onap.so.adapters.vnfmadapter.Constants;
33 import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogServiceProvider;
34 import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.BasicAuth;
35 import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.NsdmSubscription;
36 import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscription;
37 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2002;
38 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.PkgmSubscriptionRequest;
39 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsLinks;
40 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.VnfPackagesLinksSelf;
41 import org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement.cache.PackageManagementCacheServiceProvider;
42 import org.onap.so.adapters.vnfmadapter.rest.exceptions.InternalServerErrorException;
43 import org.onap.so.adapters.vnfmadapter.rest.exceptions.SubscriptionNotFoundException;
44 import org.onap.so.adapters.vnfmadapter.rest.exceptions.ConversionFailedException;
45 import org.onap.so.utils.CryptoUtils;
46 import org.slf4j.Logger;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.beans.factory.annotation.Value;
49 import org.springframework.core.convert.ConversionService;
50 import org.springframework.stereotype.Service;
51
52 /**
53  * Manages package management subscriptions from the VNFMs
54  *
55  * @author Ronan Kenny (ronan.kenny@est.tech)
56  * @author Gareth Roper (gareth.roper@est.tech)
57  */
58 @Service
59 public class SubscriptionManager {
60
61     private static final Logger logger = getLogger(SubscriptionManager.class);
62     private final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider;
63     private final ConversionService conversionService;
64     private final EtsiCatalogServiceProvider etsiCatalogServiceProvider;
65     private final String vnfmAdapterEndpoint;
66     private final String msoKeyString;
67     private final String vnfmAdapterAuth;
68
69     @Autowired
70     public SubscriptionManager(final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider,
71             final ConversionService conversionService, final EtsiCatalogServiceProvider etsiCatalogServiceProvider,
72             @Value("${vnfmadapter.endpoint}") final String vnfmAdapterEndpoint,
73             @Value("${mso.key}") final String msoKeyString,
74             @Value("${vnfmadapter.auth:BF29BA36F0CFE1C05507781F6B97EFBCA7EFAC9F595954D465FC43F646883EF585C20A58CBB02528A6FAAC}") final String vnfmAdapterAuth) {
75         this.packageManagementCacheServiceProvider = packageManagementCacheServiceProvider;
76         this.conversionService = conversionService;
77         this.etsiCatalogServiceProvider = etsiCatalogServiceProvider;
78         this.vnfmAdapterEndpoint = vnfmAdapterEndpoint;
79         this.vnfmAdapterAuth = vnfmAdapterAuth;
80         this.msoKeyString = msoKeyString;
81     }
82
83     public Optional<InlineResponse2002> createSubscription(final PkgmSubscriptionRequest pkgmSubscriptionRequest)
84             throws GeneralSecurityException {
85
86         final org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest =
87                 buildEtsiCatalogManagerPkgmSubscriptionRequest(pkgmSubscriptionRequest);
88
89         final Optional<PkgmSubscription> optionalEtsiCatalogManagerSubscription =
90                 etsiCatalogServiceProvider.postSubscription(etsiCatalogManagerSubscriptionRequest);
91
92         if (optionalEtsiCatalogManagerSubscription.isPresent()) {
93             final PkgmSubscription etsiCatalogManagerSubscription = optionalEtsiCatalogManagerSubscription.get();
94             logger.debug("postPkgmSubscriptionRequest Response SubscriptionId: {}",
95                     Objects.requireNonNull(etsiCatalogManagerSubscription.getId()));
96             final String subscriptionId = etsiCatalogManagerSubscription.getId();
97
98             packageManagementCacheServiceProvider.addSubscription(subscriptionId, pkgmSubscriptionRequest);
99
100             final InlineResponse2002 response2002 = new InlineResponse2002();
101             response2002.setId(subscriptionId);
102             response2002.setFilter(pkgmSubscriptionRequest.getFilter());
103             response2002.setCallbackUri(getSubscriptionUri(subscriptionId).toString());
104             response2002.setLinks(new SubscriptionsLinks()
105                     .self(new VnfPackagesLinksSelf().href(getSubscriptionUri(subscriptionId).toString())));
106
107             return Optional.of(response2002);
108         }
109         throw new InternalServerErrorException(
110                 "Received empty response from POST to ETSI Catalog Manager Subscription Endpoint.");
111     }
112
113     public Optional<String> getSubscriptionId(final PkgmSubscriptionRequest pkgmSubscriptionRequest) {
114         return packageManagementCacheServiceProvider.getSubscriptionId(pkgmSubscriptionRequest);
115     }
116
117     public Optional<InlineResponse2002> getSubscription(final String subscriptionId) {
118
119         logger.debug("Checking if subscrition with id: {} exists in ETSI Catalog Manager", subscriptionId);
120         final Optional<NsdmSubscription> etsiCatalogSubscriptionOption =
121                 etsiCatalogServiceProvider.getSubscription(subscriptionId);
122
123         if (!etsiCatalogSubscriptionOption.isPresent()) {
124             logger.debug("Unable to find subscription in ETSI Catalog Manager using id: {}", subscriptionId);
125             if (packageManagementCacheServiceProvider.getSubscription(subscriptionId).isPresent()) {
126                 logger.debug("will remove subcription with id: {} from local cache", subscriptionId);
127                 packageManagementCacheServiceProvider.deleteSubscription(subscriptionId);
128             }
129         }
130
131         final Optional<PkgmSubscriptionRequest> optional =
132                 packageManagementCacheServiceProvider.getSubscription(subscriptionId);
133         if (optional.isPresent()) {
134             final PkgmSubscriptionRequest subscription = optional.get();
135             return Optional.of(getInlineResponse2002(subscriptionId, subscription));
136         }
137         return Optional.empty();
138     }
139
140     public List<InlineResponse2002> getSubscriptions() {
141         final Map<String, PkgmSubscriptionRequest> subscriptions =
142                 packageManagementCacheServiceProvider.getSubscriptions();
143         final List<InlineResponse2002> response = new ArrayList<>();
144         subscriptions.forEach((key, value) -> {
145             final Optional<InlineResponse2002> optional = getSubscription(key);
146             if (optional.isPresent()) {
147                 response.add(optional.get());
148             }
149         });
150         return response;
151     }
152
153     public boolean deleteSubscription(final String subscriptionId) {
154         if (packageManagementCacheServiceProvider.getSubscription(subscriptionId).isPresent()) {
155             try {
156                 if (etsiCatalogServiceProvider.deleteSubscription(subscriptionId)) {
157                     return packageManagementCacheServiceProvider.deleteSubscription(subscriptionId);
158                 }
159             } catch (final SubscriptionNotFoundException subscriptionNotFoundException) {
160                 logger.error(
161                         "Unable to find subscription in ETSI Catalog Manager using id: {} will delete it from local cache",
162                         subscriptionId);
163                 return packageManagementCacheServiceProvider.deleteSubscription(subscriptionId);
164             }
165         }
166         return false;
167     }
168
169     public URI getSubscriptionUri(final String subscriptionId) {
170         return URI.create(
171                 vnfmAdapterEndpoint + Constants.PACKAGE_MANAGEMENT_BASE_URL + "/subscriptions/" + subscriptionId);
172     }
173
174     public Optional<PkgmSubscriptionRequest> getSubscriptionRequest(final String subscriptionId) {
175         return packageManagementCacheServiceProvider.getSubscription(subscriptionId);
176     }
177
178     private InlineResponse2002 getInlineResponse2002(final String id, final PkgmSubscriptionRequest subscription) {
179         return new InlineResponse2002().id(id).filter(subscription.getFilter())
180                 .callbackUri(subscription.getCallbackUri());
181     }
182
183     private org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest buildEtsiCatalogManagerPkgmSubscriptionRequest(
184             final PkgmSubscriptionRequest pkgmSubscriptionRequest) throws GeneralSecurityException {
185
186         final org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest;
187         try {
188             etsiCatalogManagerSubscriptionRequest = conversionService.convert(pkgmSubscriptionRequest,
189                     org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest.class);
190         } catch (final org.springframework.core.convert.ConversionException conversionException) {
191             logger.error(conversionException.getMessage());
192             throw new ConversionFailedException(
193                     "Could not convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest");
194         } catch (final Exception exception) {
195             logger.error(exception.getMessage());
196             throw new InternalServerErrorException(
197                     "Could not convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest");
198         }
199
200         if (etsiCatalogManagerSubscriptionRequest != null) {
201             etsiCatalogManagerSubscriptionRequest
202                     .setCallbackUri(vnfmAdapterEndpoint + Constants.ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL);
203
204             final String[] auth = decryptAuth();
205             final String username = auth[0];
206             final String password = auth[1];
207
208             etsiCatalogManagerSubscriptionRequest.setAuthentication(
209                     new org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.SubscriptionAuthentication()
210                             .addAuthTypeItem(BASIC).paramsBasic(new BasicAuth().userName(username).password(password)));
211             return etsiCatalogManagerSubscriptionRequest;
212         }
213         throw new ConversionFailedException(
214                 "Failed to convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest");
215     }
216
217     private String[] decryptAuth() throws GeneralSecurityException {
218         final String decryptedAuth = CryptoUtils.decrypt(vnfmAdapterAuth, msoKeyString);
219         final String[] auth = decryptedAuth.split(":");
220         return auth;
221     }
222
223 }