095b544cbba795b55dfba1029d8923cce408e9a2
[policy/gui.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020-2022, 2024 Nordix Foundation
4  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
5  *  Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
6  *  ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.gui.editors.apex.rest.handling.plugin.upload;
23
24 import java.nio.charset.StandardCharsets;
25 import java.util.Base64;
26 import org.apache.commons.lang3.StringUtils;
27 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
28 import org.onap.policy.apex.model.modelapi.ApexApiResult;
29 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
30 import org.slf4j.ext.XLogger;
31 import org.slf4j.ext.XLoggerFactory;
32 import org.springframework.beans.factory.annotation.Autowired;
33 import org.springframework.beans.factory.annotation.Value;
34 import org.springframework.http.HttpEntity;
35 import org.springframework.http.HttpHeaders;
36 import org.springframework.http.MediaType;
37 import org.springframework.stereotype.Service;
38 import org.springframework.web.client.HttpStatusCodeException;
39 import org.springframework.web.client.RestTemplate;
40
41 /**
42  * Handles the Policy Model upload.
43  */
44 @Service
45 public class PolicyUploadHandler {
46     private static final XLogger LOGGER = XLoggerFactory.getXLogger(PolicyUploadHandler.class);
47
48     @Value("${apex-editor.upload-url:}")
49     private String uploadUrl;
50
51     @Value("${apex-editor.upload-userid:}")
52     private String defaultUserId;
53
54     private final RestTemplate policyUploadRestTemplate;
55
56     // Recurring string constants
57     private static final String MODEL_UPLOAD_OK = "Model/Upload: OK";
58     private static final String MODEL_UPLOAD_NOT_OK = "Model/Upload: NOT OK";
59
60     @Autowired
61     public PolicyUploadHandler(RestTemplate policyUploadRestTemplate) {
62         this.policyUploadRestTemplate = policyUploadRestTemplate;
63     }
64
65     /**
66      * Handles the policy model upload converting it to TOSCA with given template files.
67      *
68      * @param toscaServiceTemplate the TOSCA service template
69      * @param policyModelKey       the key of the policy model
70      * @param policyModelUuid      the UUID of the policy model
71      * @param uploadUserId         the userId to use for upload. If blank, the Spring
72      *                             config parameter "apex-editor.upload-userid" is used.
73      * @return the result of the upload process
74      */
75     public ApexApiResult doUpload(final String toscaServiceTemplate, final AxArtifactKey policyModelKey,
76                                   final String policyModelUuid, String uploadUserId) {
77         LOGGER.entry();
78
79         if (StringUtils.isBlank(uploadUrl)) {
80             final var apexApiResult = new ApexApiResult(Result.FAILED);
81             apexApiResult.addMessage("Model upload is disabled, parameter upload-url is not set on server");
82             LOGGER.exit(MODEL_UPLOAD_NOT_OK);
83             return apexApiResult;
84         }
85
86         if (StringUtils.isBlank(uploadUserId)) {
87             uploadUserId = defaultUserId;
88         }
89
90         final var uploadPolicyRequestDto = new UploadPolicyRequestDto();
91         uploadPolicyRequestDto.setUserId(uploadUserId);
92         uploadPolicyRequestDto
93             .setFileData(Base64.getEncoder().encodeToString(toscaServiceTemplate.getBytes(StandardCharsets.UTF_8)));
94         uploadPolicyRequestDto.setFilename(
95             String.format("%s.%s.%s", policyModelUuid, policyModelKey.getName(), policyModelKey.getVersion()));
96
97         try {
98             var headers = new HttpHeaders();
99             headers.setContentType(MediaType.APPLICATION_JSON);
100             var request = new HttpEntity<>(uploadPolicyRequestDto, headers);
101             policyUploadRestTemplate.postForObject(uploadUrl, request, String.class);
102
103             final var apexApiResult = new ApexApiResult(Result.SUCCESS);
104             apexApiResult.addMessage(
105                 String.format("uploading Policy '%s' to URL '%s' with userId '%s' was successful",
106                     policyModelKey.getId(), uploadUrl, uploadUserId));
107             LOGGER.exit(MODEL_UPLOAD_OK);
108             return apexApiResult;
109
110         } catch (HttpStatusCodeException e) {
111             final var apexApiResult = new ApexApiResult(Result.FAILED);
112             apexApiResult.addMessage(
113                 String.format("uploading Policy '%s' to URL '%s' with userId '%s' failed with status %d",
114                     policyModelKey.getId(), uploadUrl, uploadUserId, e.getStatusCode().value()));
115             LOGGER.exit(MODEL_UPLOAD_NOT_OK);
116             return apexApiResult;
117
118         } catch (Exception e) {
119             final var apexApiResult = new ApexApiResult(Result.FAILED);
120             apexApiResult.addMessage(
121                 String.format("uploading Policy '%s' to URL '%s' with userId '%s' failed with error %s",
122                     policyModelKey.getId(), uploadUrl, uploadUserId, e.getMessage()));
123             LOGGER.exit(MODEL_UPLOAD_NOT_OK);
124             return apexApiResult;
125         }
126     }
127 }