aboutsummaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/main/java/org/onap/vid/controller/OperationalEnvironmentController.java
blob: 21aef68588cb9ebf69d92454818a2def449e0196 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*-
 * ============LICENSE_START=======================================================
 * VID
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * Modifications Copyright (C) 2018 Nokia. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.onap.vid.controller;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import io.joshworks.restclient.http.HttpResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.vid.changeManagement.RequestDetailsWrapper;
import org.onap.vid.model.ExceptionResponse;
import org.onap.vid.model.RequestReferencesContainer;
import org.onap.vid.mso.MsoBusinessLogic;
import org.onap.vid.mso.MsoInterface;
import org.onap.vid.mso.MsoResponseWrapper2;
import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo;
import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo;
import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails;
import org.onap.vid.mso.rest.RequestDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.onap.vid.utils.Logging.getMethodCallerName;
import static org.onap.vid.utils.Logging.getMethodName;

@RestController
@RequestMapping("operationalEnvironment")
public class OperationalEnvironmentController extends VidRestrictedBaseController {

    private final MsoInterface restMso;
    private final MsoBusinessLogic msoBusinessLogic;

    private static final Pattern RECOVERY_ACTION_MESSAGE_PATTERN = Pattern.compile("from String \"(.*)\": value not");


    @Autowired
    public OperationalEnvironmentController(MsoBusinessLogic msoBusinessLogic, MsoInterface msoClientInterface) {
        this.restMso = msoClientInterface;
        this.msoBusinessLogic = msoBusinessLogic;
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public MsoResponseWrapper2 createOperationalEnvironment(HttpServletRequest request, @RequestBody OperationalEnvironmentCreateBody operationalEnvironment) {
        debugStart(operationalEnvironment);
        String userId = ControllersUtils.extractUserId(request);
        RequestDetailsWrapper<OperationEnvironmentRequestDetails> requestDetailsWrapper = msoBusinessLogic.convertParametersToRequestDetails(operationalEnvironment, userId);
        String path = msoBusinessLogic.getOperationalEnvironmentCreationPath();

        HttpResponse<RequestReferencesContainer> msoResponse = restMso.post(path, requestDetailsWrapper, RequestReferencesContainer.class);
        debugEnd(msoResponse);
        return new MsoResponseWrapper2<>(msoResponse);
    }

    @RequestMapping(value = "/activate", method = RequestMethod.POST)
    public MsoResponseWrapper2 activate(HttpServletRequest request,
                                        @RequestParam("operationalEnvironment") String operationalEnvironmentId,
                                        @RequestBody OperationalEnvironmentActivateBody activateRequest) throws MissingServletRequestParameterException {

        verifyIsNotEmpty(operationalEnvironmentId, "operationalEnvironment");

        //manifest is null in case of wrong manifest structure (deserialization failure of the manifest)
        if (activateRequest.getManifest()==null || activateRequest.getManifest().getServiceModelList()==null) {
            throw new BadManifestException("Manifest structure is wrong");
        }

        String userId = ControllersUtils.extractUserId(request);

        OperationalEnvironmentActivateInfo activateInfo = new OperationalEnvironmentActivateInfo(activateRequest, userId, operationalEnvironmentId);
        debugStart(activateInfo);

        String path = msoBusinessLogic.getOperationalEnvironmentActivationPath(activateInfo);
        RequestDetailsWrapper<RequestDetails> requestDetailsWrapper = msoBusinessLogic.createOperationalEnvironmentActivationRequestDetails(activateInfo);

        HttpResponse<RequestReferencesContainer> msoResponse = restMso.post(path, requestDetailsWrapper, RequestReferencesContainer.class);

        debugEnd(msoResponse);
        return new MsoResponseWrapper2<>(msoResponse);
    }

    @RequestMapping(value = "/deactivate", method = RequestMethod.POST)
    public MsoResponseWrapper2 deactivate(HttpServletRequest request,
                                          @RequestParam("operationalEnvironment") String operationalEnvironmentId,
                                          @RequestBody Map deactivationRequest) throws MissingServletRequestParameterException {

        verifyIsNotEmpty(operationalEnvironmentId, "operationalEnvironment");

        String userId = ControllersUtils.extractUserId(request);

        OperationalEnvironmentDeactivateInfo deactivateInfo = new OperationalEnvironmentDeactivateInfo(userId, operationalEnvironmentId);
        debugStart(deactivateInfo);

        String path = msoBusinessLogic.getOperationalEnvironmentDeactivationPath(deactivateInfo);
        RequestDetailsWrapper<RequestDetails> requestDetailsWrapper =  msoBusinessLogic.createOperationalEnvironmentDeactivationRequestDetails(deactivateInfo);

        HttpResponse<RequestReferencesContainer> msoResponse = restMso.post(path, requestDetailsWrapper, RequestReferencesContainer.class);

        debugEnd(msoResponse);
        return new MsoResponseWrapper2<>(msoResponse);
    }

    @RequestMapping(value = "/requestStatus", method = RequestMethod.GET)
    public MsoResponseWrapper2 status(HttpServletRequest request, @RequestParam("requestId") String requestId) throws MissingServletRequestParameterException {

        debugStart(requestId);

        verifyIsNotEmpty(requestId, "requestId");
        String path = msoBusinessLogic.getCloudResourcesRequestsStatusPath(requestId);

        HttpResponse<HashMap> msoResponse = restMso.get(path, HashMap.class);

        LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), msoResponse);
        return new MsoResponseWrapper2<>(msoResponse);
    }

    @ExceptionHandler({
            org.springframework.web.bind.MissingServletRequestParameterException.class,
            BadManifestException.class
    })
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public ExceptionResponse clientDerivedExceptionAsBadRequest(Exception e) {
        // same handler, different HTTP Code
        return exceptionHandler(e);
    }

    @ExceptionHandler({
            org.springframework.http.converter.HttpMessageNotReadableException.class,
    })
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public ExceptionResponse handlingHttpMessageNotReadableException(Exception e) {
        //in case of wrong value in manifest for RecoveryAction the message contains the class name.
        //The wrong value is in also part of this messages
        //within the pattern of: String value '<WRONG_VALUE>': value not
        //so we use regex to find the wrong value
        if (e.getMessage().contains(OperationalEnvironmentRecoveryAction.class.getName())) {
            LOGGER.error(EELFLoggerDelegate.errorLogger, "{}: {}", getMethodName(), ExceptionUtils.getMessage(e), e);
            String message = "Wrong value for RecoveryAction in manifest. Allowed options are: "+OperationalEnvironmentRecoveryAction.options;

            Matcher matcher = RECOVERY_ACTION_MESSAGE_PATTERN.matcher(e.getMessage());
            if (matcher.find()) {
                String wrongValue = matcher.group(1);
                message = message+". Wrong value is: "+wrongValue;
            }
            return new ExceptionResponse(new BadManifestException(message));
        }
        return exceptionHandler(e);
    }


    public enum OperationalEnvironmentRecoveryAction {
        abort,
        retry,
        skip;

        public static final String options = Stream.of(OperationalEnvironmentRecoveryAction.values()).map(OperationalEnvironmentRecoveryAction::name).collect(Collectors.joining(", "));
    }

    public static class ActivateServiceModel {
        private String serviceModelVersionId;
        private OperationalEnvironmentRecoveryAction recoveryAction;

        public ActivateServiceModel() {
        }

        public ActivateServiceModel(String serviceModelVersionId, OperationalEnvironmentRecoveryAction recoveryAction) {
            this.serviceModelVersionId = serviceModelVersionId;
            this.recoveryAction = recoveryAction;
        }

        public String getServiceModelVersionId() {
            return serviceModelVersionId;
        }

        public void setServiceModelVersionId(String serviceModelVersionId) {
            this.serviceModelVersionId = serviceModelVersionId;
        }

        public OperationalEnvironmentRecoveryAction getRecoveryAction() {
            return recoveryAction;
        }

        public void setRecoveryAction(OperationalEnvironmentRecoveryAction recoveryAction) {
            this.recoveryAction = recoveryAction;
        }
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class OperationalEnvironmentManifest {


        private List<ActivateServiceModel> serviceModelList;

        public OperationalEnvironmentManifest() {
        }

        public OperationalEnvironmentManifest(List<ActivateServiceModel> serviceModelList) {
            this.serviceModelList = serviceModelList;
        }

        public List<ActivateServiceModel> getServiceModelList() {
            return serviceModelList;
        }

        public void setServiceModelList(List<ActivateServiceModel> serviceModelList) {
            this.serviceModelList = serviceModelList;
        }
    }

    public static class OperationalEnvironmentActivateBody {
        private final String relatedInstanceId;
        private final String relatedInstanceName;
        private final String workloadContext;
        private final OperationalEnvironmentManifest manifest;

        public OperationalEnvironmentActivateBody(@JsonProperty(value = "relatedInstanceId", required = true) String relatedInstanceId,
                                                  @JsonProperty(value = "relatedInstanceName", required = true) String relatedInstanceName,
                                                  @JsonProperty(value = "workloadContext", required = true) String workloadContext,
                                                  @JsonProperty(value = "manifest", required = true) OperationalEnvironmentManifest manifest) {
            this.relatedInstanceId = relatedInstanceId;
            this.relatedInstanceName = relatedInstanceName;
            this.workloadContext = workloadContext;
            this.manifest = manifest;
        }


        public String getRelatedInstanceId() {
            return relatedInstanceId;
        }

        public String getRelatedInstanceName() {
            return relatedInstanceName;
        }

        public String getWorkloadContext() {
            return workloadContext;
        }

        public OperationalEnvironmentManifest getManifest() {
            return manifest;
        }

        @Override
        public String toString() {
            return MoreObjects.toStringHelper(this)
                    .add("relatedInstanceId", relatedInstanceId)
                    .add("relatedInstanceName", relatedInstanceName)
                    .add("workloadContext", workloadContext)
                    .add("manifest", manifest)
                    .toString();
        }
    }

    public static class OperationalEnvironmentCreateBody {
        private final String instanceName;
        private final String ecompInstanceId;
        private final String ecompInstanceName;
        private final String operationalEnvironmentType;
        private final String tenantContext;
        private final String workloadContext;

        public OperationalEnvironmentCreateBody(@JsonProperty(value = "instanceName", required = true) String instanceName,
                                                @JsonProperty(value = "ecompInstanceId", required = true) String ecompInstanceId,
                                                @JsonProperty(value = "ecompInstanceName", required = true) String ecompInstanceName,
                                                @JsonProperty(value = "operationalEnvironmentType", required = true) String operationalEnvironmentType,
                                                @JsonProperty(value = "tenantContext", required = true) String tenantContext,
                                                @JsonProperty(value = "workloadContext", required = true) String workloadContext) {
            this.instanceName = instanceName;
            this.ecompInstanceId = ecompInstanceId;
            this.ecompInstanceName = ecompInstanceName;
            this.operationalEnvironmentType = operationalEnvironmentType;
            this.tenantContext = tenantContext;
            this.workloadContext = workloadContext;
        }

        public String getInstanceName() {
            return instanceName;
        }

        public String getEcompInstanceId() {
            return ecompInstanceId;
        }

        public String getEcompInstanceName() {
            return ecompInstanceName;
        }

        public String getOperationalEnvironmentType() {
            return operationalEnvironmentType;
        }

        public String getTenantContext() {
            return tenantContext;
        }

        public String getWorkloadContext() {
            return workloadContext;
        }

        @Override
        public String toString() {
            return MoreObjects.toStringHelper(this)
                    .add("instanceName", instanceName)
                    .add("ecompInstanceId", ecompInstanceId)
                    .add("ecompInstanceName", ecompInstanceName)
                    .add("operationalEnvironmentType", operationalEnvironmentType)
                    .add("tenantContext", tenantContext)
                    .add("workloadContext", workloadContext)
                    .toString();
        }
    }

    private void debugEnd(HttpResponse<RequestReferencesContainer> msoResponse) {
        LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodCallerName(), msoResponse);
    }

    private void debugStart(Object requestInfo) {
        LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodCallerName(), requestInfo);
    }

    private void verifyIsNotEmpty(String fieldValue, String fieldName) throws MissingServletRequestParameterException {
        if (StringUtils.isEmpty(fieldValue)) {
            throw new MissingServletRequestParameterException(fieldName, "String");
        }
    }

    public static class BadManifestException extends RuntimeException {
        public BadManifestException(String message) {
            super(message);
        }
    }

}