Associate Artifact Test
[sdc/sdc-workflow-designer.git] / workflow-designer-be / src / main / java / org / onap / sdc / workflow / api / ArtifactAssociationService.java
1 /*
2  * Copyright © 2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.sdc.workflow.api;
18
19 import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
20
21 import com.fasterxml.jackson.databind.ObjectMapper;
22 import java.io.IOException;
23 import java.nio.charset.Charset;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.Optional;
28 import org.apache.commons.codec.binary.Base64;
29 import org.apache.commons.io.IOUtils;
30 import org.onap.sdc.workflow.api.types.dto.ArtifactDeliveriesRequestDto;
31 import org.onap.sdc.workflow.persistence.types.ArtifactEntity;
32 import org.openecomp.sdc.logging.api.Logger;
33 import org.openecomp.sdc.logging.api.LoggerFactory;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.beans.factory.annotation.Value;
36 import org.springframework.boot.web.client.RestTemplateBuilder;
37 import org.springframework.http.HttpEntity;
38 import org.springframework.http.HttpHeaders;
39 import org.springframework.http.HttpMethod;
40 import org.springframework.http.HttpStatus;
41 import org.springframework.http.MediaType;
42 import org.springframework.http.ResponseEntity;
43 import org.springframework.stereotype.Component;
44 import org.springframework.web.client.RestTemplate;
45
46
47 @Component("ArtifactAssociationHandler")
48 public class ArtifactAssociationService {
49
50     private static final String WORKFLOW_ARTIFACT_TYPE = "WORKFLOW";
51     private static final String WORKFLOW_ARTIFACT_DESCRIPTION = "Workflow Artifact Description";
52     private static final String USER_ID_HEADER = "USER_ID";
53     private static final String MD5_HEADER = "Content-MD5";
54     private static final String X_ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID";
55     private static final String INIT_ERROR_MSG =
56             "Failed while attaching workflow artifact to Operation in SDC. Parameters were not initialized: %s";
57     private static final Logger LOGGER = LoggerFactory.getLogger(ArtifactAssociationService.class);
58     @Value("${sdc.be.endpoint}")
59     private String sdcBeEndpoint;
60     @Value("${sdc.be.protocol}")
61     private String sdcBeProtocol;
62     @Value("${sdc.be.external.user}")
63     private String sdcUser;
64     @Value("${sdc.be.external.password}")
65     private String sdcPassword;
66
67     private RestTemplate restClient;
68
69     @Autowired
70     public ArtifactAssociationService(RestTemplateBuilder builder) {
71         this.restClient = builder.build();
72     }
73
74      void setRestClient(RestTemplate restClient) {
75         this.restClient = restClient;
76     }
77
78     void setSdcBeEndpoint(String value) {
79         this.sdcBeEndpoint = value;
80     }
81
82     ResponseEntity<String> execute(String userId, ArtifactDeliveriesRequestDto deliveriesRequestDto,
83             ArtifactEntity artifactEntity) {
84
85         Optional<String> initializationState = parametersInitializationState();
86         if(initializationState.isPresent()) {
87             LOGGER.error(String.format(INIT_ERROR_MSG,initializationState.get()));
88             return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(String.format(INIT_ERROR_MSG,initializationState.get()));
89         }
90
91         String formattedArtifact;
92         try {
93             formattedArtifact = getFormattedWorkflowArtifact(artifactEntity);
94         } catch (IOException e) {
95             LOGGER.error("Failed while attaching workflow artifact to Operation in SDC", e);
96             return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(e.getMessage());
97         }
98
99         HttpEntity<String> request = new HttpEntity<>(formattedArtifact, createHeaders(userId,formattedArtifact));
100
101         return restClient.exchange(sdcBeProtocol + "://" + sdcBeEndpoint + "/" + deliveriesRequestDto.getEndpoint(),
102                 HttpMethod.valueOf(deliveriesRequestDto.getMethod()), request, String.class);
103     }
104
105     Optional<String> parametersInitializationState() {
106         ArrayList<String> result = new ArrayList<>();
107         if (sdcBeEndpoint == null || sdcBeEndpoint.equals("")) {
108             result.add("SDC_ENDPOINT");
109         }
110         if (sdcBeProtocol == null || sdcBeProtocol.equals("")) {
111             result.add("SDC_PROTOCOL");
112         }
113         if (sdcUser == null || sdcUser.equals("")) {
114             result.add("SDC_USER");
115         }
116         if (sdcPassword == null || sdcPassword.equals("")) {
117             result.add("SDC_PASSWORD");
118         }
119
120         if (result.isEmpty()) {
121             return Optional.empty();
122         } else {
123             return Optional.of(result.toString());
124         }
125     }
126
127
128     private String getFormattedWorkflowArtifact(ArtifactEntity artifactEntity) throws IOException {
129
130         byte[] encodeBase64 = Base64.encodeBase64(IOUtils.toByteArray(artifactEntity.getArtifactData()));
131         String encodedPayloadData = new String(encodeBase64);
132
133         Map<String, String> artifactInfo = new HashMap<>();
134         artifactInfo.put("artifactName", artifactEntity.getFileName());
135         artifactInfo.put("payloadData", encodedPayloadData);
136         artifactInfo.put("artifactType", WORKFLOW_ARTIFACT_TYPE);
137         artifactInfo.put("description", WORKFLOW_ARTIFACT_DESCRIPTION);
138
139         ObjectMapper mapper = new ObjectMapper();
140         return mapper.writeValueAsString(artifactInfo);
141     }
142
143     private HttpHeaders createHeaders(String userId, String formattedArtifact) {
144         HttpHeaders headers = new HttpHeaders();
145         headers.add(USER_ID_HEADER, userId);
146         headers.add(HttpHeaders.AUTHORIZATION, createAuthorizationsHeaderValue(sdcUser,sdcPassword));
147         headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
148         headers.add(MD5_HEADER, calculateMD5Base64EncodedByString(formattedArtifact));
149         headers.add(X_ECOMP_INSTANCE_ID_HEADER, "InstanceId");
150         return headers;
151     }
152
153     private String calculateMD5Base64EncodedByString(String data) {
154         String calculatedMd5 = md5Hex(data);
155         // encode base-64 result
156         byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes());
157         return new String(encodeBase64);
158     }
159
160     private String createAuthorizationsHeaderValue(String username, String password) {
161         String auth = username + ":" + password;
162         byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
163         return "Basic " + new String(encodedAuth);
164     }
165 }