2 * Copyright © 2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.onap.sdc.workflow.api;
19 import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
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;
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;
47 @Component("ArtifactAssociationHandler")
48 public class ArtifactAssociationService {
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;
67 private RestTemplate restClient;
70 public ArtifactAssociationService(RestTemplateBuilder builder) {
71 this.restClient = builder.build();
74 void setRestClient(RestTemplate restClient) {
75 this.restClient = restClient;
78 void setSdcBeEndpoint(String value) {
79 this.sdcBeEndpoint = value;
82 ResponseEntity<String> execute(String userId, ArtifactDeliveriesRequestDto deliveriesRequestDto,
83 ArtifactEntity artifactEntity) {
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()));
91 String formattedArtifact;
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());
99 HttpEntity<String> request = new HttpEntity<>(formattedArtifact, createHeaders(userId,formattedArtifact));
101 return restClient.exchange(sdcBeProtocol + "://" + sdcBeEndpoint + "/" + deliveriesRequestDto.getEndpoint(),
102 HttpMethod.valueOf(deliveriesRequestDto.getMethod()), request, String.class);
105 Optional<String> parametersInitializationState() {
106 ArrayList<String> result = new ArrayList<>();
107 if (sdcBeEndpoint == null || sdcBeEndpoint.equals("")) {
108 result.add("SDC_ENDPOINT");
110 if (sdcBeProtocol == null || sdcBeProtocol.equals("")) {
111 result.add("SDC_PROTOCOL");
113 if (sdcUser == null || sdcUser.equals("")) {
114 result.add("SDC_USER");
116 if (sdcPassword == null || sdcPassword.equals("")) {
117 result.add("SDC_PASSWORD");
120 if (result.isEmpty()) {
121 return Optional.empty();
123 return Optional.of(result.toString());
128 private String getFormattedWorkflowArtifact(ArtifactEntity artifactEntity) throws IOException {
130 byte[] encodeBase64 = Base64.encodeBase64(IOUtils.toByteArray(artifactEntity.getArtifactData()));
131 String encodedPayloadData = new String(encodeBase64);
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);
139 ObjectMapper mapper = new ObjectMapper();
140 return mapper.writeValueAsString(artifactInfo);
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");
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);
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);